diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index 65f2b4c16ea42ecdf37082a5a9f8e26eb20dd6e6..79230cf32f010ee568575817643996f15b0bf007 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -17,11 +17,10 @@ - ExtensionAbility Component - [ExtensionAbility Component Overview](extensionability-overview.md) - [ServiceExtensionAbility](serviceextensionability.md) - - [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [InputMethodExtensionAbility](inputmethodextentionability.md) - - [WindowExtensionAbility](windowextensionability.md) + - [WindowExtensionAbility (for System Applications Only)](windowextensionability.md) - Service Widget Development in Stage Model - [Service Widget Overview](service-widget-overview.md) - Developing an ArkTS Widget @@ -37,9 +36,9 @@ - [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md) - Widget Event Development - [Widget Event Capability Overview](arkts-ui-widget-event-overview.md) + - [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) - [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md) - [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md) - - [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) - Widget Data Interaction - [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md) - [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md) @@ -53,7 +52,7 @@ - [Want Overview](want-overview.md) - [Matching Rules of Explicit Want and Implicit Want](explicit-implicit-want-mappings.md) - [Common action and entities Values](actions-entities.md) - - [Using Explicit Want to Start an Ability](ability-startup-with-explicit-want.md) + - [Using Explicit Want to Start an Application Component](ability-startup-with-explicit-want.md) - [Using Implicit Want to Open a Website](ability-startup-with-implicit-want.md) - [Using Want to Share Data Between Applications](data-share-via-want.md) - [Component Startup Rules](component-startup-rules.md) @@ -62,8 +61,8 @@ - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md) - [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md) - [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md) - - IPC - - [Process Model](process-model-stage.md) + - Process Model + - [Process Model Overview](process-model-stage.md) - Common Events - [Introduction to Common Events](common-event-overview.md) - Common Event Subscription @@ -72,15 +71,15 @@ - [Subscribing to Common Events in Static Mode (for System Applications Only)](common-event-static-subscription.md) - [Unsubscribing from Common Events](common-event-unsubscription.md) - [Publishing Common Events](common-event-publish.md) - - [Removing Sticky Common Events](common-event-remove-sticky.md) + - [Removing Sticky Common Events (for System Applications Only)](common-event-remove-sticky.md) - [Background Services](background-services.md) - - Inter-Thread Communication - - [Thread Model](thread-model-stage.md) + - Thread Model + - [Thread Model Overview](thread-model-stage.md) - [Using Emitter for Inter-Thread Communication](itc-with-emitter.md) - [Using Worker for Inter-Thread Communication](itc-with-worker.md) - Mission Management - [Mission Management Scenarios](mission-management-overview.md) - - [Mission Management and Launch Type](mission-management-launch-type.md) + - [Mission and Launch Type](mission-management-launch-type.md) - [Page Stack and MissionList](page-mission-stack.md) - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - [Application Configuration File](config-file-stage.md) @@ -120,12 +119,12 @@ - [Context](application-context-fa.md) - [Want](want-fa.md) - [Component Startup Rules](component-startup-rules-fa.md) - - IPC - - [Process Model](process-model-fa.md) + - Process Model + - [Process Model Overview](process-model-fa.md) - [Common Events](common-event-fa.md) - [Background Services](rpc.md) - - Inter-Thread Communication - - [Thread Model](thread-model-fa.md) + - Thread Model + - [Thread Model Overview](thread-model-fa.md) - [Inter-Thread Communication](itc-fa-overview.md) - [Mission Management](mission-management-fa.md) - [Application Configuration File](config-file-fa.md) diff --git a/en/application-dev/application-models/ability-startup-with-explicit-want.md b/en/application-dev/application-models/ability-startup-with-explicit-want.md index 6b61b06311a519e959e87d826e4a27c8b2b3d208..36d41c555bd8d4a5cd0d4d0b7bd291bb2569cee3 100644 --- a/en/application-dev/application-models/ability-startup-with-explicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-explicit-want.md @@ -1,4 +1,4 @@ -# Using Explicit Want to Start an Ability +# Using Explicit Want to Start an Application Component When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used. diff --git a/en/application-dev/application-models/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md index dbd65bb560d7531bb6e00b21c004815fda1a997c..7d92fbccbd1ebb49dc2a89de0ea825a1e2a8c873 100644 --- a/en/application-dev/application-models/ability-startup-with-implicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md @@ -5,21 +5,21 @@ This section uses the operation of using a browser to open a website as an examp ```json { "module": { - // ... + ... "abilities": [ { - // ... + ... "skills": [ { "entities": [ "entity.system.home", "entity.system.browsable" - // ... + ... ], "actions": [ "action.system.home", "ohos.want.action.viewData" - // ... + ... ], "uris": [ { @@ -31,9 +31,9 @@ This section uses the operation of using a browser to open a website as an examp }, { "scheme": "http", - // ... + ... } - // ... + ... ] } ] @@ -59,19 +59,18 @@ function implicitStartAbility() { 'uri': 'https://www.test.com:8080/query/student' } context.startAbility(wantInfo).then(() => { - // ... + ... }).catch((err) => { - // ... + ... }) } ``` The matching process is as follows: -1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the ability to match, the matching is successful. -2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the ability to match, the matching is successful. -3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful. -4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful. +1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the application component to match, the matching is successful. +2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the application component to match, the matching is successful. +3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the application component to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful. If there are multiple matching applications, the system displays a dialog box for you to select one of them. The following figure shows an example. diff --git a/en/application-dev/application-models/abilitystage.md b/en/application-dev/application-models/abilitystage.md index 769c6b4540856a553ca30f02c0a689e1c32f2307..da764a445a6d1a79a601719f069798191641a986 100644 --- a/en/application-dev/application-models/abilitystage.md +++ b/en/application-dev/application-models/abilitystage.md @@ -24,7 +24,7 @@ AbilityStage is not automatically generated in the default project of DevEco Stu // When the HAP of the application is loaded for the first time, initialize the module. } onAcceptWant(want) { - // Triggered only for the ability with the specified launch type. + // Triggered only for the UIAbility with the specified launch type. return "MyAbilityStage"; } } @@ -37,7 +37,7 @@ AbilityStage is not automatically generated in the default project of DevEco Stu "name": "entry", "type": "entry", "srcEntry": "./ets/myabilitystage/MyAbilityStage.ts", - // ... + ... } } ``` diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md index 5c5aed302c6f8f570238fac6bd73c263840244d6..38119a1b1fe16067f7e89629811327ad079a5d15 100644 --- a/en/application-dev/application-models/actions-entities.md +++ b/en/application-dev/application-models/actions-entities.md @@ -1,9 +1,8 @@ # Common action and entities Values -**action**: Action to take, such as viewing, sharing, and application details, by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. +The **action** field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit [Want](../reference/apis/js-apis-app-ability-want.md), you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the application component that supports website viewing is matched. Declaring the **action** field in [Want](../reference/apis/js-apis-app-ability-want.md) indicates that the invoked application is expected to support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. - -**Common action Values** +The following **action** values are available: - **ACTION_HOME**: action of starting the application entry component. It must be used together with **ENTITY_HOME**. The application icon on the home screen is an explicit entry component. Users can touch the icon to start the entry component. Multiple entry components can be configured for an application. @@ -14,14 +13,13 @@ - **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records. -**entities**: Category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. - +The **entities** field specify the category information (such as browser and video player) of the target application component. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. -**Common entities Values** +The following **entities** values are available: - **ENTITY_DEFAULT**: default category, which is meaningless. -- **ENTITY_HOME**: abilities with an icon displayed on the home screen. +- **ENTITY_HOME**: application components with an icon displayed on the home screen. - **ENTITY_BROWSABLE**: browser type. diff --git a/en/application-dev/application-models/app-deviceconfig-switch.md b/en/application-dev/application-models/app-deviceconfig-switch.md index 1092c21081cd9a8d62c92a1a68ba434efee7c8c9..6c872f0c167bd4779516d611ee07d9036ca550ee 100644 --- a/en/application-dev/application-models/app-deviceconfig-switch.md +++ b/en/application-dev/application-models/app-deviceconfig-switch.md @@ -22,7 +22,7 @@ OpenHarmony has reconstructed the [deviceConfig](../quick-start/deviceconfig-str | deviceConfig in the FA Model| Description| Stage Model| Difference| | -------- | -------- | -------- | -------- | | deviceConfig| Device information.| / | This tag is no longer available in the stage model. In the stage model, device information is configured under the **app** tag.| -| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process.| / | The stage model does not support the configuration of process names.| +| process | Name of the process running the application or UIAbility. If the **process** attribute is configured in the **deviceConfig** tag, all UIAbilities of the application run in this process. You can set the **process** attribute for a specific UIAbility in the **abilities** attribute, so that the UIAbility can run in the particular process.| / | The stage model does not support the configuration of process names.| | keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications.| / | The stage model does not support changing of the model control mode for system applications.| | supportBackup | Whether the application supports data backup and restore.| / | This configuration is not supported in the stage model.| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.| / | This configuration is not supported in the stage model.| diff --git a/en/application-dev/application-models/application-component-configuration-fa.md b/en/application-dev/application-models/application-component-configuration-fa.md index 4cc1c9ad6831f0e54ae4c70f4f7229a7abc7c62f..336ad698d0f2298045b00fe0af1563574bccfd24 100644 --- a/en/application-dev/application-models/application-component-configuration-fa.md +++ b/en/application-dev/application-models/application-component-configuration-fa.md @@ -22,7 +22,7 @@ When developing an application, you may need to configure certain tags to identi "actions": ["action.system.home"] } ] - // ... + ... } ``` diff --git a/en/application-dev/application-models/application-component-configuration-stage.md b/en/application-dev/application-models/application-component-configuration-stage.md index bcf9b095464ba0110c35be9cfef44b078a091ffb..b50d40b4a694ecdf55338d249a20ff458d36ba20 100644 --- a/en/application-dev/application-models/application-component-configuration-stage.md +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -1,10 +1,12 @@ # Application- or Component-Level Configuration (Stage Model) +When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. -When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. +Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). +The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and entry labels. When you touch one of them, the corresponding UIAbility page is displayed. - **Figure 1** Icons and labels +**Figure 1** Icons and labels ![application-component-configuration-stage](figures/application-component-configuration-stage.png) @@ -22,13 +24,13 @@ When developing an application, you may need to configure certain tags to identi The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. ```json - { - "app": { - "icon": "$media:app_icon", - "label": "$string:app_name" - // ... - } + { + "app": { + "icon": "$media:app_icon", + "label": "$string:app_name" + ... } + } ``` - **Configuring the entry icon and label** @@ -40,7 +42,7 @@ When developing an application, you may need to configure certain tags to identi ```json { "module": { - // ... + ... "abilities": [ { // The information starting with $ is the resource value. @@ -61,6 +63,35 @@ When developing an application, you may need to configure certain tags to identi } } ``` + OpenHarmony strictly controls applications without icons to prevent malicious applications from deliberately configuring no icon to block uninstall attempts. + + To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). The rules for displaying the entry icon and entry label are as follows: + + 1. The HAP file contains UIAbility configuration. + * An entry icon is set in the **abilities** field of the **module.json5** file. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon configured for the UIAbility as the entry icon and displays it on the home screen. Touching this icon will direct the user to the home page of the UIAbility. + * The system uses the label configured for the UIAbility as the entry label and displays it on the home screen. If no label is configured, the system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + * No entry icon is set in the **abilities** field of the **module.json5** file. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. + * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + + 2. The HAP file does not contain UIAbility configuration. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. + * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + + **Figure 2** Application details page + + ![Application details page](figures/application_details.jpg) + - **Configuring application version declaration** To declare the application version, configure the **versionCode** and **versionName** fields in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. **versionCode** specifies the version number of the application. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version. **versionName** provides the text description of the version number. diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index 3fc6df944c5b9b137c585f59a8f83cd61db226f9..2063eee286c25e360a1700d3e1771d865b875f1c 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -1,19 +1,16 @@ # Context (Stage Model) - ## Overview -[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encryption level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. +[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. - The figure below illustrates the inheritance relationship of contexts. - ![context-inheritance](figures/context-inheritance.png) - + - The figure below illustrates the holding relationship of contexts. - ![context-holding](figures/context-holding.png) -- The following describes the information provided by different contexts. +The following describes the information provided by different contexts. - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more. ```ts @@ -21,7 +18,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let uiAbilityContext = this.context; - // ... + ... } } ``` @@ -36,7 +33,7 @@ export default class MyService extends ServiceExtensionAbility { onCreate(want) { let serviceExtensionContext = this.context; - // ... + ... } } ``` @@ -47,7 +44,7 @@ export default class MyAbilityStage extends AbilityStage { onCreate() { let abilityStageContext = this.context; - // ... + ... } } ``` @@ -58,7 +55,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let applicationContext = this.context.getApplicationContext(); - // ... + ... } } ``` @@ -84,13 +81,13 @@ The following table describes the application development paths obtained from co | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. Do not access resource files by concatenating paths. Use [@ohos.resourceManager] instead. | -| cacheDir | string | Yes| No| Path for storing the application's cache files, that is, cache directory of the application on the internal storage.
It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| -| filesDir | string | Yes | No | Path for storing the application's common files, that is, file directory of the application on the internal storage.
Files in this directory may be synchronized to other directories during application migration or backup.| -| preferencesDir | string | Yes | Yes | Path for storing the application's preference files, that is, preferences directory of the application. | -| tempDir | string | Yes | No | Path for storing the application's temporary files.
Files in this directory are deleted after the application is uninstalled.| +| bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. | +| cacheDir | string | Yes| No| Path for storing the cache files, that is, cache directory of the application on the internal storage.
It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| +| filesDir | string | Yes | No | Path for storing the common files, that is, file directory of the application on the internal storage.
Files in this directory may be synchronized to other directories during application migration or backup.| +| preferencesDir | string | Yes | Yes | Path for storing the preference files, that is, preferences directory of the application. | +| tempDir | string | Yes | No | Path for storing the temporary files.
Files in this directory are deleted after the application is uninstalled.| | databaseDir | string | Yes | No | Path for storing the application's database, that is, storage directory of the local database. | -| distributedFilesDir | string | Yes| No| Path for storing the application's distributed files.| +| distributedFilesDir | string | Yes| No| Path for storing the distributed files.| The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below. @@ -135,7 +132,7 @@ export default class EntryAbility extends UIAbility { let bundleCodeDir = this.context.bundleCodeDir; let distributedFilesDir = this.context.distributedFilesDir; let preferencesDir = this.context.preferencesDir; - // ... + ... } } ``` @@ -187,13 +184,13 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ > **NOTE** > > To obtain the context of another application: - > + > > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - > + > > - This is a system API and cannot be called by third-party applications. For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -202,7 +199,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ let bundleName2 = 'com.example.application'; let context2 = this.context.createBundleContext(bundleName2); let label2 = context2.applicationInfo.label; - // ... + ... } } ``` @@ -224,7 +221,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ let bundleName2 = 'com.example.application'; let moduleName2 = 'module1'; let context2 = this.context.createModuleContext(bundleName2, moduleName2); - // ... + ... } } ``` @@ -238,7 +235,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ onCreate(want, launchParam) { let moduleName2 = 'module1'; let context2 = this.context.createModuleContext(moduleName2); - // ... + ... } } ``` @@ -266,53 +263,53 @@ export default class EntryAbility extends UIAbility { let abilityLifecycleCallback = { // Called when a UIAbility is created. onAbilityCreate(uiAbility) { - console.log(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when a window is created. onWindowStageCreate(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window becomes active. onWindowStageActive(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window becomes inactive. onWindowStageInactive(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window is destroyed. onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the UIAbility is destroyed. onAbilityDestroy(uiAbility) { - console.log(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when the UIAbility is switched from the background to the foreground. onAbilityForeground(uiAbility) { - console.log(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when the UIAbility is switched from the foreground to the background. onAbilityBackground(uiAbility) { - console.log(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when UIAbility is continued on another device. onAbilityContinue(uiAbility) { - console.log(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); } } // Obtain the application context. let applicationContext = this.context.getApplicationContext(); // Register the application lifecycle callback. this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); - console.log(TAG, `register callback number: ${this.lifecycleId}`); + console.info(TAG, `register callback number: ${this.lifecycleId}`); } - // ... + ... onDestroy() { // Obtain the application context. diff --git a/en/application-dev/application-models/application-model-description.md b/en/application-dev/application-models/application-model-description.md index 0cdfa7323c6ef367a47a44e2c30104d3201ca159..20fa9019d10c8d242e34b309debec78e722e6c27 100644 --- a/en/application-dev/application-models/application-model-description.md +++ b/en/application-dev/application-models/application-model-description.md @@ -12,10 +12,9 @@ Along its evolution, OpenHarmony has provided two application models: The stage model is designed based on the following considerations, which make it become the recommended model: 1. **Designed for complex applications** - - In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory. - The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale. - + 2. **Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level** The stage model decouples application components from User Interfaces (UIs). @@ -38,7 +37,7 @@ The stage model is designed based on the following considerations, which make it The stage model redefines the boundary of application capabilities to well balance application capabilities and system management costs. - - Diverse application components (such as widgets and input methods) for specific scenarios. + - Diverse application components (such as service widgets and input methods) for specific scenarios. - Standardized background process management. To deliver a better user experience, the stage model manages background application processes in a more orderly manner. Applications cannot reside in the background randomly, and their background behavior is strictly managed to minimize malicious behavior. @@ -52,8 +51,8 @@ The table below describes their differences in detail. | Item| FA model| Stage model| | -------- | -------- | -------- | -| **Application component**| 1. Component classification
![fa-model-component](figures/fa-model-component.png)
- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).
- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).
- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).
2. Development mode
Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion. | 1. Component classification
![stage-model-component](figures/stage-model-component.png)
- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).
- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).
2. Development mode
The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion. | -| **Process model**| There are two types of processes:
1. Main process
2. Rendering process
For details, see [Process Model (FA Model)](process-model-fa.md).| There are three types of processes:
1. Main process
2. ExtensionAbility process
3. Rendering process
For details, see [Process Model (Stage Model)](process-model-stage.md).| -| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model (FA Model)](thread-model-fa.md).| 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model (Stage Model)](thread-model-stage.md).| +| **Application component**| 1. Component classification
![fa-model-component](figures/fa-model-component.png)
- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).
- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).
- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).
2. Development mode
Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion.| 1. Component classification
![stage-model-component](figures/stage-model-component.png)
- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).
- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).
2. Development mode
The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion.| +| **Process model**| There are two types of processes:
1. Main process
2. Rendering process
For details, see [Process Model Overview (FA Model)](process-model-fa.md). | There are three types of processes:
1. Main process
2. ExtensionAbility process
3. Rendering process
For details, see [Process Model Overview (Stage Model)](process-model-stage.md). | +| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model Overview (FA Model)](thread-model-fa.md). | 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model Overview (Stage Model)](thread-model-stage.md). | | **Mission management model**| - A mission is created for each PageAbility component instance.
- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.
- PageAbility components do not form a stack structure.
For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.
- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.
- UIAbility components do not form a stack structure.
For details, see [Mission Management Scenarios](mission-management-overview.md).| | **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.
For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.
For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).| diff --git a/en/application-dev/application-models/data-share-via-want.md b/en/application-dev/application-models/data-share-via-want.md index d5512e0c446b94dcf384504f11ff25d458cfeafc..28184edbc9304e7c6fbfbfe673cf1b8deca7d635 100644 --- a/en/application-dev/application-models/data-share-via-want.md +++ b/en/application-dev/application-models/data-share-via-want.md @@ -48,9 +48,9 @@ function implicitStartAbility() { } } context.startAbility(wantInfo).then(() => { - // ... + ... }).catch((err) => { - // ... + ... }) } ``` @@ -66,8 +66,7 @@ In the preceding code, under the custom field **parameters**, the following **ab - **ability.picker.fileSizes**: file size, in bytes. - **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping. -The following figure shows an example. - +The following figure shows an example. ![](figures/ability-startup-with-implicit-want2.png) ## Shared Party @@ -77,17 +76,17 @@ To enable the shared party to identify the shared content, configure **skills** ```json { "module": { - // ... + ... "abilities": [ { - // ... + ... "skills": [ { - // ... + ... "actions": [ "action.system.home", "ohos.want.action.sendData" - // ... + ... ], "uris": [ { @@ -102,7 +101,7 @@ To enable the shared party to identify the shared content, configure **skills** } ``` -After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. The UIAbility of the shared party, after being started, can call [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to obtain the passed Want. +After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. After the UIAbility of the application starts, the application obtains **want** information from [**onCreate()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [**onNewWant()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant). The following is an example of the Want obtained. You can use the FD of the shared file to perform required operations. diff --git a/en/application-dev/application-models/datashareextensionability.md b/en/application-dev/application-models/datashareextensionability.md deleted file mode 100644 index bea3de69c6d7ad375206fb1d53bcc36c2624989d..0000000000000000000000000000000000000000 --- a/en/application-dev/application-models/datashareextensionability.md +++ /dev/null @@ -1,4 +0,0 @@ -# DataShareExtensionAbility (for System Applications Only) - - -DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [Cross-Application Data Sharing Overview](../database/share-device-data-across-apps-overview.md). diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md index 9e748a31795e3afc713e7091067a8164e8a623cc..454fc89d718fb4adfe84c0eab67ebc332117ed26 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -1,28 +1,28 @@ # Matching Rules of Explicit Want and Implicit Want -Both explicit Want and implicit Want can be used to match an ability to start based on certain rules. These rules determine how the parameters set in Want match the configuration file declared by the target ability. +Both explicit [Want](../reference/apis/js-apis-app-ability-want.md) and implicit [Want](../reference/apis/js-apis-app-ability-want.md) can be used to match an application component to start based on certain rules. These rules determine how the parameters set in [want](../reference/apis/js-apis-app-ability-want.md) match the configuration file declared by the target application component. ## Matching Rules of Explicit Want -The table below describes the matching rules of explicit Want. +The table below describes the matching rules of explicit [Want](../reference/apis/js-apis-app-ability-want.md). | Name| Type| Matching Item| Mandatory| Rule Description| | -------- | -------- | -------- | -------- | -------- | -| deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.| +| deviceId | string | Yes| No| If this field is unspecified, only application components on the local device are matched.| | bundleName | string | Yes| Yes| If **abilityName** is specified but **bundleName** is unspecified, the matching fails.| -| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first ability is matched by default.| +| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first application component is matched by default.| | abilityName | string | Yes| Yes| To use explicit Want, this field must be specified.| -| uri | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| type | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| action | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| uri | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| type | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| action | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| | flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| -| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| ## Matching Rules for Implicit Want -The table below describes the matching rules of implicit Want. +The table below describes the matching rules of implicit [Want](../reference/apis/js-apis-app-ability-want.md). | Name | Type | Matching Item| Mandatory| Rule Description | | ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ | @@ -35,30 +35,32 @@ The table below describes the matching rules of implicit Want. | action | string | Yes | No | | | entities | Array<string> | Yes | No | | | flags | number | No | No | This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| -| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target ability as a parameter. | +| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target application component as a parameter. | Get familiar with the following about implicit Want: - The **want** parameter passed by the caller indicates the operation to be performed by the caller. It also provides data and application type restrictions. -- The **skills** field declares the capabilities of the target ability. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md). +- The **skills** field declares the capabilities of the target application component. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md). -The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the abilities one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application. +The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the application components one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application. ### Matching Rules of action in the want Parameter -The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities. +The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the application components. -- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. +- If **action** in the passed **want** parameter is unspecified and **actions** under **skills** of an application component is unspecified, the matching fails. -- If **action** in the passed **want** parameter is unspecified but **actions** under **skills** of an ability is specified, the matching is successful. +- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an application component is unspecified, the matching fails. -- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified and contains **action** in the passed **want** parameter, the matching is successful. +- If **action** in the passed **want** parameter is unspecified but **actions** under **skills** of an application component is specified, the matching is successful. -- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified but does not contain **action** in the passed **want** parameter, the matching fails. +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an application component is specified and contains **action** in the passed **want** parameter, the matching is successful. + +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an application component is specified but does not contain **action** in the passed **want** parameter, the matching fails. **Figure 1** Matching rules of action in the want parameter @@ -67,55 +69,56 @@ The system matches the **action** attribute in the **want** parameter passed by ### Matching Rules of entities in the want Parameter -The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities. +The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the application components. -- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an application component is specified, the matching is successful. -- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is unspecified, the matching is successful. +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an application component is unspecified, the matching is successful. -- If **entities** in the passed **want** parameter is specified but **entities** under **skills** of an ability is unspecified, the matching fails. +- If **entities** in the passed **want** parameter is specified but **entities** under **skills** of an application component is unspecified, the matching fails. -- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified and contains **entities** in the passed **want** parameter, the matching is successful. +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an application component is specified and contains **entities** in the passed **want** parameter, the matching is successful. -- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails. +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an application component is specified but does not contain **entities** in the passed **want** parameter, the matching fails. - **Figure 2** Matching rule of entities in the want parameter + **Figure 2** Matching rules of entities in the want parameter ![want-entities](figures/want-entities.png) ### Matching Rules of uri and type in the want Parameter -When the **uri** and **type** parameters are specified in the **want** parameter to initiate a component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the abilities one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. +When the **uri** and **type** parameters are specified in the **want** parameter to initiate an application component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the application components one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. There are four combinations of **uri** and **type** settings. The matching rules are as follows: - Neither **uri** or **type** is specified in the **want** parameter. - - If the **uris** array under **skills** of an ability is unspecified, the matching is successful. - - If the **uris** array under **skills** of an ability contains an URI element whose **scheme** and **type** are unspecified, the matching is successful. + - If the **uris** array under **skills** of an application component is unspecified, the matching is successful. + - If the **uris** array under **skills** of an application component contains an URI element whose **scheme** and **type** are unspecified, the matching is successful. - In other cases, the matching fails. - Only **uri** is specified in the **want** parameter. - - If the **uris** array under **skills** of an ability is unspecified, the matching fails. - - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and **type** is unspecified, the matching is successful. Otherwise, the matching fails. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an element whose [uri is matched](#matching-rules-of-uri) and **type** is unspecified, the matching is successful. Otherwise, the matching fails. - Only **type** is specified in the **want** parameter. - - If the **uris** array under **skills** of an ability is unspecified, the matching fails. - - If the **uris** array under **skills** of an ability contains an URI element whose **scheme** is unspecified and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an URI element whose **scheme** is unspecified and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. -- Both **uri** and **type** are specified in the **want** parameter, as shown in Figure 3. - - If the **uris** array under **skills** of an ability is unspecified, the matching fails. - - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. +- Both **uri** and **type** are specified in the **want** parameter, as shown below. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. -Leftmost URI matching: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the **uris** array under **skills** of the ability, -the matching is successful only if the leftmost URI in the passed **want** parameter matches **scheme**, the combination of **scheme** and **host**, or the combination of **scheme**, **host**, and **port**. +Leftmost URI matching: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the **uris** array under **skills** of the application component, the matching is successful only if the leftmost URI in the passed **want** parameter matches **scheme**, the combination of **scheme** and **host**, or the combination of **scheme**, **host**, and **port**. **Figure 3** Matching rules when uri and type are specified in the want parameter - ![want-uri-type1](figures/want-uri-type1.png) +![want-uri-type1](figures/want-uri-type1.png) +To simplify the description: -To simplify the description, **uri** and **type** passed in the **want** parameter are called **w_uri** and **w_type**, respectively; the **uris** array under **skills** of an ability to match is called **s_uris**; each element in the array is called **s_uri**. Matching is performed from top to bottom. +- **uri** in the **want** parameter passed in by the caller is called **w_uri**; each element in the **uris** array under **skills** of the application component to match is called **s_uri**. +- **type** in the **want** parameter passed in by the caller is called **w_type**; the type in the **uris** array under **skills** of the application component to match is called **s_type**. **Figure 4** Matching rules of uri and type in the want parameter @@ -124,7 +127,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet ### Matching Rules of uri -To simplify the description, **uri** in the passed **want** parameter is called **w_uri**; **uri** under **skills** of an ability to match is called **s_uri**. The matching rules are as follows: +The rules are as follows: - If **scheme** of **s_uri** is unspecified and **w_uri** is unspecified, the matching is successful. Otherwise, the matching fails. @@ -142,18 +145,15 @@ To simplify the description, **uri** in the passed **want** parameter is called > **NOTE** > -> The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an ability are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions: -> -> - **Full path expression**: `scheme://host:port/path` -> -> - **Prefix expression**: `scheme://host:port/pathStartWith` -> -> - **Regular expression**: `scheme://host:port/pathRegex` +> The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an application component are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions: > > - **Prefix URI expression**: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the configuration file, the matching is successful if a URI prefixed with the configuration file is passed in. > * `scheme://` > * `scheme://host` > * `scheme://host:port` +> - **Full path expression**: `scheme://host:port/path` +> - **Prefix expression**: `scheme://host:port/pathStartWith` +> - **Regular expression**: `scheme://host:port/pathRegex` ### Matching Rules of type @@ -162,7 +162,7 @@ To simplify the description, **uri** in the passed **want** parameter is called > > The matching rules of **type** described in this section are based on the fact that **type** in the **want** parameter is specified. If **type** is unspecified, follow the [matching rules of uri and type in the want parameter](#matching-rules-of-uri-and-type-in-the-want-parameter). -To simplify the description, **uri** in the passed **want** parameter is called **w_type**, and **type** of **uris** under **skills** of an ability to match is called **s_type**. The matching rules are as follows: +The matching rules are as follows: - If **s_type** is unspecified, the matching fails. diff --git a/en/application-dev/application-models/extensionability-overview.md b/en/application-dev/application-models/extensionability-overview.md index d176b2d5322b215ab3d730b59cfc5a8e1f6dfb99..f55686f33a6d37917b8d7ff75d441d6f5c6c921f 100644 --- a/en/application-dev/application-models/extensionability-overview.md +++ b/en/application-dev/application-models/extensionability-overview.md @@ -11,17 +11,17 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab - [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. -- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. +- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which is used to develop input method applications. - [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md): ExtensionAbility component of the service type, which provides APIs related to background service scenarios. - [AccessibilityExtensionAbility](../reference/apis/js-apis-application-accessibilityExtensionAbility.md): ExtensionAbility component of the accessibility type, which provides APIs related to the accessibility feature. -- [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md): ExtensionAbility component of the data_share type, which provides APIs for data sharing. +- [DataShareExtensionAbility (for system applications only)](../reference/apis/js-apis-application-dataShareExtensionAbility.md): ExtensionAbility component of the data_share type, which provides APIs for data sharing. - [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast. -- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows a system application to be embedded in and displayed over another application. +- [WindowExtensionAbility (for system applications only)](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows a system application to be embedded in and displayed over another application. - [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts. @@ -56,13 +56,11 @@ You do not need to care when to add or delete a widget. The lifecycle of the For > **NOTE** > > For an application, all ExtensionAbility components of the same type run in an independent process, whereas UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in another independent process. For details, see [Process Model (Stage Model)](process-model-stage.md). -> +> > For example, an application has one UIAbility component, one ServiceExtensionAbility, one DataShareExtensionAbility, two FormExtensionAbility, and one ImeExtensionAbility. When the application is running, there are three processes: -> +> > - UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in an independent process. -> +> > - The two FormExtensionAbility components run in an independent process. -> +> > - The two ImeExtensionAbility components run in an independent process. - - \ No newline at end of file diff --git a/en/application-dev/application-models/fa-model-development-overview.md b/en/application-dev/application-models/fa-model-development-overview.md index 07e7ef8a0bdaea927762c15e4123ae728c026cb7..295e1863556cd37c7bc7e8cb588eaabbb9decb14 100644 --- a/en/application-dev/application-models/fa-model-development-overview.md +++ b/en/application-dev/application-models/fa-model-development-overview.md @@ -8,8 +8,8 @@ During application development based on the Feature Ability (FA) model, the foll | Task| Introduction| Guide| | -------- | -------- | -------- | -| Application component development| Use the PageAbility, ServiceAbility, DataAbility, and widgets of the FA model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- [PageAbility Component](pageability-overview.md)
- [ServiceAbility Component](serviceability-overview.md)
- [DataAbility Component](dataability-overview.md)
- [Widget Development](Widget-development-fa.md)
- [Context](application-context-fa.md)
- [Want](want-fa.md) | -| Inter-process communication (IPC)| Learn the process model and common IPC modes of the FA model.| [Common Events](common-event-fa.md)
[Background Services](rpc.md) | -| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the FA model.| [Inter-Thread Communication](itc-fa-overview.md)| +| Application component development| Use the PageAbility, ServiceAbility, DataAbility, and widgets of the FA model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- [PageAbility Component](pageability-overview.md)
- [ServiceAbility Component](serviceability-overview.md)
- [DataAbility Component](dataability-overview.md)
- [Widget Development](widget-development-fa.md)
- [Context](application-context-fa.md)
- [Want](want-fa.md)| +| Process model| Learn the process model and common IPC modes of the FA model.| [Common Events](common-event-fa.md)
[Background Services](rpc.md)| +| Thread model| Learn the thread model and common inter-thread communication modes of the FA model.| [Inter-Thread Communication](itc-fa-overview.md)| | Mission management| Learn the basic concepts and typical scenarios of mission management in the FA model.| [Mission Management](mission-management-fa.md)| -| Application configuration file| Learn the requirements for developing application configuration files in the FA model.| [Application Configuration File](config-file-fa.md) | +| Application configuration file| Learn the requirements for developing application configuration files in the FA model.| [Application Configuration File](config-file-fa.md)| diff --git a/en/application-dev/application-models/figures/application_details.jpg b/en/application-dev/application-models/figures/application_details.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e849a47b3d10faefafbf76a7b6309da305a2e9b0 Binary files /dev/null and b/en/application-dev/application-models/figures/application_details.jpg differ diff --git a/en/application-dev/application-models/figures/stage-concepts.png b/en/application-dev/application-models/figures/stage-concepts.png index 42e99447a780b167adaf6ddd196bea4437dfa1a7..9d753f27fca4d507da20b5d5060f9b3d28e616b0 100644 Binary files a/en/application-dev/application-models/figures/stage-concepts.png and b/en/application-dev/application-models/figures/stage-concepts.png differ diff --git a/en/application-dev/application-models/figures/want-action.png b/en/application-dev/application-models/figures/want-action.png index 0d8e18ce5870bea777c26b832d3f29674c2fa261..b907e8158bd9fd183ceabb181a13aa813f01e77e 100644 Binary files a/en/application-dev/application-models/figures/want-action.png and b/en/application-dev/application-models/figures/want-action.png differ diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md index c51e82e15f4e14f4b42b25e656543a01d84406fb..418eac519cb62c7339048df4f8663e20df8ef185 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -55,21 +55,21 @@ The table below describes the main APIs used for cross-device migration. For det Configure the application to support migration. Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device. - - - ```json - { - "module": { - // ... - "abilities": [ - { - // ... - "continuable": true, - } - ] - } - } - ``` + + + ```json + { + "module": { + ... + "abilities": [ + { + ... + "continuable": true, + } + ] + } + } + ``` Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). @@ -83,19 +83,19 @@ The table below describes the main APIs used for cross-device migration. For det The sample code is as follows: - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - - onContinue(wantParam : {[key: string]: any}) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) - let workInput = AppStorage.Get('ContinueWork'); - // Set the user input data into wantParam. - wantParam["work"] = workInput // set user input data into want params - console.info(`onContinue input = ${wantParam["input"]}`); - return AbilityConstant.OnContinueResult.AGREE - } - ``` + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + onContinue(wantParam : {[key: string]: any}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + let workInput = AppStorage.Get('ContinueWork'); + // Set the user input data into wantParam. + wantParam["work"] = workInput // set user input data into want params + console.info(`onContinue input = ${wantParam["input"]}`); + return AbilityConstant.OnContinueResult.AGREE + } + ``` 5. Implement **onCreate()** and **onNewWant()** in the UIAbility of the target application to implement data restoration. - Implementation example of **onCreate** in the multi-instance scenario diff --git a/en/application-dev/application-models/hop-multi-device-collaboration.md b/en/application-dev/application-models/hop-multi-device-collaboration.md index b761037182f27367e9c01488de41aaa23b6b25d2..a6e767964e4d1ee83fb1e837b2ddeb55786c9739 100644 --- a/en/application-dev/application-models/hop-multi-device-collaboration.md +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -63,7 +63,7 @@ On device A, touch the **Start** button provided by the initiator application to // createDeviceManager is a system API. deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => { if (err) { - // ... + ... return } dmClass = dm @@ -94,13 +94,13 @@ On device A, touch the **Start** button provided by the initiator application to } // context is the AbilityContext of the initiator UIAbility. this.context.startAbility(want).then(() => { - // ... + ... }).catch((err) => { - // ... + ... }) ``` -5. Call stopServiceExtensionAbility(../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability) to stop the ServiceExtensionAbility when it is no longer required on device B. (This API cannot be used to stop a UIAbility. Users must manually stop a UIAbility through task management.) +5. Call [stopServiceExtensionAbility](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability) to stop the ServiceExtensionAbility when it is no longer required on device B. (This API cannot be used to stop a UIAbility. Users must manually stop a UIAbility through task management.) ```ts let want = { @@ -150,9 +150,9 @@ On device A, touch the **Start** button provided by the initiator application to } // context is the AbilityContext of the initiator UIAbility. this.context.startAbilityForResult(want).then((data) => { - // ... + ... }).catch((err) => { - // ... + ... }) ``` @@ -170,7 +170,7 @@ On device A, touch the **Start** button provided by the initiator application to } // context is the AbilityContext of the target UIAbility. this.context.terminateSelfWithResult(abilityResult, (err) => { - // ... + ... }); ``` @@ -179,17 +179,17 @@ On device A, touch the **Start** button provided by the initiator application to ```ts const RESULT_CODE: number = 1001; - // ... + ... // context is the UIAbilityContext of the initiator UIAbility. this.context.startAbilityForResult(want).then((data) => { if (data?.resultCode === RESULT_CODE) { // Parse the information returned by the target UIAbility. let info = data.want?.parameters?.info - // ... + ... } }).catch((err) => { - // ... + ... }) ``` @@ -444,10 +444,10 @@ The following describes how to implement multi-device collaboration through cros // Register the onRemoteStateChange listener of the CallerAbility. try { caller.onRemoteStateChange((str) => { - console.log('Remote state changed ' + str); + console.info('Remote state changed ' + str); }); } catch (error) { - console.log('Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + console.info('Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } } }).catch((error) => { diff --git a/en/application-dev/application-models/itc-with-emitter.md b/en/application-dev/application-models/itc-with-emitter.md index 2966bd8eea41e04893814f20a3c5b2f9e4e456c9..43a5dc67be7349bb1d51a7e4141920b8739f7beb 100644 --- a/en/application-dev/application-models/itc-with-emitter.md +++ b/en/application-dev/application-models/itc-with-emitter.md @@ -13,12 +13,12 @@ To develop the Emitter mode, perform the following steps: // Define an event with eventId 1. let event = { - eventId: 1 + eventId: 1 }; // Trigger the callback after the event with eventId 1 is received. let callback = (eventData) => { - console.info('event callback'); + console.info('event callback'); }; // Subscribe to the event with eventId 1. @@ -29,21 +29,21 @@ To develop the Emitter mode, perform the following steps: ```ts import emitter from "@ohos.events.emitter"; - + // Define an event with eventId 1 and priority Low. let event = { - eventId: 1, - priority: emitter.EventPriority.LOW + eventId: 1, + priority: emitter.EventPriority.LOW }; - + let eventData = { - data: { - "content": "c", - "id": 1, - "isEmpty": false, - } + data: { + "content": "c", + "id": 1, + "isEmpty": false, + } }; - + // Emit the event with eventId 1 and event content eventData. emitter.emit(event, eventData); ``` diff --git a/en/application-dev/application-models/itc-with-worker.md b/en/application-dev/application-models/itc-with-worker.md index 996ab941b0244571dff6116a45ab5e2165cf1184..1f105d4f0ce31acdf135ab254e7bdb66e30d1ecf 100644 --- a/en/application-dev/application-models/itc-with-worker.md +++ b/en/application-dev/application-models/itc-with-worker.md @@ -9,13 +9,13 @@ To develop the Worker mode, perform the following steps: 1. Configure the **buildOption** field in the [module-level build-profile.json5](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-building-configuration-0000001218440654#section6887184182020) file of the project. ```ts - "buildOption": { - "sourceOption": { - "workers": [ - "./src/main/ets/workers/worker.ts" - ] - } + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] } + } ``` 2. Create the **worker.ts** file based on the configuration in **build-profile.json5**. @@ -27,9 +27,9 @@ To develop the Worker mode, perform the following steps: // Process messages from the main thread. parent.onmessage = function(message) { - console.info("onmessage: " + message) - // Send a message to the main thread. - parent.postMessage("message from worker thread.") + console.info("onmessage: " + message) + // Send a message to the main thread. + parent.postMessage("message from worker thread.") } ``` @@ -46,10 +46,10 @@ To develop the Worker mode, perform the following steps: // Process messages from the worker thread. wk.onmessage = function(message) { - console.info("message from worker: " + message) + console.info("message from worker: " + message) - // Stop the worker thread based on service requirements. - wk.terminate() + // Stop the worker thread based on service requirements. + wk.terminate(); } ``` @@ -57,23 +57,22 @@ To develop the Worker mode, perform the following steps: ```ts import worker from '@ohos.worker'; - + let wk = new worker.ThreadWorker("../workers/worker.ts"); - + // Send a message to the worker thread. wk.postMessage("message from main thread.") - + // Process messages from the worker thread. wk.onmessage = function(message) { - console.info("message from worker: " + message) - - // Stop the worker thread based on service requirements. - wk.terminate() + console.info("message from worker: " + message) + + // Stop the worker thread based on service requirements. + wk.terminate(); } ``` > **NOTE** -> +> > - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.ts** when creating a worker thread in the FA model. -> > - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types). diff --git a/en/application-dev/application-models/mission-management-launch-type.md b/en/application-dev/application-models/mission-management-launch-type.md index 199de6eefead9fc056adf8d08c49f792a54a4a83..56a389cc52e093008491f75e01144bd7635b94eb 100644 --- a/en/application-dev/application-models/mission-management-launch-type.md +++ b/en/application-dev/application-models/mission-management-launch-type.md @@ -1,4 +1,4 @@ -# Mission Management and Launch Type +# Mission and Launch Type One UIAbility instance corresponds to one mission. The number of UIAbility instances is related to the UIAbility launch type, specified by **launchType**, which is configured in the **config.json** file in the FA model and the [module.json5](../quick-start/module-configuration-file.md) file in the stage model. @@ -11,13 +11,13 @@ The following describes how the mission list manager manages the UIAbility insta ![mission-and-singleton](figures/mission-and-singleton.png) -- **multiton**: Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a **UIAbility** instance is created in the application process. +- **multiton**: Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a UIAbility instance is created in the application process. **Figure 2** Missions and multiton mode ![mission-and-multiton](figures/mission-and-multiton.png) -- **specified**: The ([onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)) method of [AbilityStage](abilitystage.md) determines whether to create an instance. +- **specified**: The ([onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)) method of [AbilityStage](abilitystage.md) determines whether to create a UIAbility instance. **Figure 3** Missions and specified mode diff --git a/en/application-dev/application-models/mission-management-overview.md b/en/application-dev/application-models/mission-management-overview.md index ba55ebb136ebffca0294bf69013f2f2ab4392e7f..785a9f8291ea43e756ebed07843ceef23570160d 100644 --- a/en/application-dev/application-models/mission-management-overview.md +++ b/en/application-dev/application-models/mission-management-overview.md @@ -4,7 +4,7 @@ Before getting started with the development of mission management, be familiar with the following concepts related to mission management: -- AbilityRecord: minimum unit for the system service to manage a UIAbility instance. It corresponds to a UIAbility component instance of an application. +- AbilityRecord: minimum unit for the system service to manage a UIAbility instance. It corresponds to a UIAbility component instance of an application. A maximum of 512 UIAbility instances can be managed on the system service side. - MissionRecord: minimum unit for mission management. One MissionRecord has only one AbilityRecord. In other words, a UIAbility component instance corresponds to a mission. @@ -30,42 +30,42 @@ Missions are managed by system applications (such as home screen), rather than t A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created. -To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). +1. To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). -You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. +2. You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. ```ts import missionManager from '@ohos.app.ability.missionManager' let listener = { - // Listen for mission creation. - onMissionCreated: function (mission) { - console.info("--------onMissionCreated-------") - }, - // Listen for mission destruction. - onMissionDestroyed: function (mission) { - console.info("--------onMissionDestroyed-------") - }, - // Listen for mission snapshot changes. - onMissionSnapshotChanged: function (mission) { - console.info("--------onMissionSnapshotChanged-------") - }, - // Listen for switching the mission to the foreground. - onMissionMovedToFront: function (mission) { - console.info("--------onMissionMovedToFront-------") - }, - // Listen for mission icon changes. - onMissionIconUpdated: function (mission, icon) { - console.info("--------onMissionIconUpdated-------") - }, - // Listen for mission name changes. - onMissionLabelUpdated: function (mission) { - console.info("--------onMissionLabelUpdated-------") - }, - // Listen for mission closure events. - onMissionClosed: function (mission) { - console.info("--------onMissionClosed-------") - } + // Listen for mission creation. + onMissionCreated: function (mission) { + console.info("--------onMissionCreated-------") + }, + // Listen for mission destruction. + onMissionDestroyed: function (mission) { + console.info("--------onMissionDestroyed-------") + }, + // Listen for mission snapshot changes. + onMissionSnapshotChanged: function (mission) { + console.info("--------onMissionSnapshotChanged-------") + }, + // Listen for switching the mission to the foreground. + onMissionMovedToFront: function (mission) { + console.info("--------onMissionMovedToFront-------") + }, + // Listen for mission icon changes. + onMissionIconUpdated: function (mission, icon) { + console.info("--------onMissionIconUpdated-------") + }, + // Listen for mission name changes. + onMissionLabelUpdated: function (mission) { + console.info("--------onMissionLabelUpdated-------") + }, + // Listen for mission closure events. + onMissionClosed: function (mission) { + console.info("--------onMissionClosed-------") + } }; // 1. Register a mission change listener. @@ -73,56 +73,56 @@ You can use **missionManager** to manage missions, for example, listening for mi // 2. Obtain the latest 20 missions in the system. missionManager.getMissionInfos("", 20, (error, missions) => { - console.info("getMissionInfos is called, error.code = " + error.code); - console.info("size = " + missions.length); - console.info("missions = " + JSON.stringify(missions)); + console.info("getMissionInfos is called, error.code = " + error.code); + console.info("size = " + missions.length); + console.info("missions = " + JSON.stringify(missions)); }); // 3. Obtain the detailed information about a mission. let missionId = 11; // The mission ID 11 is only an example. let mission = missionManager.getMissionInfo("", missionId).catch(function (err) { - console.info(err); + console.info(err); }); // 4. Obtain the mission snapshot. missionManager.getMissionSnapShot("", missionId, (error, snapshot) => { - console.info("getMissionSnapShot is called, error.code = " + error.code); - console.info("bundleName = " + snapshot.ability.bundleName); + console.info("getMissionSnapShot is called, error.code = " + error.code); + console.info("bundleName = " + snapshot.ability.bundleName); }) // 5. Obtain the low-resolution mission snapshot. missionManager.getLowResolutionMissionSnapShot("", missionId, (error, snapshot) => { - console.info("getLowResolutionMissionSnapShot is called, error.code = " + error.code); - console.info("bundleName = " + snapshot.ability.bundleName); + console.info("getLowResolutionMissionSnapShot is called, error.code = " + error.code); + console.info("bundleName = " + snapshot.ability.bundleName); }) // 6. Lock or unlock the mission. missionManager.lockMission(missionId).then(() => { - console.info("lockMission is called "); + console.info("lockMission is called "); }); missionManager.unlockMission(missionId).then(() => { - console.info("unlockMission is called "); + console.info("unlockMission is called "); }); // 7. Switch the mission to the foreground. missionManager.moveMissionToFront(missionId).then(() => { - console.info("moveMissionToFront is called "); + console.info("moveMissionToFront is called "); }); // 8. Clear a single mission. missionManager.clearMission(missionId).then(() => { - console.info("clearMission is called "); + console.info("clearMission is called "); }); // 9. Clear all missions. missionManager.clearAllMissions().catch(function (err) { - console.info(err); + console.info(err); }); // 10. Deregister the mission change listener. missionManager.off('mission', listenerId, (error) => { - console.info("unregisterMissionListener"); + console.info("unregisterMissionListener"); }) ``` diff --git a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md index c98d39ff8348f330d58138db89afcc2a0d5995ca..a5da1eeaa1d232b943f388b714b5a06f10d77be0 100644 --- a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md +++ b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md @@ -21,8 +21,10 @@ Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-applica ```ts let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information. -this.context.setMissionIcon(imagePixelMap, (err) => { - console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); +context.setMissionIcon(imagePixelMap, (err) => { + if (err.code) { + console.error(`Failed to set mission icon. Code is ${err.code}, message is ${err.message}`); + } }) ``` @@ -38,9 +40,9 @@ Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-applic ```ts this.context.setMissionLabel('test').then(() => { - console.info('setMissionLabel succeeded.'); + console.info('Succeeded in seting mission label.'); }).catch((err) => { - console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); + console.error(`Failed to set mission label. Code is ${err.code}, message is ${err.message}`); }); ``` diff --git a/en/application-dev/application-models/module-switch.md b/en/application-dev/application-models/module-switch.md index 9f31f892cda1a077301773a129f4f7915cd25c82..749c41ebdd4ebe5c4c2a1e0b9628c5fbfe74cea4 100644 --- a/en/application-dev/application-models/module-switch.md +++ b/en/application-dev/application-models/module-switch.md @@ -3,7 +3,7 @@ When switching an application from the FA model to the stage model, you must migrate the configurations under the **module** tag in the **config.json** file to the **module** tag in the **module.json5** file. -### Table 1 module Comparison +**Table 1** module comparison | Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | @@ -15,8 +15,8 @@ When switching an application from the FA model to the stage model, you must mig | moduleType in the distro object| Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this field to **har**.| type | The field name is changed.| | installationFree in the distro object| Whether the HAP file supports the installation-free feature.| installationFree | The field name is changed.| | deliveryWithInstall in the distro object| Whether the HAP file is installed with the application.| deliveryWithInstall | The field name is changed.| -| metaData | Metadata of the HAP file.| metadata | See [Table 2](#table-2-metadata-comparison).| -| abilities | All abilities in the current module.| abilities | See [Table 5](#table-5-abilities-comparison).| +| metaData | Metadata of the HAP file.| metadata | For details, see Table 2.| +| abilities | All abilities in the current module.| abilities | For details, see Table 5.| | js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module.| pages | The stage model retains **pages** under the **module** tag. The window configuration is the lower level of **pages**.| | shortcuts | Shortcuts of the application.| shortcut_config.json| In the stage model, the **shortcut_config.json** file is defined in **resources/base/profile** in the development view.| | reqPermissions | Permissions that the application requests from the system when it is running.| requestPermissions | The field name is changed.| @@ -27,38 +27,38 @@ When switching an application from the FA model to the stage model, you must mig | entryTheme | Keyword of an OpenHarmony internal theme.| / | This configuration is not supported in the stage model.| -### Table 2 metaData Comparison +**Table 2** metaData comparison -| Field Name Under metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | parameters | Metadata of the parameters to be passed for calling the ability.| / | This configuration is not supported in the stage model.| | results | Metadata of the ability return value.| / | This configuration is not supported in the stage model.| -| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| metadata | See [Table 3](#table-3-comparison-between-customizedata-under-metadata-in-the-fa-model-and-metadata-in-the-stage-model).| +| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| metadata | **For details**, see Table 3.| -### Table 3 Comparison Between customizeData Under metaData in the FA Model and metadata in the Stage Model +**Table 3** Comparison between customizeData under metaData in the FA model and metadata in the stage Model -| Field Name Under customizeData in metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes.| name | None.| | value | Value of the data item. The value is a string with a maximum of 255 bytes.| value | None.| -| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see [Table 4](#table 4-metadata-examples).| +| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see Table 4.| -### Table 4 metaData Examples +**Table 4** metaData examples | Example in the FA Model| Example in the Stage Model| | -------- | -------- | | "meteData": {
"customizeDate": [{
"name": "label",
"value": "string",
"extra": "$string:label",
}]
} | "meteData": [{
"name": "label",
"value": "string",
"resource": "$string:label",
}] | -### Table 5 abilities Comparison +**Table 5** abilities comparison | Field Name Under abilities in the FA Model| Field Description| Field Name Under abilities in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | process | Name of the process running the application or ability.| / | The stage model does not support configuration of **process** under **abilities**. The configuration of **process** is available under the **module** tag.| | uri | URI of the ability.| / | This configuration is not supported in the stage model.| | deviceCapability | Device capabilities required to run the ability.| / | This configuration is not supported in the stage model.| -| metaData | Metadata of the ability.| metadata | See [Table 2](#table-2-metadata-comparison).| +| metaData | Metadata of the ability.| metadata | For details, see Table 2.| | type | Ability type.| / | This configuration is not supported in the stage model.| | grantPermission | Whether permissions can be granted for any data in the ability.| / | The stage model does not support such a configuration under **abilities**.| | readPermission | Permission required for reading data in the ability. This field applies only to the ability using the Data template.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.| diff --git a/en/application-dev/application-models/page-mission-stack.md b/en/application-dev/application-models/page-mission-stack.md index 702cb9ba928d5266ce6720d10538df6109b0cbeb..cdb7ce724f2a29c711d4d056bcda5716f265ba48 100644 --- a/en/application-dev/application-models/page-mission-stack.md +++ b/en/application-dev/application-models/page-mission-stack.md @@ -5,7 +5,8 @@ A single UIAbility component can implement multiple pages and redirection between these pages. The redirection relationship inside the UIAbility component is called page stack, which is managed by the ArkUI framework. For example, Page1 -> Page2 -> Page3 of UIAbility1 and PageA -> PageB -> PageC of UIAbility2 in the figure below are two page stacks. - **Figure 1** Page stack +**Figure 1** Page stack + ![mission-record](figures/mission-record.png) - A page stack is formed as follows (Steps 2, 3, 5, and 6 are page redirection and managed by ArkUI): diff --git a/en/application-dev/application-models/pageability-launch-type.md b/en/application-dev/application-models/pageability-launch-type.md index 3b75ff6a60899f19f08aad5235fb3dc49632cb01..1e5d14c3037261e66fb2decdede6779c079651bc 100644 --- a/en/application-dev/application-models/pageability-launch-type.md +++ b/en/application-dev/application-models/pageability-launch-type.md @@ -5,7 +5,7 @@ Depending on the launch type, the action performed when the PageAbility starts d **Table 1** PageAbility launch types -| Launch Type| Meaning | Description| +| Launch Type| Meaning| Description | | -------- | -------- | -------- | | singleton | Singleton mode| Each time **startAbility()** is called, if an ability instance of this type already exists in the application process, the instance is reused. There is only one ability instance of this type in **Recents**.
A typical scenario is as follows: When a user opens a video playback application and watches a video, returns to the home screen, and opens the video playback application again, the video that the user watched before returning to the home screen is still played.| | standard | Multiton mode| Default type. Each time **startAbility()** is called, a new ability instance is created in the application process. Multiple ability instances of this type are displayed in **Recents**.
A typical scenario is as follows: When a user opens a document application and touches **New**, a new document task is created. Multiple new document missions are displayed in **Recents**.| @@ -16,13 +16,13 @@ You can set **launchType** in the **config.json** file to configure the launch t ```json { "module": { - // ... + ... "abilities": [ { // singleton means the singleton mode. // standard means the multiton mode. "launchType": "standard", - // ... + ... } ] } diff --git a/en/application-dev/application-models/process-model-fa.md b/en/application-dev/application-models/process-model-fa.md index 699643031121521fbf95d26a949df906fa175a18..ce4c9778d3bf678c7ecb8094477050a42eebb7d7 100644 --- a/en/application-dev/application-models/process-model-fa.md +++ b/en/application-dev/application-models/process-model-fa.md @@ -1,4 +1,4 @@ -# Process Model (FA Model) +# Process Model Overview (FA Model) The OpenHarmony process model is shown below. diff --git a/en/application-dev/application-models/process-model-stage.md b/en/application-dev/application-models/process-model-stage.md index 03da480722de124a1ede58da52e74cd48c5f23f0..cf758d94636773dfd190366d0e215de655902abd 100644 --- a/en/application-dev/application-models/process-model-stage.md +++ b/en/application-dev/application-models/process-model-stage.md @@ -1,4 +1,4 @@ -# Process Model (Stage Model) +# Process Model Overview (Stage Model) The OpenHarmony process model is shown below. diff --git a/en/application-dev/application-models/redirection-rules.md b/en/application-dev/application-models/redirection-rules.md index 4e9f65a8b3439fe4dde4761fbcb3d341151ba4f3..19c74c605cd7ca1451cef6809f6ec5238cec36df 100644 --- a/en/application-dev/application-models/redirection-rules.md +++ b/en/application-dev/application-models/redirection-rules.md @@ -21,11 +21,11 @@ To enable an ability to be called by any application, configure the **config.jso ```ts { "module": { - // ... + ... "abilities": [ { "visible": "true", - // ... + ... } ] } diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index 2e9aaeb48100d86d0cd1c7a0e69ea01bf4ef2340..3f9e96cf03318d900b428348bdb1bdfb0151f611 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -29,6 +29,7 @@ Note the following: [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. **Figure 1** ServiceExtensionAbility lifecycle + ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) - **onCreate** @@ -61,7 +62,7 @@ Note the following: Only system applications can implement ServiceExtensionAbility. You must make the following preparations before development: -- **Switching to the full SDK**: All APIs related to ServiceExtensionAbility are marked as system APIs and hidden by default. Therefore, you must manually obtain the full SDK from the mirror and switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). +- **Switching to the full SDK**: All APIs related to ServiceExtensionAbility are marked as system APIs and hidden by default. Therefore, you must manually obtain the full SDK from the mirror and switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../faqs/full-sdk-switch-guide.md). - **Requesting the AllowAppUsePrivilegeExtension privilege**: Only applications with the **AllowAppUsePrivilegeExtension** privilege can develop ServiceExtensionAbility. For details about how to request the privilege, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). @@ -109,7 +110,7 @@ export default class ServiceExtImpl extends IdlServiceExtStub { insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } @@ -175,7 +176,7 @@ To manually create a ServiceExtensionAbility in the DevEco Studio project, perfo ```json { "module": { - // ... + ... "extensionAbilities": [ { "name": "ServiceExtAbility", @@ -201,41 +202,43 @@ A system application uses the [startServiceExtensionAbility()](../reference/apis 1. Start a new ServiceExtensionAbility in a system application. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts + let context = ...; // UIAbilityContext let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; - this.context.startServiceExtensionAbility(want).then(() => { - console.info('startServiceExtensionAbility success'); - }).catch((error) => { - console.info('startServiceExtensionAbility failed'); + context.startServiceExtensionAbility(want).then(() => { + console.info('Succeeded in starting ServiceExtensionAbility.'); + }).catch((err) => { + console.error(`Failed to start ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); }) ``` 2. Stop ServiceExtensionAbility in the system application. ```ts + let context = ...; // UIAbilityContext let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; - this.context.stopServiceExtensionAbility(want).then(() => { - console.info('stopServiceExtensionAbility success'); - }).catch((error) => { - console.info('stopServiceExtensionAbility failed'); + context.stopServiceExtensionAbility(want).then(() => { + console.info('Succeeded in stoping ServiceExtensionAbility.'); + }).catch((err) => { + console.error(`Failed to stop ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); }) ``` 3. ServiceExtensionAbility stops itself. ```ts - // this is the current ServiceExtensionAbility component. - this.context.terminateSelf().then(() => { - console.info('terminateSelf success'); - }).catch((error) => { - console.info('terminateSelf failed'); + let context = ...; // ServiceExtensionContext + context.terminateSelf().then(() => { + console.info('Succeeded in terminating self.'); + }).catch((err) => { + console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -257,27 +260,27 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec ```ts let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; let options = { - onConnect(elementName, remote) { - /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback. - * This object is used for communication with ServiceExtensionAbility. For details, see the section below. - */ - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback. + * This object is used for communication with ServiceExtensionAbility. For details, see the section below. + */ + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection. let connectionId = this.context.connectServiceExtensionAbility(want, options); @@ -288,9 +291,9 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec ```ts // connectionId is returned when connectServiceExtensionAbility is called and needs to be manually maintained. this.context.disconnectServiceExtensionAbility(connectionId).then((data) => { - console.info('disconnectServiceExtensionAbility success'); + console.info('disconnectServiceExtensionAbility success'); }).catch((error) => { - console.error('disconnectServiceExtensionAbility failed'); + console.error('disconnectServiceExtensionAbility failed'); }) ``` @@ -305,27 +308,27 @@ After obtaining the [rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteo import IdlServiceExtProxy from '../IdlServiceExt/idl_service_ext_proxy'; let options = { - onConnect(elementName, remote) { - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - let serviceExtProxy = new IdlServiceExtProxy(remote); - // Communication is carried out by interface calling, without exposing RPC details. - serviceExtProxy.processData(1, (errorCode, retVal) => { - console.log(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); - }); - serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { - console.log(`insertDataToMap, errorCode: ${errorCode}`); - }) - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + let serviceExtProxy = new IdlServiceExtProxy(remote); + // Communication is carried out by interface calling, without exposing RPC details. + serviceExtProxy.processData(1, (errorCode, retVal) => { + console.info(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); + }); + serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { + console.info(`insertDataToMap, errorCode: ${errorCode}`); + }) + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } ``` @@ -333,40 +336,40 @@ After obtaining the [rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteo ```ts import rpc from '@ohos.rpc'; - + const REQUEST_CODE = 1; let options = { - onConnect(elementName, remote) { - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - // Directly call the RPC interface to send messages to the server. The client needs to serialize the input parameters and deserialize the return values. The process is complex. - let option = new rpc.MessageOption(); - let data = new rpc.MessageSequence(); - let reply = new rpc.MessageSequence(); - data.writeInt(100); - - // @param code Indicates the service request code sent by the client. - // @param data Indicates the {@link MessageSequence} object sent by the client. - // @param reply Indicates the response message object sent by the remote service. - // @param options Specifies whether the operation is synchronous or asynchronous. - // - // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. - remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => { - let msg = reply.readInt(); - console.info(`sendMessageRequest ret:${ret} msg:${msg}`); - }).catch((error) => { - console.info('sendMessageRequest failed'); - }); - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + // Directly call the RPC interface to send messages to the server. The client needs to serialize the input parameters and deserialize the return values. The process is complex. + let option = new rpc.MessageOption(); + let data = new rpc.MessageSequence(); + let reply = new rpc.MessageSequence(); + data.writeInt(100); + + // @param code Indicates the service request code sent by the client. + // @param data Indicates the {@link MessageSequence} object sent by the client. + // @param reply Indicates the response message object sent by the remote service. + // @param options Specifies whether the operation is synchronous or asynchronous. + // + // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. + remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => { + let msg = reply.readInt(); + console.info(`sendMessageRequest ret:${ret} msg:${msg}`); + }).catch((error) => { + console.info('sendMessageRequest failed'); + }); + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } ``` @@ -381,8 +384,8 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i ```ts import rpc from '@ohos.rpc'; import bundleManager from '@ohos.bundle.bundleManager'; - import {processDataCallback} from './i_idl_service_ext'; - import {insertDataToMapCallback} from './i_idl_service_ext'; + import { processDataCallback } from './i_idl_service_ext'; + import { insertDataToMapCallback } from './i_idl_service_ext'; import IdlServiceExtStub from './idl_service_ext_stub'; const ERR_OK = 0; @@ -397,7 +400,7 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i bundleManager.getBundleNameByUid(callerUid).then((callerBundleName) => { console.info(TAG, 'getBundleNameByUid: ' + callerBundleName); // Identify the bundle name of the client. - if (callerBundleName != 'com.example.connectextapp') { // The verification fails. + if (callerBundleName != 'com.example.connectextapp') { // The verification fails. console.info(TAG, 'The caller bundle is not in whitelist, reject'); return; } @@ -409,7 +412,7 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } @@ -425,15 +428,15 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i import {processDataCallback} from './i_idl_service_ext'; import {insertDataToMapCallback} from './i_idl_service_ext'; import IdlServiceExtStub from './idl_service_ext_stub'; - + const ERR_OK = 0; const ERR_DENY = -1; const TAG: string = "[IdlServiceExtImpl]"; - + export default class ServiceExtImpl extends IdlServiceExtStub { processData(data: number, callback: processDataCallback): void { console.info(TAG, `processData: ${data}`); - + let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); let accessManger = abilityAccessCtrl.createAtManager(); // The permission to be verified varies depending on the service requirements. ohos.permission.SET_WALLPAPER is only an example. @@ -446,10 +449,10 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i } callback(ERR_OK, data + 1); // The verification is successful, and service logic is executed normally. } - + insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } diff --git a/en/application-dev/application-models/stage-model-development-overview.md b/en/application-dev/application-models/stage-model-development-overview.md index 451649bdb1a63147b79f8c7e2d4523d6c651c548..d4ad1d87c602c169e13b9ff99b8b491a33babd0a 100644 --- a/en/application-dev/application-models/stage-model-development-overview.md +++ b/en/application-dev/application-models/stage-model-development-overview.md @@ -12,7 +12,7 @@ The following figure shows the basic concepts used in the stage model. The stage model provides two types of application components: UIAbility and ExtensionAbility. Both have specific classes and support object-oriented development. - - UIAbility has the UI and is mainly used for user interaction. For example, with UIAbility, the Gallery application can display images in the liquid layout. After a user selects an image, it uses a new UI to display the image details. The user can touch the **Back** button to return to the liquid layout. The lifecycle of the UIAbility component contains the creation, destruction, foreground, and background states. Display-related states are exposed through WindowStage events. + - UIAbility is a type of application component that provides the UI for user interaction. For example, with UIAbility, the Gallery application can display images in the liquid layout. After a user selects an image, it uses a new UI to display the image details. The user can touch the **Back** button to return to the liquid layout. The lifecycle of the UIAbility component contains the creation, destruction, foreground, and background states. Display-related states are exposed through WindowStage events. - ExtensionAbility is oriented to specific scenarios. You cannot derive directly from ExtensionAbility. Instead, use the derived classes of ExtensionAbility for your scenarios, such as FormExtensionAbility for widget scenarios, InputMethodExtensionAbility for input method scenarios, and WorkSchedulerExtensionAbility for Work Scheduled task scenarios. For example, to enable a user to create an application widget on the home screen, you must derive FormExtensionAbility, implement the callback functions, and configure the capability in the configuration file. The derived class instances are created by developers and their lifecycles are managed by the system. In the stage model, you must use the derived classes of ExtensionAbility to develop custom services based on your service scenarios. - [WindowStage](../windowmanager/application-window-stage.md) @@ -37,7 +37,7 @@ During application development based on the stage model, the following tasks are | Task| Introduction| Guide| | -------- | -------- | -------- | | Application component development| Use the UIAbility and ExtensionAbility components of the stage model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-stage.md)
- [UIAbility Component](uiability-overview.md)
- [ExtensionAbility Component](extensionability-overview.md)
- [AbilityStage Container Component](abilitystage.md)
- [Context](application-context-stage.md)
- [Component Startup Rules](component-startup-rules.md)| -| Inter-process communication (IPC)| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)
- [Background Services](background-services.md)| -| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)
- [Worker](itc-with-worker.md)| +| Process model| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)
- [Background Services](background-services.md)| +| Thread model| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)
- [Worker](itc-with-worker.md)| | Mission management| Learn the basic concepts and typical scenarios of mission management in the stage model.| - [Mission Management Scenarios](mission-management-overview.md)
- [Mission Management and Launch Type](mission-management-launch-type.md)
- [Page Stack and Mission List](page-mission-stack.md)| | Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](config-file-stage.md)| diff --git a/en/application-dev/application-models/start-page.md b/en/application-dev/application-models/start-page.md index 5831ea0c6f6b6fa9d954134ef723f70e925e3ed7..1def472cd5fa2567fda123fc272542787b1f985c 100644 --- a/en/application-dev/application-models/start-page.md +++ b/en/application-dev/application-models/start-page.md @@ -83,7 +83,7 @@ struct Index { @State message: string = 'Hello World' build() { - // ... + ... Button("startAbility") .onClick(() => { featureAbility.startAbility({ @@ -98,7 +98,7 @@ struct Index { console.info("startAbility failed errcode:" + err.code) }) }) - // ... + ... Button("page2") .onClick(() => { featureAbility.startAbility({ @@ -113,7 +113,7 @@ struct Index { console.info("startAbility failed errcode:" + err.code) }) }) - // ... + ... } } ``` @@ -136,7 +136,7 @@ export default { }) }, onDestroy() { - // ... + ... }, } ``` diff --git a/en/application-dev/application-models/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md index 9d1b7ed27f6780ce56d1e90b3be5d196cf3b1187..bd6a11187fdfbc81c63bcc6601f8a8e82b0dbe4c 100644 --- a/en/application-dev/application-models/start-pageability-from-stage.md +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -21,7 +21,7 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { - // ... + ... }); let want = { bundleName: "com.ohos.fa", @@ -66,7 +66,7 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { - // ... + ... }); let want = { bundleName: "com.ohos.fa", diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md index 36ee305b49698c1f6e6cf216174f77212f1d53e4..a52378af306c9719b086b23f0909f87d7bf376b3 100644 --- a/en/application-dev/application-models/start-remote-pageability.md +++ b/en/application-dev/application-models/start-remote-pageability.md @@ -83,28 +83,31 @@ After obtaining the data synchronization permission, obtain the trusted device l The following sample code shows how to use **getTrustedDeviceListSync()** to obtain the trusted device list. ```ts -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmClass; +import deviceManager from '@ohos.distributedHardware.deviceManager'; + +let dmClass; + function getDeviceManager() { - deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => { - if (error) { - console.info('create device manager failed with ' + error) - } - dmClass = dm; - }) + deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => { + if (error) { + console.info('create device manager failed with ' + error) + } + dmClass = dm; + }) } -function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - let list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); - return; - } - console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; - } else { - console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); - } + +function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass != null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); + return; + } + console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + return list[0].deviceId; + } else { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + } } ``` @@ -116,21 +119,22 @@ The following sample code shows how to explicitly start a remote PageAbility thr ```ts import featureAbility from '@ohos.ability.featureAbility'; -function onStartRemoteAbility() { - console.info('onStartRemoteAbility begin'); - let params; - let wantValue = { - bundleName: 'ohos.samples.etsDemo', - abilityName: 'ohos.samples.etsDemo.RemoteAbility', - deviceId: getRemoteDeviceId(), // getRemoteDeviceId is defined in the preceding sample code. - parameters: params - }; - console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); - featureAbility.startAbility({ - want: wantValue - }).then((data) => { - console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); - }); - console.info('onStartRemoteAbility end'); + +function onStartRemoteAbility() { + console.info('onStartRemoteAbility begin'); + let params; + let wantValue = { + bundleName: 'ohos.samples.etsDemo', + abilityName: 'ohos.samples.etsDemo.RemoteAbility', + deviceId: getRemoteDeviceId(), // getRemoteDeviceId is defined in the preceding sample code. + parameters: params + }; + console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); + }); + console.info('onStartRemoteAbility end'); } ``` diff --git a/en/application-dev/application-models/subscribe-system-environment-variable-changes.md b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md index c231f483e9bcd8f83faf49d40007730d0f854de5..4eecf15808da492ca69d933fdabf39aa82347ce5 100644 --- a/en/application-dev/application-models/subscribe-system-environment-variable-changes.md +++ b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md @@ -54,7 +54,7 @@ In OpenHarmony, you can subscribe to system environment variable changes in the // Page display. build() { - // ... + ... } } ``` @@ -77,7 +77,7 @@ In OpenHarmony, you can subscribe to system environment variable changes in the // Page display. build() { - // ... + ... } } ``` @@ -99,19 +99,19 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; let systemLanguage: string; // System language in use. export default class MyAbilityStage extends AbilityStage { - onCreate() { - systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time. - console.info(`systemLanguage is ${systemLanguage} `); - } + onCreate() { + systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } - onConfigurationUpdate(newConfig) { - console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); - if (systemLanguage !== newConfig.language) { - console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); - systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. - } + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } + } } ``` @@ -131,21 +131,21 @@ import UIAbility from '@ohos.app.ability.UIAbility'; let systemLanguage: string; // System language in use. export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. - console.info(`systemLanguage is ${systemLanguage} `); - } + onCreate(want, launchParam) { + systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } - onConfigurationUpdate(newConfig) { - console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); - if (systemLanguage !== newConfig.language) { - console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); - systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. - } + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } + } - // ... + ... } ``` @@ -163,10 +163,10 @@ The code snippet below uses FormExtensionAbility as an example to describe how t import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class EntryFormAbility extends FormExtensionAbility { - onConfigurationUpdate(newConfig) { - console.info(`newConfig is ${JSON.stringify(newConfig)}`); - } + onConfigurationUpdate(newConfig) { + console.info(`newConfig is ${JSON.stringify(newConfig)}`); + } - // ... + ... } ``` diff --git a/en/application-dev/application-models/thread-model-fa.md b/en/application-dev/application-models/thread-model-fa.md index 75401be69cba994ac631b6da997fb6ce2ea35a2f..f6b335f8932ee1ebd5bb9bdf11db99ff354a1470 100644 --- a/en/application-dev/application-models/thread-model-fa.md +++ b/en/application-dev/application-models/thread-model-fa.md @@ -1,13 +1,11 @@ -# Thread Model (FA Model) - +# Thread Model Overview (FA Model) There are three types of threads in the FA model: - - Main thread - -Manages other threads. - + + Manages other threads. + - Ability thread - One ability thread for each ability. - Distributes input events. @@ -19,10 +17,8 @@ Manages other threads. Performs time-consuming operations - Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. - > **NOTE** > > The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread. diff --git a/en/application-dev/application-models/thread-model-stage.md b/en/application-dev/application-models/thread-model-stage.md index 4ca9fb3ed369f78cf12054c7b6da085b8640b1db..2b1f855980a14eeba89a18184c69d46eebaea6ac 100644 --- a/en/application-dev/application-models/thread-model-stage.md +++ b/en/application-dev/application-models/thread-model-stage.md @@ -1,4 +1,4 @@ -# Thread Model (Stage Model) +# Thread Model Overview (Stage Model) For an OpenHarmony application, each process has a main thread to provide the following functionalities: @@ -17,5 +17,6 @@ Based on the OpenHarmony thread model, different services run on different threa > **NOTE** > -> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the main thread or between the main thread and worker thread. -> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p ** -T command**, where ** indicates the ID of the application process. +> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the worker thread or between the main thread and worker thread. +> - The UIAbility and UI are in the main thread. For details about data synchronization between them, see [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md). +> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p ** -T command**, where ** indicates the [process ID](process-model-stage.md) of the application. diff --git a/en/application-dev/application-models/uiability-data-sync-with-ui.md b/en/application-dev/application-models/uiability-data-sync-with-ui.md index 52967c25c86966710853378c95c74d5e6e13e432..6998001c763a464e51f8cef4a0c64aec6f1db5e8 100644 --- a/en/application-dev/application-models/uiability-data-sync-with-ui.md +++ b/en/application-dev/application-models/uiability-data-sync-with-ui.md @@ -22,21 +22,21 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** const TAG: string = '[Example].[Entry].[EntryAbility]'; export default class EntryAbility extends UIAbility { - func1(...data) { - // Trigger the event to complete the service operation. - console.info(TAG, '1. ' + JSON.stringify(data)); - } - - onCreate(want, launch) { - // Obtain an eventHub object. - let eventhub = this.context.eventHub; - // Subscribe to the event. - eventhub.on('event1', this.func1); - eventhub.on('event1', (...data) => { - // Trigger the event to complete the service operation. - console.info(TAG, '2. ' + JSON.stringify(data)); - }); - } + func1(...data) { + // Trigger the event to complete the service operation. + console.info(TAG, '1. ' + JSON.stringify(data)); + } + + onCreate(want, launch) { + // Obtain an eventHub object. + let eventhub = this.context.eventHub; + // Subscribe to the event. + eventhub.on('event1', this.func1); + eventhub.on('event1', (...data) => { + // Trigger the event to complete the service operation. + console.info(TAG, '2. ' + JSON.stringify(data)); + }); + } } ``` @@ -62,7 +62,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** // Page display. build() { - // ... + ... } } ``` @@ -90,8 +90,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** **globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization. **Figure 1** Using globalThis for data synchronization - - ![globalThis1](figures/globalThis1.png) +![globalThis1](figures/globalThis1.png) The following describes how to use **globalThis** in three scenarios. Precautions are provided as well. @@ -105,18 +104,18 @@ The following describes how to use **globalThis** in three scenarios. Precaution By binding attributes or methods to **globalThis**, you can implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. -1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. +1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launch) { - globalThis.entryAbilityWant = want; - // ... - } + onCreate(want, launch) { + globalThis.entryAbilityWant = want; + ... + } - // ... + ... } ``` @@ -124,17 +123,17 @@ By binding attributes or methods to **globalThis**, you can implement data synch ```ts let entryAbilityWant; - + @Entry @Component struct Index { aboutToAppear() { entryAbilityWant = globalThis.entryAbilityWant; } - + // Page display. build() { - // ... + ... } } ``` @@ -150,10 +149,10 @@ To implement data synchronization between two UIAbility components in the same a import UIAbility from '@ohos.app.ability.UIAbility' export default class UIAbilityA extends UIAbility { - onCreate(want, launch) { - globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA stores the string "UIAbilityA" to globalThis. - // ... - } + onCreate(want, launch) { + globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA stores the string "UIAbilityA" to globalThis. + ... + } } ``` @@ -161,13 +160,13 @@ To implement data synchronization between two UIAbility components in the same a ```ts import UIAbility from '@ohos.app.ability.UIAbility' - + export default class UIAbilityB extends UIAbility { - onCreate(want, launch) { - // UIAbilityB reads name from globalThis and outputs it. - console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); - // ... - } + onCreate(want, launch) { + // UIAbilityB reads name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + ... + } } ``` @@ -182,11 +181,11 @@ To implement data synchronization between the UIAbility and ExtensionAbility com import UIAbility from '@ohos.app.ability.UIAbility' export default class UIAbilityA extends UIAbility { - onCreate(want, launch) { - // UIAbilityA stores the string "UIAbilityA" to globalThis. - globalThis.entryAbilityStr = 'UIAbilityA'; - // ... - } + onCreate(want, launch) { + // UIAbilityA stores the string "UIAbilityA" to globalThis. + globalThis.entryAbilityStr = 'UIAbilityA'; + ... + } } ``` @@ -194,21 +193,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com ```ts import Extension from '@ohos.app.ability.ServiceExtensionAbility' - + export default class ServiceExtAbility extends Extension { - onCreate(want) { - / / ServiceExtAbility reads name from globalThis and outputs it. - console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); - // ... - } + onCreate(want) { + / / ServiceExtAbility reads name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + ... + } } ``` ### Precautions for Using globalThis -**Figure 2** Precautions for globalThis - +**Figure 2** Precautions for globalThis ![globalThis2](figures/globalThis2.png) - In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if UIAbilityA and UIAbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. @@ -225,10 +223,10 @@ The following provides an example to describe the object overwritten problem in import UIAbility from '@ohos.app.ability.UIAbility' export default class UIAbilityA extends UIAbility { - onCreate(want, launch) { - globalThis.context = this.context; // UIAbilityA stores the context in globalThis. - // ... - } + onCreate(want, launch) { + globalThis.context = this.context; // UIAbilityA stores the context in globalThis. + ... + } } ``` @@ -243,7 +241,7 @@ The following provides an example to describe the object overwritten problem in } // Page display. build() { - // ... + ... } } ``` @@ -254,11 +252,11 @@ The following provides an example to describe the object overwritten problem in import UIAbility from '@ohos.app.ability.UIAbility' export default class UIAbilityB extends UIAbility { - onCreate(want, launch) { - // UIAbilityB overwrites the context stored by UIAbilityA in globalThis. - globalThis.context = this.context; - // ... - } + onCreate(want, launch) { + // UIAbilityB overwrites the context stored by UIAbilityA in globalThis. + globalThis.context = this.context; + ... + } } ``` @@ -273,7 +271,7 @@ The following provides an example to describe the object overwritten problem in } // Page display. build() { - // ... + ... } } ``` @@ -284,10 +282,10 @@ The following provides an example to describe the object overwritten problem in import UIAbility from '@ohos.app.ability.UIAbility' export default class UIAbilityA extends UIAbility { - onCreate(want, launch) { // UIAbilityA will not enter this lifecycle. - globalThis.context = this.context; - // ... - } + onCreate(want, launch) { // UIAbilityA will not enter this lifecycle. + globalThis.context = this.context; + ... + } } ``` @@ -302,7 +300,7 @@ The following provides an example to describe the object overwritten problem in } // Page display. build() { - // ... + ... } } ``` @@ -310,5 +308,3 @@ The following provides an example to describe the object overwritten problem in ## Using AppStorage or LocalStorage for Data Synchronization ArkUI provides AppStorage and LocalStorage to implement application- and UIAbility-level data synchronization, respectively. Both solutions can be used to manage the application state, enhance application performance, and improve user experience. The AppStorage is a global state manager and is applicable when multiple UIAbilities share the same state data. The LocalStorage is a local state manager that manages state data used inside a single UIAbility. They help you control the application state more flexibly and improve the maintainability and scalability of applications. For details, see [State Management of Application-Level Variables](../quick-start/arkts-application-state-management-overview.md). - - \ No newline at end of file diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md index 9dbbc2be90107d2131a1cdae21e576cb4771966e..208fd1af3bb9912439a8a50d3ce35f5a5d58596e 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -32,20 +32,20 @@ Assume that your application has two UIAbility components: EntryAbility and Func ```ts let context = ...; // UIAbilityContext - let wantInfo = { + let want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. + moduleName: 'func', // moduleName is optional. parameters: {// Custom information. info: 'From the Index page of EntryAbility', }, } // context is the UIAbilityContext of the initiator UIAbility. - context.startAbility(wantInfo).then(() => { - // ... + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -53,18 +53,17 @@ Assume that your application has two UIAbility components: EntryAbility and Func ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - import window from '@ohos.window'; export default class FuncAbility extends UIAbility { onCreate(want, launchParam) { // Receive the parameters passed by the initiator UIAbility. let funcAbilityWant = want; let info = funcAbilityWant?.parameters?.info; - // ... + ... } } ``` - + > **NOTE**
> > In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter. @@ -76,11 +75,14 @@ Assume that your application has two UIAbility components: EntryAbility and Func // context is the UIAbilityContext of the UIAbility instance to stop. context.terminateSelf((err) => { - // ... + if (err.code) { + console.error(`Failed to terminate Self. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` - > **NOTE** + > **NOTE**
> > When [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called to stop the **UIAbility** instance, the snapshot of the instance is retained by default. That is, the mission corresponding to the instance is still displayed in Recents. If you do not want to retain the snapshot, set **removeMissionAfterTerminate** under the [abilities](../quick-start/module-configuration-file.md#abilities) tag to **true** in the [module.json5 file](../quick-start/module-configuration-file.md) of the corresponding UIAbility. @@ -95,20 +97,20 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ```ts let context = ...; // UIAbilityContext - let wantInfo = { + let want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. + moduleName: 'func', // moduleName is optional. parameters: {// Custom information. info: 'From the Index page of EntryAbility', }, } // context is the UIAbilityContext of the initiator UIAbility. - context.startAbilityForResult(wantInfo).then((data) => { - // ... + context.startAbilityForResult(want).then((data) => { + ... }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -122,7 +124,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned want: { bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'module1', + moduleName: 'func', parameters: { info: 'From the Index page of FuncAbility', }, @@ -130,7 +132,10 @@ When starting FuncAbility from EntryAbility, you want the result to be returned } // context is the AbilityContext of the target UIAbility. context.terminateSelfWithResult(abilityResult, (err) => { - // ... + if (err.code) { + console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` @@ -140,17 +145,17 @@ When starting FuncAbility from EntryAbility, you want the result to be returned let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; - // ... + ... // context is the UIAbilityContext of the initiator UIAbility. - context.startAbilityForResult(wantInfo).then((data) => { + context.startAbilityForResult(want).then((data) => { if (data?.resultCode === RESULT_CODE) { // Parse the information returned by the target UIAbility. let info = data.want?.parameters?.info; - // ... + ... } }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -174,15 +179,15 @@ This section describes how to start the UIAbility of another application through "module": { "abilities": [ { - // ... + ... "skills": [ { "entities": [ - // ... + ... "entity.system.default" ], "actions": [ - // ... + ... "ohos.want.action.viewData" ] } @@ -197,7 +202,7 @@ This section describes how to start the UIAbility of another application through ```ts let context = ...; // UIAbilityContext - let wantInfo = { + let want = { deviceId: '', // An empty deviceId indicates the local device. // Uncomment the line below if you want to implicitly query data only in the specific bundle. // bundleName: 'com.example.myapplication', @@ -207,14 +212,14 @@ This section describes how to start the UIAbility of another application through } // context is the UIAbilityContext of the initiator UIAbility. - context.startAbility(wantInfo).then(() => { - // ... + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` - The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. + The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. ![](figures/uiability-intra-device-interaction.png) 3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). @@ -224,7 +229,10 @@ This section describes how to start the UIAbility of another application through // context is the UIAbilityContext of the UIAbility instance to stop. context.terminateSelf((err) => { - // ... + if (err.code) { + console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` @@ -240,15 +248,15 @@ If you want to obtain the return result when using implicit Want to start the UI "module": { "abilities": [ { - // ... + ... "skills": [ { "entities": [ - // ... + ... "entity.system.default" ], "actions": [ - // ... + ... "ohos.want.action.editData" ] } @@ -263,20 +271,20 @@ If you want to obtain the return result when using implicit Want to start the UI ```ts let context = ...; // UIAbilityContext - let wantInfo = { + let want = { deviceId: '', // An empty deviceId indicates the local device. // Uncomment the line below if you want to implicitly query data only in the specific bundle. // bundleName: 'com.example.myapplication', action: 'ohos.want.action.editData', // entities can be omitted. - entities: ['entity.system.default'], + entities: ['entity.system.default'] } // context is the UIAbilityContext of the initiator UIAbility. - context.startAbilityForResult(wantInfo).then((data) => { - // ... + context.startAbilityForResult(want).then((data) => { + ... }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -298,7 +306,10 @@ If you want to obtain the return result when using implicit Want to start the UI } // context is the AbilityContext of the target UIAbility. context.terminateSelfWithResult(abilityResult, (err) => { - // ... + if (err.code) { + console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` @@ -317,10 +328,10 @@ If you want to obtain the return result when using implicit Want to start the UI if (data?.resultCode === RESULT_CODE) { // Parse the information returned by the target UIAbility. let payResult = data.want?.parameters?.payResult; - // ... + ... } }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -352,27 +363,28 @@ For details about how to obtain the context, see [Obtaining the Context of UIAbi import AbilityConstant from '@ohos.app.ability.AbilityConstant'; let context = ...; // UIAbilityContext -let wantInfo = { +let want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. + moduleName: 'func', // moduleName is optional. parameters: {// Custom information. info: 'From the Index page of EntryAbility', }, } let options = { windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING -} +}; // context is the UIAbilityContext of the initiator UIAbility. -context.startAbility(wantInfo, options).then(() => { - // ... +context.startAbility(want, options).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` -The display effect is shown below. +The display effect is shown below. + ![](figures/start-uiability-floating-window.png) ## Starting a Specified Page of UIAbility @@ -387,20 +399,20 @@ When the initiator UIAbility starts another UIAbility, it usually needs to redir ```ts let context = ...; // UIAbilityContext -let wantInfo = { +let want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. + moduleName: 'func', // moduleName is optional. parameters: {// Custom parameter used to pass the page information. router: 'funcA', }, } // context is the UIAbilityContext of the initiator UIAbility. -context.startAbility(wantInfo).then(() => { - // ... +context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -431,7 +443,7 @@ export default class FuncAbility extends UIAbility { } } windowStage.loadContent(url, (err, data) => { - // ... + ... }); } } @@ -455,7 +467,7 @@ In summary, when a UIAbility instance of application A has been created and the onNewWant(want, launchParam) { // Receive the parameters passed by the initiator UIAbility. globalThis.funcAbilityWant = want; - // ... + ... } } ``` @@ -480,7 +492,7 @@ In summary, when a UIAbility instance of application A has been created and the // Page display. build() { - // ... + ... } } ``` @@ -494,11 +506,11 @@ In summary, when a UIAbility instance of application A has been created and the Call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the call to implement data sharing between two UIAbility instances (CallerAbility and CalleeAbility) through IPC. -The core API used for the call is **startAbilityByCall**, which differs from **startAbility** in the following ways: +The core API used for the call is **startAbilityByCall()**, which differs from **startAbility()** in the following ways: -- **startAbilityByCall** supports UIAbility launch in the foreground and background, whereas **startAbility** supports UIAbility launch in the foreground only. +- **startAbilityByCall()** supports UIAbility launch in the foreground and background, whereas **startAbility()** supports UIAbility launch in the foreground only. -- The CallerAbility can use the caller object returned by **startAbilityByCall** to communicate with the CalleeAbility, but **startAbility** does not provide the communication capability. +- The CallerAbility can use the caller object returned by **startAbilityByCall()** to communicate with the CalleeAbility, but **startAbility()** does not provide the communication capability. Call is usually used in the following scenarios: @@ -506,6 +518,7 @@ Call is usually used in the following scenarios: - Starting the CalleeAbility in the background + **Table 1** Terms used in the call | **Term**| Description| @@ -517,9 +530,9 @@ Call is usually used in the following scenarios: The following figure shows the call process. - Figure 1 Call process +Figure 1 Call process - ![call](figures/call.png) +![call](figures/call.png) - The CallerAbility uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the CalleeAbility. @@ -537,7 +550,7 @@ The following figure shows the call process. The following table describes the main APIs used for the call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). - **Table 2** Call APIs +**Table 2** Call APIs | API| Description| | -------- | -------- | @@ -571,7 +584,6 @@ For the CalleeAbility, implement the callback to receive data and the methods to ``` 3. Define the agreed parcelable data. - The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string. @@ -588,7 +600,7 @@ For the CalleeAbility, implement the callback to receive data and the methods to marshalling(messageSequence) { messageSequence.writeInt(this.num); messageSequence.writeString(this.str); - return true + return true; } unmarshalling(messageSequence) { @@ -600,9 +612,9 @@ For the CalleeAbility, implement the callback to receive data and the methods to ``` 4. Implement **Callee.on** and **Callee.off**. - + The time to register a listener for the CalleeAbility depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the UIAbility and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: - + ```ts const TAG: string = '[CalleeAbility]'; @@ -625,16 +637,16 @@ For the CalleeAbility, implement the callback to receive data and the methods to onCreate(want, launchParam) { try { this.callee.on(MSG_SEND_METHOD, sendMsgCallback); - } catch (error) { - console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); + } catch (err) { + console.error(`Failed to register. Code is ${err.code}, message is ${err.message}`); } } onDestroy() { try { this.callee.off(MSG_SEND_METHOD); - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); + } catch (err) { + console.error(`Failed to unregister. Code is ${err.code}, message is ${err.message}`); } } } @@ -661,9 +673,9 @@ For the CalleeAbility, implement the callback to receive data and the methods to caller.on('release', (msg) => { console.info(`caller onRelease is called ${msg}`); }) - console.info('caller register OnRelease succeed'); - } catch (error) { - console.info(`caller register OnRelease failed with ${error}`); + console.info('Succeeded in registering on release.'); + } catch (err) { + console.err(`Failed to caller register on release. Code is ${err.code}, message is ${err.message}`); } } @@ -672,15 +684,15 @@ For the CalleeAbility, implement the callback to receive data and the methods to this.caller = await context.startAbilityByCall({ bundleName: 'com.samples.CallApplication', abilityName: 'CalleeAbility' - }) + }); if (this.caller === undefined) { console.info('get caller failed') - return + return; } console.info('get caller success') this.regOnRelease(this.caller) - } catch (error) { - console.info(`get caller failed with ${error}`) + } (err) { + console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`); } } ``` diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md index 8f5762fcde0a766f454a2540708368048e1b01aa..c7aac3d4bc3acdb2601580646024ec1f8117473f 100644 --- a/en/application-dev/application-models/uiability-launch-type.md +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -17,7 +17,8 @@ The launch type of the UIAbility component refers to the state of the UIAbility Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. -**Figure 1** Demonstration effect in singleton mode +**Figure 1** Demonstration effect in singleton mode + ![uiability-launch-type1](figures/uiability-launch-type1.gif) > **NOTE** @@ -30,11 +31,11 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration ```json { "module": { - // ... + ... "abilities": [ { "launchType": "singleton", - // ... + ... } ] } @@ -56,11 +57,11 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick ```json { "module": { - // ... + ... "abilities": [ { "launchType": "multiton", - // ... + ... } ] } @@ -73,6 +74,7 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. **Figure 3** Demonstration effect in specified mode + ![uiability-launch-type3](figures/uiability-launch-type3.gif) For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility. @@ -82,11 +84,11 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ```json { "module": { - // ... + ... "abilities": [ { "launchType": "specified", - // ... + ... } ] } @@ -99,23 +101,24 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili // Configure an independent key for each UIAbility instance. // For example, in the document usage scenario, use the document path as the key. function getInstance() { - // ... + ... } + let context =...; // context is the UIAbilityContext of the initiator UIAbility. let want = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'SpecifiedAbility', - moduleName: 'module1', // moduleName is optional. - parameters: {// Custom information. - instanceKey: getInstance(), - }, + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'SpecifiedAbility', + moduleName: 'specified', // moduleName is optional. + parameters: {// Custom information. + instanceKey: getInstance(), + }, } - // context is the UIAbilityContext of the initiator UIAbility. - this.context.startAbility(want).then(() => { - // ... + + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -127,16 +130,16 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili import AbilityStage from '@ohos.app.ability.AbilityStage'; export default class MyAbilityStage extends AbilityStage { - onAcceptWant(want): string { - // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. - // In this example, SpecifiedAbility of module1 is returned. - if (want.abilityName === 'SpecifiedAbility') { - // The returned key string is a custom string. - return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; - } - - return ''; + onAcceptWant(want): string { + // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. + // In this example, SpecifiedAbility of module1 is returned. + if (want.abilityName === 'SpecifiedAbility') { + // The returned key string is a custom string. + return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; } + + return ''; + } } ``` @@ -154,4 +157,3 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili 3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3. 4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key of the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance. - \ No newline at end of file diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md index 57200abb8fbfb625e2e6c8999da5ad817e2e85b4..8a8506a71ffe130d4f39ed10a8fe60fbdead281e 100644 --- a/en/application-dev/application-models/uiability-lifecycle.md +++ b/en/application-dev/application-models/uiability-lifecycle.md @@ -9,7 +9,7 @@ The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Backgr **Figure 1** UIAbility lifecycle states -![Ability-Life-Cycle](figures/Ability-Life-Cycle.png) +![Ability-Life-Cycle](figures/Ability-Life-Cycle.png) ## Description of Lifecycle States @@ -22,24 +22,25 @@ The **Create** state is triggered when the UIAbility instance is created during ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Initialize the application. - } - // ... + onCreate(want, launchParam) { + // Initialize the application. + } + ... } ``` +> **NOTE** +> +> [Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. For details, see [Want](want-overview.md). ### WindowStageCreate and WindowStageDestory After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback. -**Figure 2** WindowStageCreate and WindowStageDestory - -![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) +**Figure 2** WindowStageCreate and WindowStageDestory +![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible. @@ -48,29 +49,44 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... - - onWindowStageCreate(windowStage: Window.WindowStage) { - // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible). - try { - windowStage.on('windowStageEvent', (data) => { - console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + - JSON.stringify(data)); - }); - } catch (exception) { - console.error('Failed to enable the listener for window stage event changes. Cause:' + - JSON.stringify(exception)); - }; - - // Set the UI loading. - windowStage.loadContent('pages/Index', (err, data) => { - // ... - }); + ... + + onWindowStageCreate(windowStage: window.WindowStage) { + // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible). + try { + windowStage.on('windowStageEvent', (data) => { + let stageEventType: window.WindowStageEventType = data; + switch (stageEventType) { + case window.WindowStageEventType.SHOWN: // Switch to the foreground. + console.info('windowStage foreground.'); + break; + case window.WindowStageEventType.ACTIVE: // Gain focus. + console.info('windowStage active.'); + break; + case window.WindowStageEventType.INACTIVE: // Lose focus. + console.info('windowStage inactive.'); + break; + case window.WindowStageEventType.HIDDEN: // Switch to the background. + console.info('windowStage background.'); + break; + default: + break; + } + }); + } catch (exception) { + console.error('Failed to enable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); } + + // Set UI loading. + windowStage.loadContent('pages/Index', (err, data) => { + ... + }); + } } ``` -> **NOTE** +> **NOTE**
> > For details about how to use WindowStage, see [Window Development](../windowmanager/application-window-stage.md). @@ -82,18 +98,23 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... - - onWindowStageDestroy() { - // Release UI resources. - // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback. - try { - windowStage.off('windowStageEvent'); - } catch (exception) { - console.error('Failed to disable the listener for window stage event changes. Cause:' + - JSON.stringify(exception)); - }; - } + windowStage: window.WindowStage; + ... + + onWindowStageCreate(windowStage: window.WindowStage) { + this.windowStage = windowStage; + ... + } + + onWindowStageDestroy() { + // Release UIresources. + // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback. + try { + this.windowStage.off('windowStageEvent'); + } catch (err) { + console.error(`Failed to disable the listener for window stage event changes. Code is ${err.code}, message is ${err.message}`); + }; + } } ``` @@ -115,16 +136,16 @@ When the application is switched to the background, you can disable positioning import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - // ... + ... - onForeground() { - // Apply for the resources required by the system or re-apply for the resources released in onBackground(). - } + onForeground() { + // Apply for the resources required by the system or re-apply for the resources released in onBackground(). + } - onBackground() { - // Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, - // for example, saving the status. - } + onBackground() { + // Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, + // for example, saving the status. + } } ``` @@ -137,13 +158,12 @@ The UIAbility instance is destroyed when **terminateSelf()** is called or the us ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... + ... - onDestroy() { - // Release system resources and save data. - } + onDestroy() { + // Release system resources and save data. + } } ``` diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md index e9a904e060e30e2523902aa4014664f6f0100e3a..5aa0ca79c49bd9f7566e7e0cc1ea977cea8c83d5 100644 --- a/en/application-dev/application-models/uiability-overview.md +++ b/en/application-dev/application-models/uiability-overview.md @@ -11,7 +11,9 @@ The following design philosophy is behind UIAbility: 2. Support for multiple device types and window forms -For details, see [Interpretation of the Application Model] (application-model-description.md). +> **NOTE** +> +> For details, see [Interpretation of the Application Model](application-model-description.md). The UIAbility division principles and suggestions are as follows: @@ -33,7 +35,7 @@ To enable an application to properly use a UIAbility component, declare the UIAb ```json { "module": { - // ... + ... "abilities": [ { "name": "EntryAbility", // Name of the UIAbility component. @@ -43,7 +45,7 @@ To enable an application to properly use a UIAbility component, declare the UIAb "label": "$string:EntryAbility_label", // Label of the UIAbility component. "startWindowIcon": "$media:icon", // Index of the icon resource file. "startWindowBackground": "$color:start_window_background", // Index of the background color resource file. - // ... + ... } ] } diff --git a/en/application-dev/application-models/uiability-usage.md b/en/application-dev/application-models/uiability-usage.md index fa8badc6d48c7e550922cb60a15d02eab9cc80b6..46959284ef3bfe179d465f5dae92b6f8538f680a 100644 --- a/en/application-dev/application-models/uiability-usage.md +++ b/en/application-dev/application-models/uiability-usage.md @@ -14,14 +14,14 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - // Main window is created. Set a main page for this ability. - windowStage.loadContent('pages/Index', (err, data) => { - // ... - }); - } + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created. Set a main page for this ability. + windowStage.loadContent('pages/Index', (err, data) => { + ... + }); + } - // ... + ... } ``` @@ -40,15 +40,14 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Obtain the context of the UIAbility instance. - let context = this.context; - - // ... - } + onCreate(want, launchParam) { + // Obtain the context of the UIAbility instance. + let context = this.context; + ... + } } ``` - + - Import the context module and define the **context** variable in the component. ```ts @@ -68,7 +67,7 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC // Page display. build() { - // ... + ... } } ``` @@ -93,7 +92,7 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC // Page display. build() { - // ... + ... } } ``` diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md index 1ce771daf195a09250a5fde05e0ce5a7acc60355..cf5cac43999a5efbe59659252b6b3db325cacd8a 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -6,43 +6,46 @@ [Want](../reference/apis/js-apis-app-ability-want.md) is an object that transfers information between application components. It is often used as a parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). For example, when UIAbilityA needs to start UIAbilityB and transfer some data to UIAbilityB, it can use the **want** parameter in **startAbility()** to transfer the data. **Figure 1** Want usage + ![usage-of-want](figures/usage-of-want.png) ## Types of Want -- **Explicit Want**: If **abilityName** and **bundleName** are specified when starting an ability, explicit Want is used. - Explicit Want is usually used to start a known target ability in the same application. The target ability is started by specifying **bundleName** of the application where the target ability is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target ability. - +- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an an application component, explicit Want is used. + + Explicit Want is usually used to start a known target application component in the same application. The target application component is started by specifying **bundleName** of the application where the target application component is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target application component. + ```ts let wantInfo = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', } ``` - -- **Implicit Want**: If **abilityName** is not specified when starting the ability, implicit Want is used. + +- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting the an application component, implicit Want is used. + Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select. - + ```ts let wantInfo = { - // Uncomment the line below if you want to implicitly query data only in the specific bundle. - // bundleName: 'com.example.myapplication', - action: 'ohos.want.action.search', - // entities can be omitted. - entities: [ 'entity.system.browsable' ], - uri: 'https://www.test.com:8080/query/student', - type: 'text/plain', + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.search', + // entities can be omitted. + entities: [ 'entity.system.browsable' ], + uri: 'https://www.test.com:8080/query/student', + type: 'text/plain', }; ``` - + > **NOTE** - > - Depending on the ability matching result, the following cases may be possible when you attempt to use implicit Want to start the ability. - > - No ability is matched. The startup fails. - > - An ability that meets the conditions is matched. That ability is started. - > - Multiple abilities that meet the conditions are matched. A dialog box is displayed for users to select one of them. + > - Depending on the application component matching result, the following cases may be possible when you attempt to use implicit Want to start the application component. + > - No application component is matched. The startup fails. + > - An application component that meets the conditions is matched. That application component is started. + > - Multiple application components that meet the conditions are matched. A dialog box is displayed for users to select one of them. > > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want. > diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md index b766c3420f56a7406bc345911a09bbf91bb6a187..3aa1a9fd29495b36a02d155e5d2ad48e94bce5ad 100644 --- a/en/application-dev/application-models/widget-development-fa.md +++ b/en/application-dev/application-models/widget-development-fa.md @@ -20,7 +20,7 @@ Before you get started, it would be helpful if you have a basic understanding of Figure 1 shows the working principles of the widget framework. -**Figure 1** Widget framework working principles in the FA model +**Figure 1** Widget framework working principles in the FA model ![form-extension](figures/form-extension.png) The widget host consists of the following modules: @@ -122,48 +122,48 @@ To create a widget in the FA model, implement the widget lifecycle callbacks. Ge ```ts export default { - onCreate(want) { - console.info('FormAbility onCreate'); - // Called when the widget is created. The widget provider should return the widget data binding class. - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - }, - onCastToNormal(formId) { - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. - console.info('FormAbility onCastToNormal'); - }, - onUpdate(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.info('FormAbility onUpdate'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - formProvider.updateForm(formId, formData).catch((error) => { - console.info('FormAbility updateForm, error:' + JSON.stringify(error)); - }); - }, - onVisibilityChange(newStatus) { - // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. - console.info('FormAbility onVisibilityChange'); - }, - onEvent(formId, message) { - // If the widget supports event triggering, override this method and implement the trigger. - console.info('FormAbility onEvent'); - }, - onDestroy(formId) { - // Delete widget data. - console.info('FormAbility onDestroy'); - }, - onAcquireFormState(want) { - console.info('FormAbility onAcquireFormState'); - return formInfo.FormState.READY; - }, + onCreate(want) { + console.info('FormAbility onCreate'); + // Called when the widget is created. The widget provider should return the widget data binding class. + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + }, + onCastToNormal(formId) { + // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + console.info('FormAbility onCastToNormal'); + }, + onUpdate(formId) { + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + console.info('FormAbility onUpdate'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + formProvider.updateForm(formId, formData).catch((error) => { + console.info('FormAbility updateForm, error:' + JSON.stringify(error)); + }); + }, + onVisibilityChange(newStatus) { + // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. + console.info('FormAbility onVisibilityChange'); + }, + onEvent(formId, message) { + // If the widget supports event triggering, override this method and implement the trigger. + console.info('FormAbility onEvent'); + }, + onDestroy(formId) { + // Delete widget data. + console.info('FormAbility onDestroy'); + }, + onAcquireFormState(want) { + console.info('FormAbility onAcquireFormState'); + return formInfo.FormState.READY; + }, } ``` @@ -188,15 +188,15 @@ The widget configuration file is named **config.json**. Find the **config.json** ```json - "js": [{ - "name": "widget", - "pages": ["pages/index/index"], - "window": { - "designWidth": 720, - "autoDesignWidth": true - }, - "type": "form" - }] + "js": [{ + "name": "widget", + "pages": ["pages/index/index"], + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "type": "form" + }] ``` - The **abilities** module in the **config.json** file corresponds to **FormAbility** of the widget. The internal structure is described as follows: @@ -275,7 +275,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean } } -// ... +... onCreate(want) { console.info('FormAbility onCreate'); @@ -293,7 +293,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean let formData = formBindingData.createFormBindingData(obj); return formData; } -// ... +... ``` You should override **onDestroy** to implement widget data deletion. @@ -313,14 +313,14 @@ async function deleteFormInfo(formId: string) { } } -// ... +... onDestroy(formId) { console.info('FormAbility onDestroy'); // Delete the persistent widget instance data. // Implement this API based on project requirements. deleteFormInfo(formId); } -// ... +... ``` For details about how to implement persistent data storage, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md). @@ -543,4 +543,3 @@ The following is an example: } } ``` - diff --git a/en/application-dev/application-models/windowextensionability.md b/en/application-dev/application-models/windowextensionability.md index 0f6e28b89790cfa1dd7dc471ed3a450280f19a4a..3c1d364cd50e73c8232c5ba2482e04b2ca2a6077 100644 --- a/en/application-dev/application-models/windowextensionability.md +++ b/en/application-dev/application-models/windowextensionability.md @@ -11,7 +11,7 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat > **NOTE** > -> **WindowExtensionAbility** is a system API. To embed a third-party application in another application and display it over the application, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md). +> **WindowExtensionAbility** is a system API. To embed a third-party application in another application and display it over the application, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../faqs/full-sdk-switch-guide.md). > @@ -43,7 +43,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i onWindowReady(window) { window.loadContent('WindowExtAbility/pages/index1').then(() => { window.getProperties().then((pro) => { - console.log("WindowExtension " + JSON.stringify(pro)); + console.info("WindowExtension " + JSON.stringify(pro)); }) window.show(); }) @@ -110,4 +110,5 @@ System applications can load the created WindowExtensionAbility through the Abil .backgroundColor(0x64BB5c) } } - ``` \ No newline at end of file + ``` + diff --git a/en/application-dev/file-management/share-app-file.md b/en/application-dev/file-management/share-app-file.md index d9ee1d90904f5cdb43cd1987a66b09668200bc81..c2f8f8d12f5ff056e043fb632cff9752c95256ce 100644 --- a/en/application-dev/file-management/share-app-file.md +++ b/en/application-dev/file-management/share-app-file.md @@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing The file URIs are in the following format: - file://<bundleName>/<path>/\#networkid=<networkid> + file://<bundleName>/<path> - **file**: indicates a file URI. @@ -20,8 +20,6 @@ The file URIs are in the following format: - *path*: specifies the application sandbox path of the file. -- *networkid* (optional): specifies the device to which the file belongs in a distributed file system. Leave this parameter unspecified if the file location does not need to be set. - ## Sharing a File with Another Application Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path). diff --git a/en/application-dev/media/audio-playback-concurrency.md b/en/application-dev/media/audio-playback-concurrency.md index 0b36594f6bef62c7ba7588bc8977af67609a6c9d..fee7e776d68914ad376e01b8fe40ee84e3da4224 100644 --- a/en/application-dev/media/audio-playback-concurrency.md +++ b/en/application-dev/media/audio-playback-concurrency.md @@ -14,7 +14,7 @@ The audio interruption policy determines the operations (for example, pause, res Two audio interruption modes, specified by [InterruptMode](../reference/apis/js-apis-audio.md#interruptmode9), are preset in the audio interruption policy: -- **SHARED_MODE**: Multiple audio streams created by an application share one audio focus. The concurrency rules between these audio streams are determined by the application, without the use of the audio interruption policy. However, if another application needs to play audio while one of these audio streams is being played, the audio interruption policy is triggered. +- **SHARE_MODE**: Multiple audio streams created by an application share one audio focus. The concurrency rules between these audio streams are determined by the application, without the use of the audio interruption policy. However, if another application needs to play audio while one of these audio streams is being played, the audio interruption policy is triggered. - **INDEPENDENT_MODE**: Each audio stream created by an application has an independent audio focus. When multiple audio streams are played concurrently, the audio interruption policy is triggered. diff --git a/en/application-dev/media/audio-playback-overview.md b/en/application-dev/media/audio-playback-overview.md index d17970d6de9b8b238db74d971ad5f58c605462eb..5ef7a6f9c4d08719a71c9e07f34fa1104802fcc6 100644 --- a/en/application-dev/media/audio-playback-overview.md +++ b/en/application-dev/media/audio-playback-overview.md @@ -8,7 +8,7 @@ OpenHarmony provides multiple classes for you to develop audio playback applicat - [AudioRenderer](using-audiorenderer-for-playback.md): provides ArkTS and JS API to implement audio output. It supports only the PCM format and requires applications to continuously write audio data. The applications can perform data preprocessing, for example, setting the sampling rate and bit width of audio files, before audio input. This class can be used to develop more professional and diverse playback applications. To use this class, you must have basic audio processing knowledge. -- [OpenSLES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio output in PCM format and is applicable to playback applications that are ported from other embedded platforms or that implements audio output at the native layer. +- [OpenSL ES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio output in PCM format and is applicable to playback applications that are ported from other embedded platforms or that implements audio output at the native layer. - [TonePlayer](using-toneplayer-for-playback.md): provides ArkTS and JS API to implement the playback of dialing tones and ringback tones. It can be used to play the content selected from a fixed type range, without requiring the input of media assets or audio data. This class is application to specific scenarios where dialing tones and ringback tones are played. is available only to system applications. diff --git a/en/application-dev/media/audio-recording-overview.md b/en/application-dev/media/audio-recording-overview.md index 698255fddd78d98f9e635b16b3db94e6980bd4a0..2c6fb6fe5b8ffd0e82478d450e64bfc0e10257c6 100644 --- a/en/application-dev/media/audio-recording-overview.md +++ b/en/application-dev/media/audio-recording-overview.md @@ -8,7 +8,7 @@ OpenHarmony provides multiple classes for you to develop audio recording applica - [AudioCapturer](using-audiocapturer-for-recording.md): provides ArkTS and JS API to implement audio input. It supports only the PCM format and requires applications to continuously read audio data. The application can perform data processing after audio output. This class can be used to develop more professional and diverse recording applications. To use this class, you must have basic audio processing knowledge. -- [OpenSLES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio input in PCM format and is applicable to recording applications that are ported from other embedded platforms or that implements audio input at the native layer. +- [OpenSL ES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio input in PCM format and is applicable to recording applications that are ported from other embedded platforms or that implements audio input at the native layer. ## Precautions for Developing Audio Recording Applications diff --git a/en/application-dev/media/avplayer-avrecorder-overview.md b/en/application-dev/media/avplayer-avrecorder-overview.md index 051ca3b66ce1839046a2e783a8c274c304625045..3bf9b785b93a32b60b73c902449b9b019e651a2b 100644 --- a/en/application-dev/media/avplayer-avrecorder-overview.md +++ b/en/application-dev/media/avplayer-avrecorder-overview.md @@ -59,6 +59,7 @@ The table below lists the supported protocols. | -------- | -------- | | Local VOD| The file descriptor is supported, but the file path is not.| | Network VoD| HTTP, HTTPS, and HLS are supported.| +| Live webcasting| HLS is supported.| The table below lists the supported audio playback formats. diff --git a/en/application-dev/media/figures/audiocapturer-status-change.png b/en/application-dev/media/figures/audiocapturer-status-change.png index aadbc4fb6470b7cdc0f399ee5954a96c01a7f7c3..ff76a8414f7a254af7d2796e44f2c2555dc9185f 100644 Binary files a/en/application-dev/media/figures/audiocapturer-status-change.png and b/en/application-dev/media/figures/audiocapturer-status-change.png differ diff --git a/en/application-dev/media/media-application-overview.md b/en/application-dev/media/media-application-overview.md index d350482e61e7bc9659054b0426c10ce07da88045..6ca7bbd61bccab668076da76841e785d1918abe9 100644 --- a/en/application-dev/media/media-application-overview.md +++ b/en/application-dev/media/media-application-overview.md @@ -2,7 +2,7 @@ ## Multimedia Subsystem Architecture -The multimedia subsystem provides the capability of processing users' visual and auditory information. For example, it can be used to collect, compress, store, decompress, and play audio and video information. Based on the type of media information to process, the media system is usually divided into four modules: audio, media, camera, and image. +The multimedia subsystem provides the capability of processing users' visual and auditory information. For example, it can be used to collect, compress, store, decompress, and play audio and video information. Based on the type of media information to process, the multimedia subsystem subsystem is usually divided into four modules: audio, media, camera, and image. As shown in the figure below, the multimedia subsystem provides APIs for developing audio/video, camera, and gallery applications, and provides adaptation and acceleration for different hardware chips. In the middle part, it provides core media functionalities and management mechanisms in the form of services. diff --git a/en/application-dev/media/using-audiorenderer-for-playback.md b/en/application-dev/media/using-audiorenderer-for-playback.md index 11934e669813fa7a89ceef43bd2c3795db6bad75..d72637819259e3752a33b37d6f645786793cfc38 100644 --- a/en/application-dev/media/using-audiorenderer-for-playback.md +++ b/en/application-dev/media/using-audiorenderer-for-playback.md @@ -151,9 +151,6 @@ export default class AudioRendererDemo { console.info(`${TAG}: creating AudioRenderer success`); this.renderModel = renderer; this.renderModel.on('stateChange', (state) => { // Set the events to listen for. A callback is invoked when the AudioRenderer is switched to the specified state. - if (state == 1) { - console.info('audio renderer state is: STATE_PREPARED'); - } if (state == 2) { console.info('audio renderer state is: STATE_RUNNING'); } diff --git a/en/application-dev/media/using-avplayer-for-playback.md b/en/application-dev/media/using-avplayer-for-playback.md index 6cb6ab1e67ef0ae8a44e04fa915ad87bcc9ed024..9af55fb71b489f7b3ece342969c72d18ed90eaab 100644 --- a/en/application-dev/media/using-avplayer-for-playback.md +++ b/en/application-dev/media/using-avplayer-for-playback.md @@ -12,7 +12,7 @@ During application development, you can use the **state** attribute of the AVPla **Figure 1** Playback state transition -![Playback state change](figures/playback-status-change.png) +![Playback status change](figures/playback-status-change.png) For details about the state, see [AVPlayerState](../reference/apis/js-apis-media.md#avplayerstate9). When the AVPlayer is in the **prepared**, **playing**, **paused**, or **completed** state, the playback engine is working and a large amount of RAM is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the instance. @@ -68,7 +68,9 @@ import common from '@ohos.app.ability.common'; export class AVPlayerDemo { private avPlayer; private count: number = 0; - + private isSeek: boolean = true; // Specify whether the seek operation is supported. + private fileSize: number = -1; + private fd: number = 0; // Set AVPlayer callback functions. setAVPlayerCallback() { // Callback function for the seek operation. @@ -102,8 +104,13 @@ export class AVPlayerDemo { case 'playing': // This state is reported upon a successful callback of play(). console.info('AVPlayer state playing called.'); if (this.count !== 0) { - console.info('AVPlayer start to seek.'); - this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the audio clip. + if (this.isSeek) { + console.info('AVPlayer start to seek.'); + this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the audio clip. + } else { + // When the seek operation is not supported, the playback continues until it reaches the end. + console.info('AVPlayer wait to play end.'); + } } else { this.avPlayer.pause(); // Call pause() to pause the playback. } @@ -145,6 +152,7 @@ export class AVPlayerDemo { // Open the corresponding file address to obtain the file descriptor and assign a value to the URL to trigger the reporting of the initialized state. let file = await fs.open(path); fdPath = fdPath + '' + file.fd; + this.isSeek = true; // The seek operation is supported. this.avPlayer.url = fdPath; } @@ -158,10 +166,85 @@ export class AVPlayerDemo { // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. let context = getContext(this) as common.UIAbilityContext; let fileDescriptor = await context.resourceManager.getRawFd('01.mp3'); + this.isSeek = true; // The seek operation is supported. // Assign a value to fdSrc to trigger the reporting of the initialized state. this.avPlayer.fdSrc = fileDescriptor; } + + // The following demo shows how to use the file system to open the sandbox address, obtain the media file address, and play the media file with the seek operation using the dataSrc attribute. + async avPlayerDataSrcSeekDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + // dataSrc indicates the playback source address. When the seek operation is supported, fileSize indicates the size of the file to be played. The following describes how to assign a value to fileSize. + let src = { + fileSize: -1, + callback: (buf, length, pos) => { + let num = 0; + if (buf == undefined || length == undefined || pos == undefined) { + return -1; + } + num = fs.readSync(this.fd, buf, { offset: pos, length: length }); + if (num > 0 && (this.fileSize >= pos)) { + return num; + } + return -1; + } + } + let context = getContext(this) as common.UIAbilityContext; + // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. + let pathDir = context.filesDir; + let path = pathDir + '/01.mp3'; + await fs.open(path).then((file) => { + this.fd = file.fd; + }) + // Obtain the size of the file to be played. + this.fileSize = fs.statSync(path).size; + src.fileSize = this.fileSize; + this.isSeek = true; // The seek operation is supported. + this.avPlayer.dataSrc = src; + } + + // The following demo shows how to use the file system to open the sandbox address, obtain the media file address, and play the media file without the seek operation using the dataSrc attribute. + async avPlayerDataSrcNoSeekDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + let context = getContext(this) as common.UIAbilityContext; + let src: object = { + fileSize: -1, + callback: (buf, length, pos) => { + let num = 0; + if (buf == undefined || length == undefined) { + return -1; + } + num = fs.readSync(this.fd, buf); + if (num > 0) { + return num; + } + return -1; + } + } + // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. + let pathDir = context.filesDir; + let path = pathDir + '/01.mp3'; + await fs.open(path).then((file) => { + this.fd = file.fd; + }) + this.isSeek = false; // The seek operation is not supported. + this.avPlayer.dataSrc = src; + } + + // The following demo shows how to play live streams by setting the network address through the URL. + async avPlayerLiveDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + this.isSeek = false; // The seek operation is not supported. + this.avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8'; + } } ``` - - \ No newline at end of file diff --git a/en/application-dev/media/using-avsession-controller.md b/en/application-dev/media/using-avsession-controller.md index 5e4b69d8b48f5acad64f120892062e66d67c6b12..958661d90cec031cbbca1bb7c11ccb80e4dc0e66 100644 --- a/en/application-dev/media/using-avsession-controller.md +++ b/en/application-dev/media/using-avsession-controller.md @@ -1,6 +1,6 @@ # AVSession Controller -Media Controller preset in OpenHarmony functions as the controller to interact with audio and video applications, for example, obtaining and displaying media information and delivering control commands. +Media Controller preset in OpenHarmony functions as the controller to interact with audio and video applications, for example, obtaining and displaying media information and delivering playback control commands. You can develop a system application (for example, a new playback control center or voice assistant) as the controller to interact with audio and video applications in the system. @@ -8,24 +8,50 @@ You can develop a system application (for example, a new playback control center - AVSessionDescriptor: session information, including the session ID, session type (audio/video), custom session name (**sessionTag**), information about the corresponding application (**elementName**), and whether the session is pined on top (isTopSession). -- Top session: session with the highest priority in the system, for example, a session that is being played. Generally, the controller must hold an **AVSessionController** object to communicate with a session. However, the controller can directly communicate with the top session, for example, directly sending a control command or key event, without holding an **AVSessionController** object. +- Top session: session with the highest priority in the system, for example, a session that is being played. Generally, the controller must hold an **AVSessionController** object to communicate with a session. However, the controller can directly communicate with the top session, for example, directly sending a playback control command or key event, without holding an **AVSessionController** object. ## Available APIs -The table below lists the key APIs used by the controller. The APIs use either a callback or promise to return the result. The APIs listed below use a callback. They provide the same functions as their counterparts that use a promise. +The key APIs used by the controller are classified into the following types: +1. APIs called by the **AVSessionManager** object, which is obtained by means of import. An example API is **AVSessionManager.createController(sessionId)**. +2. APIs called by the **AVSessionController** object. An example API is **controller.getAVPlaybackState()**. + +Asynchronous JavaScript APIs use either a callback or promise to return the result. The APIs listed below use a callback. They provide the same functions as their counterparts that use a promise. For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). -| API| Description| +### APIs Called by the AVSessionManager Object + +| API| Description| +| -------- | -------- | +| getAllSessionDescriptors(callback: AsyncCallback<Array<Readonly<AVSessionDescriptor>>>): void | Obtains the descriptors of all AVSessions in the system.| +| createController(sessionId: string, callback: AsyncCallback<AVSessionController>): void | Creates an AVSessionController.| +| getValidCommands(callback: AsyncCallback<Array<AVControlCommandType>>): void | Obtains valid commands supported by the AVSession.
Playback control commands listened by an audio and video application when it accesses the AVSession are considered as valid commands supported by the AVSession. For details, see [Provider of AVSession](using-avsession-developer.md).| +| getLaunchAbility(callback: AsyncCallback<WantAgent>): void | Obtains the UIAbility that is configured in the AVSession and can be started.
The UIAbility configured here is started when a user operates the UI of the controller, for example, clicking a widget in Media Controller.| +| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to an AVSession through the AVSessionController object.| +| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to the top session.| +| sendControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a playback control command to an AVSession through the AVSessionController object.| +| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a playback control command to the top session.| +| getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\>>): void10+ | Obtains the descriptors of historical sessions.| + +### APIs Called by the AVSessionController Object + +| API| Description| | -------- | -------- | -| getAllSessionDescriptors(callback: AsyncCallback<Array<Readonly<AVSessionDescriptor>>>): void | Obtains the descriptors of all AVSessions in the system.| -| createController(sessionId: string, callback: AsyncCallback<AVSessionController>): void | Creates an AVSessionController.| -| getValidCommands(callback: AsyncCallback<Array<AVControlCommandType>>): void | Obtains valid commands supported by the AVSession.
Control commands listened by an audio and video application when it accesses the AVSession are considered as valid commands supported by the AVSession. For details, see [Provider of AVSession](using-avsession-developer.md).| -| getLaunchAbility(callback: AsyncCallback<WantAgent>): void | Obtains the UIAbility that is configured in the AVSession and can be started.
The UIAbility configured here is started when a user operates the UI of the controller, for example, clicking a widget in Media Controller.| -| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to an AVSession through the AVSessionController object.| -| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to the top session.| -| sendControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a control command to an AVSession through the AVSessionController object.| -| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a control command to the top session.| +| getAVPlaybackState(callback: AsyncCallback<AVPlaybackState>): void | Obtains the information related to the playback state.| +| getAVMetadata(callback: AsyncCallback<AVMetadata>): void | Obtains the session metadata.| +| getOutputDevice(callback: AsyncCallback<OutputDeviceInfo>): void | Obtains the output device information.| +| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to the session corresponding to this controller.| +| getLaunchAbility(callback: AsyncCallback<WantAgent>): void | Obtains the **WantAgent** object saved by the application in the session.| +| isActive(callback: AsyncCallback<boolean>): void | Checks whether the session is activated.| +| destroy(callback: AsyncCallback<void>): void | Destroys this controller. A controller can no longer be used after being destroyed.| +| getValidCommands(callback: AsyncCallback<Array<AVControlCommandType>>): void | Obtains valid commands supported by the session.| +| sendControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a playback control command to the session through the controller.| +| sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback<void>): void10+ | Sends a custom playback control command to the session through the controller.| +| getAVQueueItems(callback: AsyncCallback<Array<AVQueueItem>>): void10+ | Obtains the information related to the items in the playlist.| +| getAVQueueTitle(callback: AsyncCallback<string>): void10+ | Obtains the name of the playlist.| +| skipToQueueItem(itemId: number, callback: AsyncCallback<void>): void10+ | Sends the ID of an item in the playlist to the session for processing. The session can play the song.| +| getExtras(callback: AsyncCallback<{[key: string]: Object}>): void10+ | Obtains the custom media packet set by the provider.| ## How to Develop @@ -48,13 +74,26 @@ To enable a system application to access the AVSession service as a controller, AVSessionManager.createController(descriptor.sessionId).then((controller) => { g_controller.push(controller); }).catch((err) => { - console.error(`createController : ERROR : ${err.message}`); + console.error(`Failed to create controller. Code: ${err.code}, message: ${err.message}`); }); }); }).catch((err) => { - console.error(`getAllSessionDescriptors : ERROR : ${err.message}`); + console.error(`Failed to get all session descriptors. Code: ${err.code}, message: ${err.message}`); }); + // Obtain the descriptors of historical sessions. + avSession.getHistoricalSessionDescriptors().then((descriptors) => { + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors.length : ${descriptors.length}`); + if (descriptors.length > 0){ + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].isActive : ${descriptors[0].isActive}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].type : ${descriptors[0].type}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionTag : ${descriptors[0].sessionTag}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].sessionId : ${descriptors[0].sessionId}`); + console.info(`getHistoricalSessionDescriptors : SUCCESS : descriptors[0].elementName.bundleName : ${descriptors[0].elementName.bundleName}`); + } + }).catch((err) => { + console.error(`Failed to get historical session descriptors, error code: ${err.code}, error message: ${err.message}`); + }); ``` 2. Listen for the session state and service state events. @@ -74,7 +113,7 @@ To enable a system application to access the AVSession service as a controller, AVSessionManager.createController(session.sessionId).then((controller) => { g_controller.push(controller); }).catch((err) => { - console.info(`createController : ERROR : ${err.message}`); + console.error(`Failed to create controller. Code: ${err.code}, message: ${err.message}`); }); }); @@ -103,7 +142,7 @@ To enable a system application to access the AVSession service as a controller, // Subscribe to the 'sessionServiceDie' event. AVSessionManager.on('sessionServiceDie', () => { // The server is abnormal, and the application clears resources. - console.info("Server exception."); + console.info(`Server exception.`); }) ``` @@ -117,6 +156,10 @@ To enable a system application to access the AVSession service as a controller, - **validCommandChange**: triggered when the valid commands supported by the session changes. - **outputDeviceChange**: triggered when the output device changes. - **sessionDestroy**: triggered when a session is destroyed. + - **sessionEvent**: triggered when the custom session event changes. + - **extrasChange**: triggered when the custom media packet of the session changes. + - **queueItemsChange**: triggered when one or more items in the custom playlist of the session changes. + - **queueTitleChange**: triggered when the custom playlist name of the session changes. The controller can listen for events as required. @@ -124,18 +167,18 @@ To enable a system application to access the AVSession service as a controller, // Subscribe to the 'activeStateChange' event. controller.on('activeStateChange', (isActive) => { if (isActive) { - console.info("The widget corresponding to the controller is highlighted."); + console.info(`The widget corresponding to the controller is highlighted.`); } else { - console.info("The widget corresponding to the controller is invalid."); + console.info(`The widget corresponding to the controller is invalid.`); } }); // Subscribe to the 'sessionDestroy' event to enable the controller to get notified when the session dies. controller.on('sessionDestroy', () => { - console.info('on sessionDestroy : SUCCESS '); + info(`on sessionDestroy : SUCCESS `); controller.destroy().then(() => { - console.info('destroy : SUCCESS '); + console.info(`destroy : SUCCESS`); }).catch((err) => { - console.info(`destroy : ERROR :${err.message}`); + console.error(`Failed to destroy session. Code: ${err.code}, message: ${err.message}`); }); }); @@ -164,10 +207,26 @@ To enable a system application to access the AVSession service as a controller, controller.on('outputDeviceChange', (device) => { console.info(`on outputDeviceChange device isRemote : ${device.isRemote}`); }); + // Subscribe to custom session event changes. + controller.on('sessionEvent', (eventName, eventArgs) => { + console.info(`Received new session event, event name is ${eventName}, args are ${JSON.stringify(eventArgs)}`); + }); + // Subscribe to custom media packet changes. + controller.on('extrasChange', (extras) => { + console.info(`Received custom media packet, packet data is ${JSON.stringify(extras)}`); + }); + // Subscribe to custom playlist item changes. + controller.on('queueItemsChange', (items) => { + console.info(`Caught queue items change, items length is ${items.length}`); + }); + // Subscribe to custom playback name changes. + controller.on('queueTitleChange', (title) => { + console.info(`Caught queue title change, title is ${title}`); + }); ``` 4. Obtain the media information transferred by the provider for display on the UI, for example, displaying the track being played and the playback state in Media Controller. - + ```ts async getInfoFromSessionByController() { // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. @@ -186,19 +245,36 @@ To enable a system application to access the AVSession service as a controller, let avPlaybackState: AVSessionManager.AVPlaybackState = await controller.getAVPlaybackState(); console.info(`get playbackState by controller : ${avPlaybackState.state}`); console.info(`get favoriteState by controller : ${avPlaybackState.isFavorite}`); + // Obtain the playlist items of the session. + let queueItems: Array = await controller.getAVQueueItems(); + console.info(`get queueItems length by controller : ${queueItems.length}`); + // Obtain the playlist name of the session. + let queueTitle: string = await controller.getAVQueueTitle(); + console.info(`get queueTitle by controller : ${queueTitle}`); + // Obtain the custom media packet of the session. + let extras: any = await controller.getExtras(); + console.info(`get custom media packets by controller : ${JSON.stringify(extras)}`); + // Obtain the ability information provided by the application corresponding to the session. + let agent: WantAgent = await controller.getLaunchAbility(); + console.info(`get want agent info by controller : ${JSON.stringify(agent)}`); + // Obtain the current playback position of the session. + let currentTime: number = controller.getRealPlaybackPositionSync(); + console.info(`get current playback time by controller : ${currentTime}`); + // Obtain valid commands supported by the session. + let validCommands: Array = await controller.getValidCommands(); + console.info(`get valid commands by controller : ${JSON.stringify(validCommands)}`); } ``` 5. Control the playback behavior, for example, sending a command to operate (play/pause/previous/next) the item being played in Media Controller. - After listening for the control command event, the audio and video application serving as the provider needs to implement the corresponding operation. + After listening for the playback control command event, the audio and video application serving as the provider needs to implement the corresponding operation. - ```ts async sendCommandToSessionByController() { // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. let controller: AVSessionManager.AVSessionController = ALLREADY_HAVE_A_CONTROLLER; - // Obtain the commands supported by the session. + // Obtain valid commands supported by the session. let validCommandTypeArray: Array = await controller.getValidCommands(); console.info(`get validCommandArray by controller : length : ${validCommandTypeArray.length}`); // Deliver the 'play' command. @@ -222,11 +298,28 @@ To enable a system application to access the AVSession service as a controller, let avCommand: AVSessionManager.AVControlCommand = {command:'playNext'}; controller.sendControlCommand(avCommand); } + // Deliver a custom playback control command. + let commandName: string = 'custom command'; + let args = { + command : 'This is my custom command' + } + await controller.sendCommonCommand(commandName, args).then(() => { + console.info(`SendCommonCommand successfully`); + }).catch((err) => { + console.error(`Failed to send common command. Code: ${err.code}, message: ${err.message}`); + }) + // Set the ID of an item in the specified playlist for the session to play. + let queueItemId: number = 0; + await controller.skipToQueueItem(queueItemId).then(() => { + console.info(`SkipToQueueItem successfully`); + }).catch((err) => { + console.error(`Failed to skip to queue item. Code: ${err.code}, message: ${err.message}`); + }); } ``` 6. When the audio and video application exits, cancel the listener and release the resources. - + ```ts async destroyController() { // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. @@ -235,9 +328,9 @@ To enable a system application to access the AVSession service as a controller, // Destroy the AVSessionController object. After being destroyed, it is no longer available. controller.destroy(function (err) { if (err) { - console.info(`Destroy controller ERROR : code: ${err.code}, message: ${err.message}`); + console.error(`Failed to destroy controller. Code: ${err.code}, message: ${err.message}`); } else { - console.info('Destroy controller SUCCESS'); + console.info(`Destroy controller SUCCESS`); } }); } diff --git a/en/application-dev/media/using-avsession-developer.md b/en/application-dev/media/using-avsession-developer.md index 077f0b956a5fb6abaf26c647132bdbb81e78fc63..bf0b914647b9c364bea0ac86a30def88fe3c0f52 100644 --- a/en/application-dev/media/using-avsession-developer.md +++ b/en/application-dev/media/using-avsession-developer.md @@ -1,12 +1,12 @@ # AVSession Provider -An audio and video application needs to access the AVSession service as a provider in order to display media information in the controller (for example, Media Controller) and respond to control commands delivered by the controller. +An audio and video application needs to access the AVSession service as a provider in order to display media information in the controller (for example, Media Controller) and respond to playback control commands delivered by the controller. ## Basic Concepts - AVMetadata: media data related attributes, including the IDs of the current media asset (assetId), previous media asset (previousAssetId), and next media asset (nextAssetId), title, author, album, writer, and duration. -- AVPlaybackState: playback state attributes, including the playback state, position, speed, buffered time, loop mode, and whether the media asset is favorited (**isFavorite**). +- AVPlaybackState: playback state attributes, including the playback state, position, speed, buffered time, loop mode, media item being played (activeItemId), custom media data (extras), and whether the media asset is favorited (isFavorite). ## Available APIs @@ -14,28 +14,43 @@ The table below lists the key APIs used by the provider. The APIs use either a c For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). -| API| Description| +| API| Description| | -------- | -------- | -| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback<AVSession>): void | Creates an AVSession.
Only one AVSession can be created for a UIAbility.| -| setAVMetadata(data: AVMetadata, callback: AsyncCallback<void>): void | Sets AVSession metadata.| -| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback<void>): void | Sets the AVSession playback state.| -| setLaunchAbility(ability: WantAgent, callback: AsyncCallback<void>): void | Starts a UIAbility.| -| getController(callback: AsyncCallback<AVSessionController>): void | Obtains the controller of the AVSession.| -| activate(callback: AsyncCallback<void>): void | Activates the AVSession.| -| destroy(callback: AsyncCallback<void>): void | Destroys the AVSession.| +| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback<AVSession>): void | Creates an AVSession.
Only one AVSession can be created for a UIAbility.| +| setAVMetadata(data: AVMetadata, callback: AsyncCallback<void>): void | Sets AVSession metadata.| +| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback<void>): void | Sets the AVSession playback state.| +| setLaunchAbility(ability: WantAgent, callback: AsyncCallback<void>): void | Starts a UIAbility.| +| getController(callback: AsyncCallback<AVSessionController>): void | Obtains the controller of the AVSession.| +| getOutputDevice(callback: AsyncCallback<OutputDeviceInfo>): void | Obtains the output device information.| +| activate(callback: AsyncCallback<void>): void | Activates the AVSession.| +| deactivate(callback: AsyncCallback<void>): void | Deactivates this session.| +| destroy(callback: AsyncCallback<void>): void | Destroys the AVSession.| +| setAVQueueItems(items: Array<AVQueueItem>, callback: AsyncCallback<void>): void 10+ | Sets a playlist.| +| setAVQueueTitle(title: string, callback: AsyncCallback<void>): void10+ | Sets a name for the playlist.| +| dispatchSessionEvent(event: string, args: {[key: string]: Object}, callback: AsyncCallback<void>): void10+ | Dispatches a custom session event.| +| setExtras(extras: {[key: string]: Object}, callback: AsyncCallback<void>): void10+ | Sets a custom media packet in the form of a key-value pair.| ## How to Develop To enable an audio and video application to access the AVSession service as a provider, proceed as follows: 1. Call an API in the **AVSessionManager** class to create and activate an **AVSession** object. - + ```ts + // To create an AVSession object, you must first obtain the application context. You can set a global variable in the EntryAbility file of the application to store the application context. + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + globalThis.context = this.context; // Set the global variable globalThis.context to store the application context. + } + // Other APIs of the EntryAbility class. + } + + // Start to create and activate an AVSession object. import AVSessionManager from '@ohos.multimedia.avsession'; // Import the AVSessionManager module. // Create an AVSession object. async createSession() { - let session: AVSessionManager.AVSession = await AVSessionManager.createAVSession(this.context, 'SESSION_NAME', 'audio'); + let session: AVSessionManager.AVSession = await AVSessionManager.createAVSession(globalThis.context, 'SESSION_NAME', 'audio'); session.activate(); console.info(`session create done : sessionId : ${session.sessionId}`); } @@ -46,22 +61,22 @@ To enable an audio and video application to access the AVSession service as a pr - AVPlaybackState The controller will call an API in the **AVSessionController** class to obtain the information and display or process the information. - + ```ts async setSessionInfo() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. - let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; // The player logic that triggers changes in the session metadata and playback state is omitted here. // Set necessary session metadata. let metadata: AVSessionManager.AVMetadata = { - assetId: "0", - title: "TITLE", - artist: "ARTIST" + assetId: '0', + title: 'TITLE', + artist: 'ARTIST' }; session.setAVMetadata(metadata).then(() => { - console.info('SetAVMetadata successfully'); + console.info(`SetAVMetadata successfully`); }).catch((err) => { - console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`); + console.error(`Failed to set AVMetadata. Code: ${err.code}, message: ${err.message}`); }); // Set the playback state to paused and set isFavorite to false. let playbackState: AVSessionManager.AVPlaybackState = { @@ -70,86 +85,230 @@ To enable an audio and video application to access the AVSession service as a pr }; session.setAVPlaybackState(playbackState, function (err) { if (err) { - console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); + console.error(`Failed to set AVPlaybackState. Code: ${err.code}, message: ${err.message}`); } else { - console.info('SetAVPlaybackState successfully'); + console.info(`SetAVPlaybackState successfully`); } }); + // Set a playlist. + let queueItemDescription_1 = { + mediaId: '001', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.xxx.com', + extras: {'extras':'any'} + }; + let queueItem_1 = { + itemId: 1, + description: queueItemDescription_1 + }; + let queueItemDescription_2 = { + mediaId: '002', + title: 'music_name', + subtitle: 'music_sub_name', + description: 'music_description', + icon: PIXELMAP_OBJECT, + iconUri: 'http://www.xxx.com', + extras: {'extras':'any'} + }; + let queueItem_2 = { + itemId: 2, + description: queueItemDescription_2 + }; + let queueItemsArray = [queueItem_1, queueItem_2]; + session.setAVQueueItems(queueItemsArray).then(() => { + console.info(`SetAVQueueItems successfully`); + }).catch((err) => { + console.error(`Failed to set AVQueueItem, error code: ${err.code}, error message: ${err.message}`); + }); + // Set a name for the playlist. + let queueTitle = 'QUEUE_TITLE'; + session.setAVQueueTitle(queueTitle).then(() => { + console.info(`SetAVQueueTitle successfully`); + }).catch((err) => { + console.info(`Failed to set AVQueueTitle, error code: ${err.code}, error message: ${err.message}`); + }); } ``` 3. Set the UIAbility to be started by the controller. The UIAbility configured here is started when a user operates the UI of the controller, for example, clicking a widget in Media Controller. The UIAbility is set through the **WantAgent** API. For details, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). - + ```ts - import WantAgent from "@ohos.app.ability.wantAgent"; + import wantAgent from "@ohos.app.ability.wantAgent"; ``` ```ts - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. - let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; let wantAgentInfo = { wants: [ { - bundleName: "com.example.musicdemo", - abilityName: "com.example.musicdemo.MainAbility" + bundleName: 'com.example.musicdemo', + abilityName: 'com.example.musicdemo.MainAbility' } ], - operationType: WantAgent.OperationType.START_ABILITIES, + operationType: wantAgent.OperationType.START_ABILITIES, requestCode: 0, - wantAgentFlags: [WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] } - WantAgent.getWantAgent(wantAgentInfo).then((agent) => { - session.setLaunchAbility(agent) + wantAgent.getWantAgent(wantAgentInfo).then((agent) => { + session.setLaunchAbility(agent); }) ``` -4. Listen for control commands delivered by the controller, for example, Media Controller. +4. Set a custom session event. The controller performs an operation after receiving the event. + > **NOTE** > - > After the provider registers a listener for the control command event, the event will be reflected in **getValidCommands()** of the controller. In other words, the controller determines that the command is valid and triggers the corresponding event as required. To ensure that the control commands delivered by the controller can be executed normally, the provider should not use a null implementation for listening. - + > The data set through **dispatchSessionEvent** is not saved in the **AVSession** object or AVSession service. + ```ts - async setListenerForMesFromController() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. - let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; - // Generally, logic processing on the player is implemented in the listener. - // After the processing is complete, use the setter to synchronize the playback information. For details, see the code snippet above. - session.on('play', () => { - console.info('on play , do play task'); - - // do some tasks ··· - }); - session.on('pause', () => { - console.info('on pause , do pause task'); - // do some tasks ··· - }); - session.on('stop', () => { - console.info('on stop , do stop task'); - // do some tasks ··· - }); - session.on('playNext', () => { - console.info('on playNext , do playNext task'); - // do some tasks ··· - }); - session.on('playPrevious', () => { - console.info('on playPrevious , do playPrevious task'); - // do some tasks ··· - }); + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; + let eventName = 'dynamic_lyric'; + let args = { + lyric : 'This is my lyric' } + await session.dispatchSessionEvent(eventName, args).then(() => { + console.info(`Dispatch session event successfully`); + }).catch((err) => { + console.error(`Failed to dispatch session event. Code: ${err.code}, message: ${err.message}`); + }) ``` -5. Obtain an **AVSessionController** object for this **AVSession** object for interaction. - +5. Set a custom media packet. The controller performs an operation after receiving the event. + + > **NOTE** + > + > The data set by using **setExtras** is stored in the AVSession service. The data lifecycle is the same as that of the **AVSession** object, and the controller corresponding to the object can use **getExtras** to obtain the data. + + ```ts + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; + let extras = { + extra : 'This is my custom meida packet' + } + await session.setExtras(extras).then(() => { + console.info(`Set extras successfully`); + }).catch((err) => { + console.error(`Failed to set extras. Code: ${err.code}, message: ${err.message}`); + }) + ``` + +6. Listen for playback control commands or events delivered by the controller, for example, Media Controller. + + Both fixed playback control commands and advanced playback control events can be listened for. + + - Listening for Fixed Playback Control Commands + + > **NOTE** + > + > After the provider registers a listener for fixed playback control commands, the commands will be reflected in **getValidCommands()** of the controller. In other words, the controller determines that the command is valid and triggers the corresponding event as required. To ensure that the playback control commands delivered by the controller can be executed normally, the provider should not use a null implementation for listening. + + Fixed playback control commands on the session side include basic operation commands such as play, pause, previous, and next. For details, see [AVControlCommand](../reference/apis/js-apis-avsession.md). + + ```ts + async setListenerForMesFromController() { + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; + // Generally, logic processing on the player is implemented in the listener. + // After the processing is complete, use the setter to synchronize the playback information. For details, see the code snippet above. + session.on('play', () => { + console.info(`on play , do play task`); + // do some tasks ··· + }); + session.on('pause', () => { + console.info(`on pause , do pause task`); + // do some tasks ··· + }); + session.on('stop', () => { + console.info(`on stop , do stop task`); + // do some tasks ··· + }); + session.on('playNext', () => { + console.info(`on playNext , do playNext task`); + // do some tasks ··· + }); + session.on('playPrevious', () => { + console.info(`on playPrevious , do playPrevious task`); + // do some tasks ··· + }); + session.on('fastForward', () => { + console.info(`on fastForward , do fastForward task`); + // do some tasks ··· + }); + session.on('rewind', () => { + console.info(`on rewind , do rewind task`); + // do some tasks ··· + }); + + session.on('seek', (time) => { + console.info(`on seek , the seek time is ${time}`); + // do some tasks ··· + }); + session.on('setSpeed', (speed) => { + console.info(`on setSpeed , the speed is ${speed}`); + // do some tasks ··· + }); + session.on('setLoopMode', (mode) => { + console.info(`on setLoopMode , the loop mode is ${mode}`); + // do some tasks ··· + }); + session.on('toggleFavorite', (assetId) => { + console.info(`on toggleFavorite , the target asset Id is ${assetId}`); + // do some tasks ··· + }); + } + ``` + + - Listening for Advanced Playback Control Events + + The following advanced playback control events can be listened for: + + - **skipToQueueItem**: triggered when an item in the playlist is selected. + - **handleKeyEvent**: triggered when a key is pressed. + - **outputDeviceChange**: triggered when the output device changes. + - **commonCommand**: triggered when a custom playback control command changes. + + ```ts + async setListenerForMesFromController() { + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; + // Generally, logic processing on the player is implemented in the listener. + // After the processing is complete, use the setter to synchronize the playback information. For details, see the code snippet above. + session.on('skipToQueueItem', (itemId) => { + console.info(`on skipToQueueItem , do skip task`); + // do some tasks ··· + }); + session.on('handleKeyEvent', (event) => { + console.info(`on handleKeyEvent , the event is ${JSON.stringify(event)}`); + // do some tasks ··· + }); + session.on('outputDeviceChange', (device) => { + console.info(`on outputDeviceChange , the device info is ${JSON.stringify(device)}`); + // do some tasks ··· + }); + session.on('commonCommand', (commandString, args) => { + console.info(`on commonCommand , command is ${commandString}, args are ${JSON.stringify(args)}`); + // do some tasks ··· + }); + } + ``` + +7. Obtain an **AVSessionController** object for this **AVSession** object for interaction. + ```ts async createControllerFromSession() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. - let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; // Obtain an AVSessionController object for this AVSession object. let controller: AVSessionManager.AVSessionController = await session.getController(); - // The AVSessionController object can interact with the AVSession object, for example, by delivering a control command. + // The AVSessionController object can interact with the AVSession object, for example, by delivering a playback control command. let avCommand: AVSessionManager.AVControlCommand = {command:'play'}; controller.sendControlCommand(avCommand); @@ -163,13 +322,14 @@ To enable an audio and video application to access the AVSession service as a pr } ``` -6. When the audio and video application exits and does not need to continue playback, cancel the listener and destroy the **AVSession** object. - The code snippet below is used for canceling the listener for control commands: +8. When the audio and video application exits and does not need to continue playback, cancel the listener and destroy the **AVSession** object. + + The code snippet below is used for canceling the listener for playback control commands: ```ts async unregisterSessionListener() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. - let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; // Cancel the listener of the AVSession object. session.off('play'); @@ -177,22 +337,27 @@ To enable an audio and video application to access the AVSession service as a pr session.off('stop'); session.off('playNext'); session.off('playPrevious'); + session.off('skipToQueueItem'); + session.off('handleKeyEvent'); + session.off('outputDeviceChange'); + session.off('commonCommand'); } ``` - - The code snippet below is used for destroying the AVSession object: - - ```ts + + + The code snippet below is used for destroying the AVSession object: + + ```ts async destroySession() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. - let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; - // Destroy the AVSession object. - session.destroy(function (err) { - if (err) { - console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`); - } else { - console.info('Destroy : SUCCESS '); - } - }); + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. + let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION; + // Destroy the AVSession object. + session.destroy(function (err) { + if (err) { + console.error(`Failed to destroy session. Code: ${err.code}, message: ${err.message}`); + } else { + console.info(`Destroy : SUCCESS `); + } + }); } - ``` + ``` \ No newline at end of file diff --git a/en/application-dev/media/using-distributed-avsession.md b/en/application-dev/media/using-distributed-avsession.md index c1835d661fdd2b57b7dce0f2507dbea748eaea7e..fc5c49b9804b67750228a010c1c53d58a2086bbf 100644 --- a/en/application-dev/media/using-distributed-avsession.md +++ b/en/application-dev/media/using-distributed-avsession.md @@ -36,15 +36,15 @@ To enable a system application that accesses the AVSession service as the contro let audioDevices; await audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { audioDevices = data; - console.info('Promise returned to indicate that the device list is obtained.'); + console.info(`Promise returned to indicate that the device list is obtained.`); }).catch((err) => { - console.info(`getDevices : ERROR : ${err.message}`); + console.error(`Failed to get devices. Code: ${err.code}, message: ${err.message}`); }); AVSessionManager.castAudio('all', audioDevices).then(() => { - console.info('createController : SUCCESS'); + console.info(`createController : SUCCESS`); }).catch((err) => { - console.info(`createController : ERROR : ${err.message}`); + console.error(`Failed to cast audio. Code: ${err.code}, message: ${err.message}`); }); ``` diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index fff4aa830ddc45e7d20e0fd06655adfdc5243fe5..f745f2f25120f7068de6634af56aa1f443c5b5d9 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -78,7 +78,9 @@ export class AVPlayerDemo { private avPlayer; private count: number = 0; private surfaceID: string; // The surfaceID parameter specifies the window used to display the video. Its value is obtained through the XComponent. - + private isSeek: boolean = true; // Specify whether the seek operation is supported. + private fileSize: number = -1; + private fd: number = 0; // Set AVPlayer callback functions. setAVPlayerCallback() { // Callback function for the seek operation. @@ -113,8 +115,13 @@ export class AVPlayerDemo { case 'playing': // This state is reported upon a successful callback of play(). console.info('AVPlayer state playing called.'); if (this.count !== 0) { - console.info('AVPlayer start to seek.'); - this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the video clip. + if (this.isSeek) { + console.info('AVPlayer start to seek.'); + this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the video clip. + } else { + // When the seek operation is not supported, the playback continues until it reaches the end. + console.info('AVPlayer wait to play end.'); + } } else { this.avPlayer.pause(); // Call pause() to pause the playback. } @@ -152,10 +159,11 @@ export class AVPlayerDemo { let context = getContext(this) as common.UIAbilityContext; // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. let pathDir = context.filesDir; - let path = pathDir + '/H264_AAC.mp4'; + let path = pathDir + '/H264_AAC.mp4'; // Open the corresponding file address to obtain the file descriptor and assign a value to the URL to trigger the reporting of the initialized state. let file = await fs.open(path); fdPath = fdPath + '' + file.fd; + this.isSeek = true; // The seek operation is supported. this.avPlayer.url = fdPath; } @@ -169,9 +177,86 @@ export class AVPlayerDemo { // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. let context = getContext(this) as common.UIAbilityContext; let fileDescriptor = await context.resourceManager.getRawFd('H264_AAC.mp4'); + this.isSeek = true; // The seek operation is supported. // Assign a value to fdSrc to trigger the reporting of the initialized state. this.avPlayer.fdSrc = fileDescriptor; } + + // The following demo shows how to use the file system to open the sandbox address, obtain the media file address, and play the media file with the seek operation using the dataSrc attribute. + async avPlayerDataSrcSeekDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + // dataSrc indicates the playback source address. When the seek operation is supported, fileSize indicates the size of the file to be played. The following describes how to assign a value to fileSize. + let src = { + fileSize: -1, + callback: (buf, length, pos) => { + let num = 0; + if (buf == undefined || length == undefined || pos == undefined) { + return -1; + } + num = fs.readSync(this.fd, buf, { offset: pos, length: length }); + if (num > 0 && (this.fileSize >= pos)) { + return num; + } + return -1; + } + } + let context = getContext(this) as common.UIAbilityContext; + // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. + let pathDir = context.filesDir; + let path = pathDir + '/H264_AAC.mp4'; + await fs.open(path).then((file) => { + this.fd = file.fd; + }) + // Obtain the size of the file to be played. + this.fileSize = fs.statSync(path).size; + src.fileSize = this.fileSize; + this.isSeek = true; // The seek operation is supported. + this.avPlayer.dataSrc = src; + } + + // The following demo shows how to use the file system to open the sandbox address, obtain the media file address, and play the media file without the seek operation using the dataSrc attribute. + async avPlayerDataSrcNoSeekDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + let context = getContext(this) as common.UIAbilityContext; + let src: object = { + fileSize: -1, + callback: (buf, length, pos) => { + let num = 0; + if (buf == undefined || length == undefined) { + return -1; + } + num = fs.readSync(this.fd, buf); + if (num > 0) { + return num; + } + return -1; + } + } + // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. + let pathDir = context.filesDir; + let path = pathDir + '/H264_AAC.mp4'; + await fs.open(path).then((file) => { + this.fd = file.fd; + }) + this.isSeek = false; // The seek operation is not supported. + this.avPlayer.dataSrc = src; + } + + // The following demo shows how to play live streams by setting the network address through the URL. + async avPlayerLiveDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + this.isSeek = false; // The seek operation is not supported. + this.avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8'; // Play live webcasting streams using HLS. + } } ``` diff --git a/en/application-dev/quick-start/arkts-observed-and-objectlink.md b/en/application-dev/quick-start/arkts-observed-and-objectlink.md index a84802480d1fbd3eb4b6942d5b8f1a2f5f642aa1..1282545cc1d65a1acdc90da3ac5a2828cf611ca9 100644 --- a/en/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/en/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -316,7 +316,7 @@ class StringArray extends Array { -Declare a class that extends from** Array**: **class StringArray extends Array\ {}** and create an instance of **StringArray**. The use of the **new** operator is required for the \@Observed class decorator to work properly. +Declare a class that extends from **Array**: **class StringArray extends Array\ {}** and create an instance of **StringArray**. The use of the **new** operator is required for the \@Observed class decorator to work properly. ```ts diff --git a/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md b/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md index 2b8f2293918bef081b6f6377a99d6fdb2e35a03e..90a06cc468f5dc383ec3cf15a9f2d8a894f63239 100644 --- a/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md +++ b/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @@ -19,7 +19,7 @@ The following lifecycle callbacks are provided for the lifecycle of a page, that - [onBackPress](../reference/arkui-ts/ts-custom-component-lifecycle.md#onbackpress): Invoked when the user clicks the Back button. -The following lifecycle callbacks are provided for the lifecycle of a custom component, which is one decorated with \@Component: +The following lifecycle callbacks are provided for the lifecycle of a component, that is, the lifecycle of a custom component decorated with \@Component: - [aboutToAppear](../reference/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear): Invoked when the custom component is about to appear. Specifically, it is invoked after a new instance of the custom component is created and before its **build** function is executed. @@ -134,7 +134,7 @@ struct MyComponent { Child() } // When this.showChild is false, the Child child component is deleted, and Child aboutToDisappear is invoked. - Button('create or delete Child').onClick(() => { + Button('delete Child').onClick(() => { this.showChild = false; }) // Because of the pushing from the current page to Page2, onPageHide is invoked. diff --git a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md index 7086569f912a0c447228643958c38b3bd16e0045..95b6665c834a4bdf281b4712717e71f51659c112 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md +++ b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @@ -75,15 +75,17 @@ interface DataChangeListener { } ``` -| Declaration | Parameter Type | Description | -| ---------------------------------------- | -------------------------------------- | ---------------------------------------- | -| onDataReloaded(): void | - | Invoked when all data is reloaded. | -| onDataAdded(index: number):void | number | Invoked when data is added to the position indicated by the specified index.
**index**: index of the position where data is added. | -| onDataMoved(from: number, to: number): void | from: number,
to: number | Invoked when data is moved.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| -| onDataChanged(index: number): void | number | Invoked when data in the position indicated by the specified index is changed.
**index**: listener for data changes. | -| onDataAdd(index: number): void | number | Invoked when data is added to the position indicated by the specified index.
**index**: index of the position where data is added. | -| onDataMove(from: number, to: number): void | from: number,
to: number | Invoked when data is moved.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| -| onDataChanged(index: number): void | number | Invoked when data in the position indicated by the specified index is changed.
**index**: index of the position where data is changed.| +| Declaration | Parameter Type | Description | +| ------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------ | +| onDataReloaded(): void | - | Invoked when all data is reloaded. | +| onDataAdded(index: number):void(deprecated) | number | Invoked when data is added to the position indicated by the specified index.
This API is deprecated since API version 8. You are advised to use **onDataAdd** instead.
**index**: index of the position where data is added.| +| onDataMoved(from: number, to: number): void(deprecated) | from: number,
to: number | Invoked when data is moved.
This API is deprecated since API version 8. You are advised to use **onDataMove** instead.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| +| onDataDeleted(index: number):void(deprecated) | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly.
This API is deprecated since API version 8. You are advised to use **onDataDelete** instead.
**index**: index of the position where data is deleted.| +| onDataChanged(index: number): void(deprecated) | number | Invoked when data in the position indicated by the specified index is changed.
This API is deprecated since API version 8. You are advised to use **onDataChange** instead.
**index**: listener for data changes.| +| onDataAdd(index: number): void8+ | number | Invoked when data is added to the position indicated by the specified index.
**index**: index of the position where data is added.| +| onDataMove(from: number, to: number): void8+ | from: number,
to: number | Invoked when data is moved.
**from**: original position of data; **to**: target position of data.
**NOTE**
The ID must remain unchanged before and after data movement. If the ID changes, APIs for deleting and adding data must be called.| +| onDataDelete(index: number):void8+ | number | Invoked when data is deleted from the position indicated by the specified index. LazyForEach will update the displayed content accordingly.
**index**: index of the position where data is deleted.
**NOTE**
Before **onDataDelete** is called, ensure that the corresponding data in **dataSource** has been deleted. Otherwise, undefined behavior will occur during page rendering.| +| onDataChange(index: number): void8+ | number | Invoked when data in the position indicated by the specified index is changed.
**index**: index of the position where data is changed.| ## Restrictions diff --git a/en/application-dev/quick-start/atomicService-aging.md b/en/application-dev/quick-start/atomicService-aging.md index 6b393b5a9456e3cbf840dbf9cf5655c46d832658..75c4be084bc7e103f504924f936daea71b8fe5de 100644 --- a/en/application-dev/quick-start/atomicService-aging.md +++ b/en/application-dev/quick-start/atomicService-aging.md @@ -4,7 +4,7 @@ Space management for atomic services is necessary from two aspects. On the one h ## Managing Quota for Atomic Service Data Directories -Set a storage quota for the data sandbox directory of an atomic service. This quota can be obtained through the system parameter **persist.sys.bms.aging.policy.atomicservice.datasize.threshold**. The default value is 1024 MB. When the quota is used up, writing data will return an error message. +Set a storage quota for the data sandbox directory of an atomic service. This quota can be obtained through the system parameter **persist.sys.bms.aging.policy.atomicservice.datasize.threshold**. The default value is 50 MB. When the quota is used up, writing data will return an error message. You can run the [param get/set](../../device-dev/subsystems/subsys-boot-init-plugin.md) command to view and set system parameters. diff --git a/en/application-dev/quick-start/cross-app-hsp.md b/en/application-dev/quick-start/cross-app-hsp.md index db971e348908dbc6f6ca87f5d84d162b6bac0997..4d4115490d7060843fe008cda7281fcc2a003ada 100644 --- a/en/application-dev/quick-start/cross-app-hsp.md +++ b/en/application-dev/quick-start/cross-app-hsp.md @@ -17,34 +17,29 @@ An inter-application HSP works by combining the following parts: HSP: contains the actual implementation code, including the JS/TS code, C++ libraries, resources, and configuration files. It is either released to the application market or integrated into the system version. ### Integrating the HAR in an Inter-Application HSP -Define the interfaces to be exported in the **index.d.ets** file in the HAR, which is the entry to the declaration file exported by the inter-application HSP. The path of the **index.d.ets** file is as follows: +Define the interfaces to be exported in the **index.ets** file in the HAR, which is the entry to the declaration file exported by the inter-application HSP. The path to the **index.ets** file is as follows: ``` -src -├── main -| └── module.json5 -├── index.d.ets +liba +├── src +│ └── main +│ ├── ets +│ │ ├── pages +│ │ └── index.ets +│ ├── resources +│ └── module.json5 └── oh-package.json5 ``` -Below is an example of the **index.d.ets** file content: -```ts -@Component -export declare struct UIComponent { - build():void; -} - -export declare function hello(): string; - -export declare function foo1(): string; +Below is an example of the **index.ets** file content: -export declare function foo2(): string; - -export declare function nativeHello(): string; +```ts +// liba/src/main/ets/index.ets +export { hello, foo1, foo2, nativeMulti, UIComponent } from './ui/MyUIComponent' ``` -In the example, **UIComponent** is an ArkUI component, **hello()**, **foo1()**, and **foo2()** are TS methods, and **nativeHello()** is a native method. Specific implementation is as follows: +In the example, **UIComponent** is an ArkUI component, **hello()**, **foo1()**, and **foo2()** are TS methods, and **nativeMulti()** is a native method. Specific implementation is as follows: #### ArkUI Components The following is an implementation example of ArkUI components in the HSP: ```ts -// lib/src/main/ets/ui/MyUIComponent.ets +// liba/src/main/ets/ui/MyUIComponent.ets @Component export struct UIComponent { @State message: string = 'Hello World' @@ -63,6 +58,7 @@ export struct UIComponent { #### **TS Methods** The following is an implementation example of TS methods in the HSP: ```ts +// liba/src/main/ets/ui/MyUIComponent.ets export function hello(name: string): string { return "hello + " + name; } @@ -74,50 +70,22 @@ export function foo1() { export function foo2() { return "foo2"; } + ``` #### **Native Methods** -The following is an implementation example of native methods in the HSP: -```C++ -#include "napi/native_api.h" -#include -#include -#include - -const std::string libname = "liba"; -const std::string version = "v10001"; - -static napi_value Hello(napi_env env, napi_callback_info info) { - napi_value ret; - std::string msg = libname + ":native hello, " + version; - napi_create_string_utf8(env, msg.c_str(), msg.length(), &ret); - return ret; -} +The HSP can contain .so files compiled in C++. The HSP indirectly exports the native method in the .so file. In this example, the **multi** API in the **libnative.so** file is exported. -EXTERN_C_START -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor desc[] = { - {"nativeHello", nullptr, Hello, nullptr, nullptr, nullptr, napi_default, nullptr}}; - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; -} -EXTERN_C_END - -static napi_module demoModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "liba", - .nm_priv = ((void *)0), - .reserved = {0}, -}; - -extern "C" __attribute__((constructor)) void RegisterLibaModule(void) { - napi_module_register(&demoModule); +```ts +// liba/src/main/ets/ui/MyUIComponent.ets +import native from "libnative.so" + +export function nativeMulti(a: number, b: number) { + return native.multi(a, b); } ``` + ### Using the Capabilities Exported from the HAR -To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391) on the HAR. The dependency information will then be generated in the **module.json5** file of the corresponding module, as shown in the following: +To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/creating_har_api9-0000001518082393-V3#section611662614153) on the HAR. The dependency information will then be generated in the **module.json5** file of the corresponding module, as shown in the following: ```json "dependencies": [ { @@ -180,7 +148,7 @@ struct Index { #### Referencing Native Methods in the HAR To reference the native methods exported from the HAR, use **import** as follows: ``` ts -import { nativeHello } from 'liba' +import { nativeMulti } from 'liba' @Component struct Index { @@ -190,7 +158,7 @@ struct Index { Button('Button') .onClick(()=>{ // Reference the native method in the HAR. - nativeHello(); + nativeMulti(); }) } .width('100%') @@ -207,11 +175,6 @@ Inter-application HSPs are not completely integrated into an application. They a ### Inter-Application HSP Debugging Mode You can debug an inter-application HSP after it is distributed to a device. If the aforementioned distribution methods are not applicable, you can distribute the HSP by running **bm** commands. The procedure is as follows: - -> **NOTE** -> -> Do not reverse steps 2 and 3. Otherwise, your application will fail to be installed due to a lack of the required inter-application HSP. For more information about the **bm** commands, see [Bundle Management](../../readme/bundle-management.md). - 1. Obtain the inter-application HSP installation package. 2. Run the following **bm** command to install the inter-application HSP. ``` @@ -222,3 +185,7 @@ bm install -s sharebundle.hsp bm install -p feature.hap ``` 4. Start your application and start debugging. + +> **NOTE** +> +> Do not reverse steps 2 and 3. Otherwise, your application will fail to be installed due to a lack of the required inter-application HSP. For more information about the **bm** commands, see [bm Commands](../../readme/bundle-management.md#bm-commands). \ No newline at end of file diff --git a/en/application-dev/quick-start/har-package.md b/en/application-dev/quick-start/har-package.md index 63b5fcfd10437ac2140a17bcc1daf690e780c791..587af49e108ed1cfedbd9a190ea7858bc470073c 100644 --- a/en/application-dev/quick-start/har-package.md +++ b/en/application-dev/quick-start/har-package.md @@ -2,7 +2,7 @@ A Harmony Archive (HAR) is a static shared package that can contain code, C++ libraries, resources, and configuration files. It enables modules and projects to share code related to ArkUI components, resources, and more. Unlike a Harmony Ability Package (HAP), a HAR cannot be independently installed on a device. Instead, it can be referenced only as the dependency of an application module. ## Creating a HAR Module -You can kickstart your HAR module development with the module template of the **Library** type in DevEco Studio. By default, obfuscation is disabled for the HAR module. To enable this feature, set **artifactType** in the **build-profile.json5** file of the HAR module to **obfuscation** as follows: +You can [create a HAR module in DevEco Studio](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/creating_har_api9-0000001518082393-V3#section143510369612). To better protect your source code, enable obfuscation for the HAR module so that DevEco Studio compiles, obfuscates, and compresses code during HAR building. To enable obfuscation, open the **build-profile.json5** file of the HAR module and set **artifactType** to **obfuscation** as follows: ```json { @@ -12,15 +12,13 @@ You can kickstart your HAR module development with the module template of the ** } } ``` -The value options of **artifactType** are as follows, and the default value is **original**: +The value options of **artifactType** are as follows, with the default value being **original**: - **original**: Code is not obfuscated. - **obfuscation**: Code is obfuscated using Uglify. -When obfuscation is enabled, DevEco Studio compiles, obfuscates, and compresses code during HAR building, thereby protecting your code assets. - > **NOTE** > -> If **artifactType** is set to **obfuscation**, **apiType** must be set to **stageMode**, because obfuscation is available only in the stage model. +> Obfuscation is available only in the stage model. Therefore, if **artifactType** is set to **obfuscation**, **apiType** must be set to **stageMode**. ## Precautions for HAR Development - The HAR does not support the declaration of **abilities** and **extensionAbilities** in its configuration file. @@ -88,12 +86,12 @@ export { func2 } from './src/main/ts/test' ``` ### Resources Resources are packed into the HAR when it is being compiled and packaged. During compilation and building of a HAP, DevEco Studio collects resource files from the HAP module and its dependent modules. If the resource files of different modules have the same name, DevEco Studio overwrites the resource files based on the following priorities (in descending order): -- AppScope (supported only by the stage model of API version 9) +- AppScope (only for the stage model of API version 9) - Modules in the HAP file - If resource conflicts occur between dependent HAR modules, they are overwritten based on the dependency sequence. (The module that is higher in the dependency sequence list has higher priority.) ## Referencing ArkUI Components, APIs, and Resources in the HAR -To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434#section89674298391) on the HAR. +To start with, [configure dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/creating_har_api9-0000001518082393-V3#section611662614153) on the HAR. ### Reference ArkUI Components in the HAR @@ -170,3 +168,7 @@ struct Index { } } ``` + +## Releasing a HAR + +Follow the [instructions](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/creating_har_api9-0000001518082393-V3#section1213451811512) to release a HAR. diff --git a/en/application-dev/quick-start/in-app-hsp.md b/en/application-dev/quick-start/in-app-hsp.md index 4c0cc3c7dffc1c41d0011dd644a94a84424808dc..cb31cbc5b703c3caec5c34b4e0702657b56d26f5 100644 --- a/en/application-dev/quick-start/in-app-hsp.md +++ b/en/application-dev/quick-start/in-app-hsp.md @@ -5,7 +5,7 @@ The in-application HSP is released with the Application Package (App Pack) of th ## Developing an In-Application HSP -You can kickstart your HSP development with the HSP template in DevEco Studio. In this example, an HSP module named **library** is created. The basic project directory structure is as follows: +[Create an HSP module in DevEco Studio](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/hsp-0000001521396322-V3#section7717162312546). In this example, an HSP module named **library** is created. The basic project directory structure is as follows: ``` library ├── src @@ -88,7 +88,7 @@ if **Image("common/example.png")** is used in the HSP module, the **\** c ### Exporting Native Methods The HSP can contain .so files compiled in C++. The HSP indirectly exports the native method in the .so file. In this example, the **multi** method in the **libnative.so** file is exported. ```ts -// ibrary/src/main/ets/utils/nativeTest.ts +// library/src/main/ets/utils/nativeTest.ts import native from "libnative.so" export function nativeMulti(a: number, b: number) { @@ -103,15 +103,9 @@ export { nativeMulti } from './utils/nativeTest' ``` ## Using the In-Application HSP -To use APIs in the HSP, first configure the dependency on the HSP in the **oh-package.json5** file of the module that needs to call the APIs (called the invoking module). If the HSP and the invoking module are in the same project, the APIs can be referenced locally. The sample code is as follows: -```json -// entry/oh-package.json5 -"dependencies": { - "library": "file:../library" -} -``` -You can now call the external APIs of the HSP in the same way as calling the APIs in the HAR. -In this example, the external APIs are the following ones exported from **library**: +To use APIs in the HSP, first [configure the dependency](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/hsp-0000001521396322-V3#section6161154819195) on the HSP in the **oh-package.json5** file of the module that needs to call the APIs (called the invoking module). +You can then call the external APIs of the HSP in the same way as calling the APIs in the HAR. In this example, the external APIs are the following ones exported from **library**: + ```ts // library/src/main/ets/index.ets export { Log, add, minus } from './utils/test' diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index 2d830a4b8318afdf61f4d9d7531e71a3a6420858..ac141ad75d108f68d25007491a15062ae958563e 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -309,7 +309,7 @@ Set **icon**, **label**, and **skills** under **abilities** in the **module.json | [metadata](#metadata)| Metadata information of the UIAbility component.| Object array| Yes (initial value: left empty)| | exported | Whether the UIAbility component can be called by other applications.
- **true**: The UIAbility component can be called by other applications.
- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | continuable | Whether the UIAbility component can be [migrated](../application-models/hop-cross-device-migration.md).
- **true**: The UIAbility component can be migrated.
- **false**: The UIAbility component cannot be migrated.| Boolean| Yes (initial value: **false**)| -| [skills](#skills) | Feature set of [wants](../application-models/want-overview.md) that can be received by the current UIAbility or ExtensionAbility component.
Configuring rule:
- For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an OpenHarmony application. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.)
- For HAPs of the feature type, you can configure **skills** attributes with the entry capability for an OpenHarmony application, but not for an OpenHarmony service.| Object array| Yes (initial value: left empty)| +| [skills](#skills) | Feature set of [wants](../application-models/want-overview.md) that can be received by the current UIAbility or ExtensionAbility component.
Configuration rules:
- For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an OpenHarmony application. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.)
- For HAPs of the feature type, you can configure **skills** attributes with the entry capability for an OpenHarmony application, but not for an OpenHarmony service.| Object array| Yes (initial value: left empty)| | backgroundModes | Continuous tasks of the UIAbility component.
Continuous tasks are classified into the following types:
- **dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.
- **audioPlayback**: audio playback service.
- **audioRecording**: audio recording service.
- **location**: location and navigation services.
- **bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables).
- **multiDeviceConnection**: multi-device interconnection service.
- **wifiInteraction**: Wi-Fi scanning, connection, and transmission services (as used in the Multi-screen Collaboration and clone features)
- **voip**: voice/video call and VoIP services.
- **taskKeeping**: computing service.| String array| Yes (initial value: left empty)| | startWindowIcon | Index to the icon file of the UIAbility component startup page. Example: **$media:icon**.
The value is a string with a maximum of 255 bytes.| String| No| | startWindowBackground | Index to the background color resource file of the UIAbility component startup page. Example: **$color:red**.
The value is a string with a maximum of 255 bytes.| String| No| diff --git a/en/application-dev/quick-start/quickfix-principles.md b/en/application-dev/quick-start/quickfix-principles.md index 4c0a1f684cfc1ff71c5ad9a2594ae8823e178e82..0431534f0f46bb7bb0988c538d84628767ce8bfb 100644 --- a/en/application-dev/quick-start/quickfix-principles.md +++ b/en/application-dev/quick-start/quickfix-principles.md @@ -10,7 +10,7 @@ Quick fix is a technical means provided by the OpenHarmony system for developers * The bundle name and application version number configured in the quick fix package must be the same as those of the installed application. Otherwise, the deployment will fail. * Make sure the version of the quick fix package to deploy is later than that of the one previously deployed. Otherwise, the deployment will fail. * The signature information of the quick fix package must be the same as that of the application to be fixed. Otherwise, the deployment will fail. -* Installing an application update will delete quick fix package. +* Installing an application update will delete the quick fix package. ## Structure of the Quick Fix Package @@ -18,7 +18,7 @@ Quick fix is a technical means provided by the OpenHarmony system for developers
The preceding figure shows the structure of the quick fix package released by an OpenHarmony application. * As shown in the figure, the quick fix package comes in two formats: * .appqf (Application Quick Fix) -
There is a one-to-one mapping between the .appqf file and App Pack of an application. For details, see [Application Package Structure in Stage Model](application-package-structure-stage). +
There is a one-to-one mapping between the .appqf file and App Pack of an application. For details, see [Application Package Structure in Stage Model](application-package-structure-stage.md). * The .appqf file is used to release OpenHarmony applications to the application market and cannot be directly installed on devices. * An .appqf file consists of one or more .hqf (Harmony Ability Package Quick Fix) files, which are extracted from the .appqf file by the application market and then distributed to specific devices. * The .appqf file must contain the developer's signature information before being released to the application market. For details about how to sign the file, see [hapsigner Overview](../security/hapsigntool-overview.md). diff --git a/en/application-dev/quick-start/resource-categories-and-access.md b/en/application-dev/quick-start/resource-categories-and-access.md index aa5e53ae90c1794125f5b6ae8a8f7a5115128743..f87ae3594a44b17b34233adfd0d8127a2be34028 100644 --- a/en/application-dev/quick-start/resource-categories-and-access.md +++ b/en/application-dev/quick-start/resource-categories-and-access.md @@ -8,8 +8,6 @@ During application development, you may need to use different resources, such as ## Resource Categories -### resources Directory - Resource files used during application development must be stored in specified directories for management. The **resources** directory consists of three types of subdirectories: the **base** subdirectory, qualifiers subdirectories, and the **rawfile** subdirectory. The common resource files used across projects in the stage model are stored in the **resources** directory under **AppScope**. The **base** subdirectory is provided by default, and the qualifiers subdirectories are created on your own. When your application needs to use a resource, the system preferentially searches the qualifiers subdirectories that match the current device state. The system searches the **base** subdirectory for the target resource only when the **resources** directory does not contain any qualifiers subdirectories that match the current device state or the target resource is not found in the qualifiers subdirectories. The **rawfile** directory is not searched for resources. @@ -18,24 +16,42 @@ Example of the **resources** directory: ``` resources -|---base // Default directory +|---base +| |---element +| | |---string.json +| |---media +| | |---icon.png +| |---profile +| | |---test_profile.json +|---en_US // Default directory. When the device language is en-us, resources in this directory are preferentially matched. +| |---element +| | |---string.json +| |---media +| | |---icon.png +| |---profile +| | |---test_profile.json +|---zh_CN // Default directory. When the device language is zh-cn, resources in this directory are preferentially matched. | |---element | | |---string.json | |---media | | |---icon.png -|---en_GB-vertical-car-mdpi // Example of a qualifiers subdirectory, which needs to be created on your own +| |---profile +| | |---test_profile.json +|---en_GB-vertical-car-mdpi // Example of a qualifiers subdirectory, which needs to be created on your own. | |---element | | |---string.json | |---media | | |---icon.png -|---rawfile +| |---profile +| | |---test_profile.json +|---rawfile // Other types of files are saved as raw files and will not be integrated into the resources.index file. You can customize the file name as needed. ``` **Table 1** Classification of the resources directory | Category | base Subdirectory | Qualifiers Subdirectory | rawfile Subdirectory | | ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | -| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories).
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.
However, resource files in the **rawfile** subdirectory will not be matched based on the device status.| +| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| **en_US** and **zh_CN** are two default qualifiers subdirectories. You need to create other qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories).
Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.
However, resource files in the **rawfile** subdirectory will not be matched based on the device status.| | Compilation| Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. | | Reference| Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the file path and file name. | @@ -77,14 +93,13 @@ The name of a qualifiers subdirectory consists of one or more qualifiers that re You can create resource group subdirectories (including element, media, and profile) in the **base** and qualifiers subdirectories to store resource files of specific types. -**Table 3** Resource group subdirectories + **Table 3** Resource group subdirectories | Resource Group Subdirectory | Description | Resource File | | ------- | ---------------------------------------- | ---------------------------------------- | | element | Indicates element resources. Each type of data is represented by a JSON file. (Only files are supported in this directory.) The options are as follows:
- **boolean**: boolean data
- **color**: color data
- **float**: floating-point data
- **intarray**: array of integers
- **integer**: integer data
- **pattern**: pattern data
- **plural**: plural form data
- **strarray**: array of strings
- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:
- boolean.json
- color.json
- float.json
- intarray.json
- integer.json
- pattern.json
- plural.json
- strarray.json
- string.json | | media | Indicates media resources, including non-text files such as images, audios, and videos. (Only files are supported in this directory.) | The file name can be customized, for example, **icon.png**. | | profile | Indicates a custom configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. (Only files are supported in this directory.) | The file name can be customized, for example, **test_profile.json**. | -| rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. | **Media Resource Types** @@ -231,7 +246,7 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile( > > The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) API. -In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories): +In the **.ets** file, you can use the resources defined in the **resources** directory. As described in [Resource Group Subdirectories](#resource-group-subdirectories), you can reference .json resource files, including **color.json**, **string.json**, and **plural.json**. The usage is as follows: ```ts Text($r('app.string.string_hello')) @@ -242,13 +257,14 @@ Text($r('app.string.string_world')) .fontColor($r('app.color.color_world')) .fontSize($r('app.float.font_world')) -// Reference string resources. The second parameter of $r is used to replace %s, and value is "We will arrive at five'o clock". -Text($r('app.string.message_arrive', "five'o clock")) +// Reference string resources. The first parameter of $r indicates the string resource, and the second parameter is used to replace %s in the string.json file. +// In this example, the resultant value is "We will arrive at five of the clock". +Text($r('app.string.message_arrive', "five of the clock")) .fontColor($r('app.color.color_hello')) .fontSize($r('app.float.font_hello')) -// Reference plural resources. The first parameter indicates the plural resource, the second parameter indicates the number of plural resources, and the third parameter indicates the substitute of %d. -// The value is "5 apple" in singular form and "5 apples" in plural form. +// Reference plural resources. The first parameter of $r indicates the plural resource, the second parameter indicates the number of plural resources (for English, **one** indicates singular and is represented by **1**, and **other** indicates plural and is represented by an integer greater than or equal to 1; for Chinese, **other** indicates both singular and plural), and the third parameter is used to replace %d. +// In this example, the resultant value is "5 apples". Text($r('app.plural.eat_apple', 5, 5)) .fontColor($r('app.color.color_world')) .fontSize($r('app.float.font_world')) diff --git a/en/application-dev/quick-start/start-with-ets-fa.md b/en/application-dev/quick-start/start-with-ets-fa.md index 019490d354b8d7c6b6ff7771065aae1b7534b76c..36fe7adfb84fa9ea5a5e735a61d71ca44dbe6dab 100644 --- a/en/application-dev/quick-start/start-with-ets-fa.md +++ b/en/application-dev/quick-start/start-with-ets-fa.md @@ -10,7 +10,7 @@ ## Creating an ArkTS Project -1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click Next. +1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click **Next**. ![createProject](figures/createProject.png) diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index d18a01875cf2e52abd45b493f8223c596912276d..978ffd47a206abc5f5b3e047a8d7f3dcc0e599e9 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -10,7 +10,7 @@ ## Creating an ArkTS Project -1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click Next. +1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click **Next**. ![createProject](figures/createProject.png) diff --git a/en/application-dev/quick-start/start-with-js-fa.md b/en/application-dev/quick-start/start-with-js-fa.md index abb27d9fb942a406e22d98285626984bdc63d197..812be6247b4ed3aae55dd1f67b0ee5bb47f01065 100644 --- a/en/application-dev/quick-start/start-with-js-fa.md +++ b/en/application-dev/quick-start/start-with-js-fa.md @@ -8,7 +8,7 @@ ## Creating a JavaScript Project -1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click Next. +1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click **Next**. ![createProject](figures/createProject.png) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index b12b546360875f9bb0d71e8840c8d8716bf62907..b942d5aa2a56cfc90c0496074d2ca7dda6d96b6f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -18,8 +18,6 @@ - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](js-apis-app-form-formExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md) - - Stage Model (To Be Deprecated Soon) - - [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md) - FA Model - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) - [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md) @@ -39,10 +37,12 @@ - [@ohos.app.ability.Want (Want)](js-apis-app-ability-want.md) - [@ohos.app.ability.wantAgent (WantAgent)](js-apis-app-ability-wantAgent.md) - [@ohos.app.ability.wantConstant (wantConstant)](js-apis-app-ability-wantConstant.md) + - [@ohos.app.businessAbilityRouter (Business Ability Router)](js-apis-businessAbilityRouter.md) - [@ohos.app.form.formBindingData (formBindingData)](js-apis-app-form-formBindingData.md) - [@ohos.app.form.formHost (FormHost)](js-apis-app-form-formHost.md) - [@ohos.app.form.formInfo (FormInfo)](js-apis-app-form-formInfo.md) - [@ohos.app.form.formProvider (FormProvider)](js-apis-app-form-formProvider.md) + - [@ohos.application.uriPermissionManager (URI Permission Management)](js-apis-uripermissionmanager.md) - Both Models (To Be Deprecated Soon) - [@ohos.ability.dataUriUtils (DataUriUtils)](js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md) @@ -139,7 +139,11 @@ - [NotificationSlot](js-apis-inner-notification-notificationSlot.md) - [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md) - [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) -- Bundle Management + - Common Events + - [Common Events of the Bundle Management Subsystem](common_event/commonEvent-bundleManager.md) + - [Common Events of the Notification Service](common_event/commonEvent-ans.md) + - [Common Events of the Telephony Subsystem](common_event/commonEvent-telephony.md) +- Bundle Management - [@ohos.bundle.appControl (appControl)](js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md) - [@ohos.bundle.bundleMonitor (bundleMonitor)](js-apis-bundleMonitor.md) @@ -148,6 +152,7 @@ - [@ohos.bundle.freeInstall (freeInstall)](js-apis-freeInstall.md) - [@ohos.bundle.installer (installer)](js-apis-installer.md) - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](js-apis-launcherBundleManager.md) + - [@ohos.bundle.overlay (overlay)](js-apis-overlay.md) - [@ohos.zlib (Zip)](js-apis-zlib.md) - bundleManager - [abilityInfo](js-apis-bundleManager-abilityInfo.md) @@ -155,18 +160,22 @@ - [AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md) - [bundleInfo](js-apis-bundleManager-bundleInfo.md) - [BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md) + - [BusinessAbilityInfo](js-apis-bundleManager-businessAbilityInfo.md) - [dispatchInfo](js-apis-bundleManager-dispatchInfo.md) - [elementName](js-apis-bundleManager-elementName.md) - [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - [metadata](js-apis-bundleManager-metadata.md) + - [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md) - [permissionDef](js-apis-bundleManager-permissionDef.md) - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) + - [SharedBundleInfo](js-apis-bundleManager-sharedBundleInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - UI Page - [@ohos.animator (Animator)](js-apis-animator.md) + - [@ohos.arkui.componentSnapshot (Component Snapshot)](js-apis-arkui-componentSnapshot.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md) - [@ohos.curves (Interpolation Calculation)](js-apis-curve.md) - [@ohos.matrix4 (Matrix Transformation)](js-apis-matrix4.md) @@ -264,7 +273,7 @@ - [@ohos.net.connection (Network Connection Management)](js-apis-net-connection.md) - [@ohos.net.ethernet (Ethernet Connection Management)](js-apis-net-ethernet.md) - [@ohos.net.http (Data Request)](js-apis-http.md) - - [@ohos.net.policy (Network Policy Management)](js-apis-net-policy.md) + - [@ohos.net.mdns (mDNS Management)](js-apis-net-mdns.md) - [@ohos.net.sharing (Network Sharing)](js-apis-net-sharing.md) - [@ohos.net.socket (Socket Connection)](js-apis-socket.md) - [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md) @@ -449,4 +458,4 @@ - [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - [shortcutInfo](js-apis-bundle-ShortcutInfo.md) - data/rdb - - [resultSet (Result Set)](js-apis-data-resultset.md) \ No newline at end of file + - [resultSet](js-apis-data-resultset.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-ability-ability.md b/en/application-dev/reference/apis/js-apis-ability-ability.md index 80610df7f925ac5a5d29744b48179488e8efc7f6..04313f3dfe02920b468647e7e717065760da46cc 100644 --- a/en/application-dev/reference/apis/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability'; | Name | Type | Description | | ----------- | -------------------- | ------------------------------------------------------------ | | DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Level-2 module **DataAbilityHelper**. | -| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | Level-2 module **PacMap**.| +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Level-2 module **PacMap**.| | DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | Level-2 module **DataAbilityOperation**.| | DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | Level-2 module **DataAbilityResult**.| | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md index 54785d5ddb6a24dba26fff11e436f7a222ae96f2..9f59a5506ce0d330fc8da3179bc03978f06353f2 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -1,6 +1,6 @@ # @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry) -**AbilityDelegatorRegistry**, a module of the [Test Framework](../../ability-deprecated/ability-delegator.md), is used to obtain [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) and [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) objects. **AbilityDelegator** provides APIs for creating **AbilityMonitor** objects, which can be used to listen for ability lifecycle changes. **AbilityDelegatorArgs** provides APIs for obtaining test parameters. +**AbilityDelegatorRegistry**, a module of the [arkXtest User Guide](../../application-test/arkxtest-guidelines.md), is used to obtain [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) and [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) objects. **AbilityDelegator** provides APIs for creating **AbilityMonitor** objects, which can be used to listen for ability lifecycle changes. **AbilityDelegatorArgs** provides APIs for obtaining test parameters. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-app-ability-common.md b/en/application-dev/reference/apis/js-apis-app-ability-common.md index e18bc26fecc0695b771769df0abee199c4254ed9..dacf140793402f8d0512b7ac388fe7f7d65ee6b0 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-common.md @@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common'; | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.| | ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Level-2 module **ServiceExtensionContext**.| | EventHub | [EventHub](js-apis-inner-application-eventHub.md) | Level-2 module **EventHub**.| -| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | Level-2 module **PacMap**.| +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Level-2 module **PacMap**.| | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.| | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.| diff --git a/en/application-dev/reference/apis/js-apis-application-want.md b/en/application-dev/reference/apis/js-apis-application-want.md index 65f7fb03e38244ee92c9f94797fa3435072d2f60..1c61a91f7852898d4539ff7b8208d1bd9a9f63ac 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -130,6 +130,6 @@ import Want from '@ohos.application.Want'; }); ``` -- For more details and examples, see [Want](../../application-models/want-overview.md). +- For more details and examples, see [Application Model](../../application-models/application-model-composition.md). diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 83c2d59e857f73cf3b6573cbc2b96f8200c14e18..4301f1019a2b6665a3ee039550146bee70e97be0 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -3553,6 +3553,7 @@ let inputAudioDeviceDescriptor = [{ networkId : audio.LOCAL_NETWORK_ID, interruptGroupId : 1, volumeGroupId : 1, + displayName : "", }]; async function selectInputDevice(){ @@ -3602,6 +3603,7 @@ let inputAudioDeviceDescriptor = [{ networkId : audio.LOCAL_NETWORK_ID, interruptGroupId : 1, volumeGroupId : 1, + displayName : "", }]; async function getRoutingManager(){ @@ -3756,6 +3758,7 @@ let outputAudioDeviceDescriptor = [{ networkId : audio.LOCAL_NETWORK_ID, interruptGroupId : 1, volumeGroupId : 1, + displayName : "", }]; async function selectOutputDevice(){ @@ -3805,6 +3808,7 @@ let outputAudioDeviceDescriptor = [{ networkId : audio.LOCAL_NETWORK_ID, interruptGroupId : 1, volumeGroupId : 1, + displayName : "", }]; async function selectOutputDevice(){ @@ -3856,6 +3860,7 @@ let outputAudioDeviceDescriptor = [{ networkId : audio.LOCAL_NETWORK_ID, interruptGroupId : 1, volumeGroupId : 1, + displayName : "", }]; async function selectOutputDeviceByFilter(){ @@ -3914,6 +3919,7 @@ let outputAudioDeviceDescriptor = [{ networkId : audio.LOCAL_NETWORK_ID, interruptGroupId : 1, volumeGroupId : 1, + displayName : "", }]; async function selectOutputDeviceByFilter(){ @@ -4082,17 +4088,18 @@ Describes the audio renderer change event. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable | Writable | Description | -| ----------------- | ------------------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | -| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | -| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | No | Audio device description. | +| Name | Type | Readable| Writable| Description | +| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API.| +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | +| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API.| +| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | No | Audio device description.| **Example** ```js + import audio from '@ohos.multimedia.audio'; const audioManager = audio.getAudioManager(); @@ -4140,13 +4147,13 @@ Describes the audio capturer change event. **System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Readable | Writable | Description | -| ----------------- | ------------------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | -| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | -| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | No | Audio device description. | +| Name | Type | Readable| Writable| Description | +| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API.| +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | +| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API.| +| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | No | Audio device description.| **Example** @@ -4194,19 +4201,20 @@ Describes an audio device. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Readable | Writable | Description | -| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | -| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | -| id9+ | number | Yes | No | Device ID, which is unique. | -| name9+ | string | Yes | No | Device name. | -| address9+ | string | Yes | No | Device address. | -| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | -| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | -| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | -| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. | -| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | -| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | +| Name | Type | Readable| Writable| Description | +| ----------------------------- | -------------------------- | ---- | ---- | ---------- | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role.| +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type.| +| id9+ | number | Yes | No | Device ID, which is unique. | +| name9+ | string | Yes | No | Device name.| +| address9+ | string | Yes | No | Device address.| +| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates.| +| channelCounts9+ | Array<number> | Yes | No | Number of channels supported.| +| channelMasks9+ | Array<number> | Yes | No | Supported channel masks.| +| displayName10+ | string | Yes | No | Display name of the device.| +| networkId9+ | string | Yes | No | ID of the device network.
This is a system API.| +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API.| +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API.| **Example** @@ -4238,11 +4246,11 @@ Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you m **System API**: This is a system API. -| Name | Type | Mandatory | Description | -| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | -| uid | number | No | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | -| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| Name | Type | Mandatory| Description | +| -------------| ---------------------------------------- | ---- | -------------- | +| uid | number | No | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core| +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer| +| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer| **Example** @@ -4264,9 +4272,9 @@ Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable | Writable | Description | -| ------------------ | -------------------------- | -------- | -------- | --------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | +| Name | Type | Readable| Writable| Description | +| ----- | -------------------------- | ---- | ---- | ------------------ | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state.| **Example** @@ -4284,9 +4292,9 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------------------------------------- | :--- | :--------------------- | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information.| **Example** @@ -4309,9 +4317,9 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Return value** -| Type | Description | -| -------------------------------------------------- | ------------------------------------------------ | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | +| Type | Description | +| -------------------------------------------------- | ------------------------------- | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information.| **Example** @@ -4336,9 +4344,9 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| **Example** @@ -4362,9 +4370,9 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| :--------------------------------------------- | :--------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| **Example** @@ -4378,7 +4386,6 @@ audioRenderer.getStreamInfo().then((streamInfo) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### getAudioStreamId9+ @@ -4391,9 +4398,9 @@ Obtains the stream ID of this **AudioRenderer** instance. This API uses an async **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID.| **Example** @@ -4401,7 +4408,6 @@ Obtains the stream ID of this **AudioRenderer** instance. This API uses an async audioRenderer.getAudioStreamId((err, streamid) => { console.info(`Renderer GetStreamId: ${streamid}`); }); - ``` ### getAudioStreamId9+ @@ -4414,9 +4420,9 @@ Obtains the stream ID of this **AudioRenderer** instance. This API uses a promis **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| :--------------------------------------------- | :--------------------- | +| Promise | Promise used to return the stream ID.| **Example** @@ -4426,7 +4432,6 @@ audioRenderer.getAudioStreamId().then((streamid) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### start8+ @@ -4439,9 +4444,9 @@ Starts the renderer. This API uses an asynchronous callback to return the result **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -4453,7 +4458,6 @@ audioRenderer.start((err) => { console.info('Renderer start success.'); } }); - ``` ### start8+ @@ -4466,9 +4470,9 @@ Starts the renderer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -4478,7 +4482,6 @@ audioRenderer.start().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### pause8+ @@ -4491,9 +4494,9 @@ Pauses rendering. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -4505,7 +4508,6 @@ audioRenderer.pause((err) => { console.info('Renderer paused.'); } }); - ``` ### pause8+ @@ -4518,9 +4520,9 @@ Pauses rendering. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -4530,7 +4532,6 @@ audioRenderer.pause().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### drain8+ @@ -4543,9 +4544,9 @@ Drains the playback buffer. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -4557,7 +4558,6 @@ audioRenderer.drain((err) => { console.info('Renderer drained.'); } }); - ``` ### drain8+ @@ -4570,9 +4570,9 @@ Drains the playback buffer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -4582,7 +4582,6 @@ audioRenderer.drain().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### stop8+ @@ -4595,9 +4594,9 @@ Stops rendering. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -4609,7 +4608,6 @@ audioRenderer.stop((err) => { console.info('Renderer stopped.'); } }); - ``` ### stop8+ @@ -4622,9 +4620,9 @@ Stops rendering. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -4634,7 +4632,6 @@ audioRenderer.stop().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### release8+ @@ -4647,9 +4644,9 @@ Releases the renderer. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -4661,7 +4658,6 @@ audioRenderer.release((err) => { console.info('Renderer released.'); } }); - ``` ### release8+ @@ -4674,9 +4670,9 @@ Releases the renderer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -4686,7 +4682,6 @@ audioRenderer.release().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### write8+ @@ -4699,10 +4694,10 @@ Writes the buffer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ------------------------------------------------------------ | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | --------------------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| **Example** @@ -4742,7 +4737,6 @@ for (let i = 0;i < len; i++) { }) } - ``` ### write8+ @@ -4755,9 +4749,9 @@ Writes the buffer. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| **Example** @@ -4792,7 +4786,6 @@ for (let i = 0;i < len; i++) { console.error(`audioRenderer.write err: ${err}`); } } - ``` ### getAudioTime8+ @@ -4805,9 +4798,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp.| **Example** @@ -4815,7 +4808,6 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioRenderer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); - ``` ### getAudioTime8+ @@ -4828,9 +4820,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Return value** -| Type | Description | -| ---------------- | ------------------------------------- | -| Promise\ | Promise used to return the timestamp. | +| Type | Description | +| ---------------- | ----------------------- | +| Promise\ | Promise used to return the timestamp.| **Example** @@ -4840,7 +4832,6 @@ audioRenderer.getAudioTime().then((timestamp) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### getBufferSize8+ @@ -4853,9 +4844,9 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size.| **Example** @@ -4865,7 +4856,6 @@ let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { console.error('getBufferSize error'); } }); - ``` ### getBufferSize8+ @@ -4878,9 +4868,9 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Return value** -| Type | Description | -| ---------------- | --------------------------------------- | -| Promise\ | Promise used to return the buffer size. | +| Type | Description | +| ---------------- | --------------------------- | +| Promise\ | Promise used to return the buffer size.| **Example** @@ -4892,7 +4882,6 @@ audioRenderer.getBufferSize().then((data) => { }).catch((err) => { console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); - ``` ### setRenderRate8+ @@ -4905,10 +4894,10 @@ Sets the render rate. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ----------------------------------- | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -4920,7 +4909,6 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => console.info('Callback invoked to indicate a successful render rate setting.'); } }); - ``` ### setRenderRate8+ @@ -4933,15 +4921,15 @@ Sets the render rate. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | --------- | ------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------- | ---- | ------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate.| **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -4951,7 +4939,6 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### getRenderRate8+ @@ -4964,9 +4951,9 @@ Obtains the current render rate. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate.| **Example** @@ -4974,7 +4961,6 @@ Obtains the current render rate. This API uses an asynchronous callback to retur audioRenderer.getRenderRate((err, renderrate) => { console.info(`getRenderRate: ${renderrate}`); }); - ``` ### getRenderRate8+ @@ -4987,9 +4973,9 @@ Obtains the current render rate. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------------------------------------- | --------------------------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | +| Type | Description | +| ------------------------------------------------- | ------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate.| **Example** @@ -4999,9 +4985,7 @@ audioRenderer.getRenderRate().then((renderRate) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` - ### setInterruptMode9+ setInterruptMode(mode: InterruptMode): Promise<void> @@ -5012,15 +4996,15 @@ Sets the audio interruption mode for the application. This API uses a promise to **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------------- | --------- | ------------------------ | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------- | ------ | ---------- | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned.| **Example** @@ -5031,9 +5015,7 @@ audioRenderer.setInterruptMode(mode).then(data=>{ }).catch((err) => { console.error(`setInterruptMode Fail: ${err}`); }); - ``` - ### setInterruptMode9+ setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void @@ -5044,10 +5026,10 @@ Sets the audio interruption mode for the application. This API uses an asynchron **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | --------- | ----------------------------------- | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ------ | -------------- | +|mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode.| +|callback | AsyncCallback\ | Yes |Callback used to return the result.| **Example** @@ -5059,7 +5041,6 @@ audioRenderer.setInterruptMode(mode, (err, data)=>{ } console.info('setInterruptMode Success!'); }); - ``` ### setVolume9+ @@ -5072,15 +5053,15 @@ Sets the volume for the application. This API uses a promise to return the resul **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | ------------------------------------------------------------ | -| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | +| Name | Type | Mandatory | Description | +| ---------- | ------- | ------ | ------------------- | +| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0.| **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned.| **Example** @@ -5090,9 +5071,7 @@ audioRenderer.setVolume(0.5).then(data=>{ }).catch((err) => { console.error(`setVolume Fail: ${err}`); }); - ``` - ### setVolume9+ setVolume(volume: number, callback: AsyncCallback\): void @@ -5103,10 +5082,10 @@ Sets the volume for the application. This API uses an asynchronous callback to r **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ------------------------------------------------------------ | -| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------- | -----------| ------ | ------------------- | +|volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0.| +|callback | AsyncCallback\ | Yes |Callback used to return the result.| **Example** @@ -5117,7 +5096,6 @@ audioRenderer.setVolume(0.5, (err, data)=>{ } console.info('setVolume Success!'); }); - ``` ### on('audioInterrupt')9+ @@ -5132,18 +5110,18 @@ Same as [on('interrupt')](#oninterrupt), this API is used to listen for focus ch **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio rendering is interrupted. | -| callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the audio interruption event. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio rendering is interrupted.| +| callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the audio interruption event. | **Error codes** For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). -| ID | Error Message | -| ------- | ------------------------------ | -| 6800101 | if input parameter value error | +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** @@ -5215,7 +5193,6 @@ async function onAudioInterrupt(){ } }); } - ``` ### on('markReach')8+ @@ -5228,11 +5205,11 @@ Subscribes to mark reached events. When the number of frames rendered reaches th **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------- | :--- | :---------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**.| +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** @@ -5242,7 +5219,6 @@ audioRenderer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` @@ -5256,15 +5232,14 @@ Unsubscribes from mark reached events. **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'markReach'**.| **Example** ```js audioRenderer.off('markReach'); - ``` ### on('periodReach') 8+ @@ -5277,11 +5252,11 @@ Subscribes to period reached events. When the number of frames rendered reaches **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**.| +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** @@ -5291,7 +5266,6 @@ audioRenderer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` ### off('periodReach') 8+ @@ -5304,15 +5278,14 @@ Unsubscribes from period reached events. **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :-------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**.| **Example** ```js audioRenderer.off('periodReach') - ``` ### on('stateChange')8+ @@ -5325,10 +5298,10 @@ Subscribes to state change events. **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Event type. The value **stateChange** means the state change event.| +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | **Example** @@ -5341,7 +5314,6 @@ audioRenderer.on('stateChange', (state) => { console.info('audio renderer state is: STATE_RUNNING'); } }); - ``` ## AudioCapturer8+ @@ -5352,15 +5324,14 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo **System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Readable | Writable | Description | -| :----------------- | :------------------------- | :------- | :------- | :-------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | +| Name | Type | Readable| Writable| Description | +| :---- | :------------------------- | :--- | :--- | :--------------- | +| state8+ | [AudioState](#audiostate8) | Yes| No | Audio capturer state.| **Example** ```js let state = audioCapturer.state; - ``` ### getCapturerInfo8+ @@ -5373,9 +5344,9 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the capturer information. | +| Name | Type | Mandatory| Description | +| :------- | :-------------------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the capturer information.| **Example** @@ -5389,7 +5360,6 @@ audioCapturer.getCapturerInfo((err, capturerInfo) => { console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } }); - ``` @@ -5403,9 +5373,9 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Return value** -| Type | Description | -| :------------------------------------------------ | :----------------------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | +| Type | Description | +| :------------------------------------------------ | :---------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information.| **Example** @@ -5422,7 +5392,6 @@ audioCapturer.getCapturerInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); - ``` ### getStreamInfo8+ @@ -5435,9 +5404,9 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| **Example** @@ -5453,7 +5422,6 @@ audioCapturer.getStreamInfo((err, streamInfo) => { console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } }); - ``` ### getStreamInfo8+ @@ -5466,9 +5434,9 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| :--------------------------------------------- | :------------------------------ | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| **Example** @@ -5482,7 +5450,6 @@ audioCapturer.getStreamInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`getStreamInfo :ERROR: ${err}`); }); - ``` ### getAudioStreamId9+ @@ -5495,9 +5462,9 @@ Obtains the stream ID of this **AudioCapturer** instance. This API uses an async **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID.| **Example** @@ -5505,7 +5472,6 @@ Obtains the stream ID of this **AudioCapturer** instance. This API uses an async audioCapturer.getAudioStreamId((err, streamid) => { console.info(`audioCapturer GetStreamId: ${streamid}`); }); - ``` ### getAudioStreamId9+ @@ -5518,9 +5484,9 @@ Obtains the stream ID of this **AudioCapturer** instance. This API uses a promis **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| :----------------| :--------------------- | +| Promise | Promise used to return the stream ID.| **Example** @@ -5530,7 +5496,6 @@ audioCapturer.getAudioStreamId().then((streamid) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); - ``` ### start8+ @@ -5543,9 +5508,9 @@ Starts capturing. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -5557,7 +5522,6 @@ audioCapturer.start((err) => { console.info('Capturer start success.'); } }); - ``` @@ -5571,9 +5535,9 @@ Starts capturing. This API uses a promise to return the result. **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -5589,7 +5553,6 @@ audioCapturer.start().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); - ``` ### stop8+ @@ -5602,9 +5565,9 @@ Stops capturing. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -5616,7 +5579,6 @@ audioCapturer.stop((err) => { console.info('Capturer stopped.'); } }); - ``` @@ -5630,9 +5592,9 @@ Stops capturing. This API uses a promise to return the result. **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -5646,7 +5608,6 @@ audioCapturer.stop().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); - ``` ### release8+ @@ -5659,9 +5620,9 @@ Releases this **AudioCapturer** instance. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -5673,7 +5634,6 @@ audioCapturer.release((err) => { console.info('capturer released.'); } }); - ``` @@ -5687,9 +5647,9 @@ Releases this **AudioCapturer** instance. This API uses a promise to return the **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -5703,7 +5663,6 @@ audioCapturer.release().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); - ``` ### read8+ @@ -5716,11 +5675,11 @@ Reads the buffer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :-------------------------- | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | -| callback | AsyncCallback | Yes | Callback used to return the buffer. | +| Name | Type | Mandatory| Description | +| :------------- | :-------------------------- | :--- | :------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer.| **Example** @@ -5737,7 +5696,6 @@ audioCapturer.read(bufferSize, true, async(err, buffer) => { console.info('Success in reading the buffer data'); } }); - ``` ### read8+ @@ -5750,16 +5708,16 @@ Reads the buffer. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :------ | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| Name | Type | Mandatory| Description | +| :------------- | :------ | :--- | :--------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation.| **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | +| Type | Description | +| :-------------------- | :----------------------------------------------------- | +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned.| **Example** @@ -5777,7 +5735,6 @@ audioCapturer.read(bufferSize, true).then((buffer) => { }).catch((err) => { console.info(`ERROR : ${err}`); }); - ``` ### getAudioTime8+ @@ -5790,9 +5747,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -5800,7 +5757,6 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioCapturer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); - ``` ### getAudioTime8+ @@ -5813,9 +5769,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the timestamp. | +| Type | Description | +| :--------------- | :---------------------------- | +| Promise | Promise used to return the timestamp.| **Example** @@ -5825,7 +5781,6 @@ audioCapturer.getAudioTime().then((audioTime) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); - ``` ### getBufferSize8+ @@ -5838,9 +5793,9 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :--------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------- | :--- | :----------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size.| **Example** @@ -5855,7 +5810,6 @@ audioCapturer.getBufferSize((err, bufferSize) => { }); } }); - ``` ### getBufferSize8+ @@ -5868,9 +5822,9 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Return value** -| Type | Description | -| :--------------- | :-------------------------------------- | -| Promise | Promise used to return the buffer size. | +| Type | Description | +| :--------------- | :---------------------------------- | +| Promise | Promise used to return the buffer size.| **Example** @@ -5882,14 +5836,13 @@ audioCapturer.getBufferSize().then((data) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); - ``` ### on('audioInterrupt')10+ on(type: 'audioInterrupt', callback: Callback\): void -Subscribes to audio interruption events. This API uses a callback to get interrupt events. +Subscribes to audio interruption events. This API uses a callback to obtain interrupt events. Same as [on('interrupt')](#oninterrupt), this API is used to listen for focus changes. The **AudioCapturer** instance proactively gains the focus when the **start** event occurs and releases the focus when the **pause** or **stop** event occurs. Therefore, you do not need to request to gain or release the focus. @@ -5897,18 +5850,18 @@ Same as [on('interrupt')](#oninterrupt), this API is used to listen for focus ch **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio capturing is interrupted. | -| callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the audio interruption event. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio capturing is interrupted.| +| callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the audio interruption event. | **Error codes** For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). -| ID | Error Message | -| ------- | ------------------------------ | -| 6800101 | if input parameter value error | +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** @@ -5959,7 +5912,6 @@ async function onAudioInterrupt(){ } }); } - ``` @@ -5973,11 +5925,11 @@ Subscribes to mark reached events. When the number of frames captured reaches th **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :---------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered.| **Example** @@ -5987,7 +5939,6 @@ audioCapturer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` ### off('markReach')8+ @@ -6000,15 +5951,14 @@ Unsubscribes from mark reached events. **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :-------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**.| **Example** ```js audioCapturer.off('markReach'); - ``` ### on('periodReach')8+ @@ -6021,11 +5971,11 @@ Subscribes to period reached events. When the number of frames captured reaches **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**.| +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** @@ -6035,7 +5985,6 @@ audioCapturer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); - ``` ### off('periodReach')8+ @@ -6048,15 +5997,14 @@ Unsubscribes from period reached events. **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Name| Type | Mandatory| Description | +| :----- | :----- | :--- | :---------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**.| **Example** ```js audioCapturer.off('periodReach') - ``` ### on('stateChange')8+ @@ -6069,10 +6017,10 @@ Subscribes to state change events. **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------- | :--- | :------------------------------------------ | +| type | string | Yes | Event type. The value **stateChange** means the state change event.| +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | **Example** @@ -6085,7 +6033,6 @@ audioCapturer.on('stateChange', (state) => { console.info('audio capturer state is: STATE_RUNNING'); } }); - ``` ## ToneType9+ @@ -6096,35 +6043,35 @@ Enumerates the tone types of the player. **System capability**: SystemCapability.Multimedia.Audio.Tone -| Name | Value | Description | -| :----------------------------------------------- | :---- | :-------------------------------------------- | -| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | -| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | -| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | -| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | -| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | -| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | -| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | -| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | -| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | -| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | -| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | -| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | -| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | -| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | -| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | -| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | -| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | -| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | -| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | -| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | -| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | -| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | -| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | -| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | -| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | +| Name | Value | Description | +| :------------------------------------------------ | :----- | :----------------------------| +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | ## TonePlayer9+ @@ -6144,10 +6091,10 @@ Loads the DTMF tone configuration. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :--------------| :-------------------------- | :-----| :------------------------------ | +| type | [ToneType](#tonetype9) | Yes | Tone type. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -6160,7 +6107,6 @@ tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { console.info('callback call load success'); } }); - ``` ### load9+ @@ -6175,15 +6121,15 @@ Loads the DTMF tone configuration. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :--------------------- | :-------- | ----------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | +| Name | Type | Mandatory | Description | +| :------------- | :--------------------- | :--- | ---------------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :--------------| :-------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -6193,7 +6139,6 @@ tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { }).catch(() => { console.error('promise call load fail'); }); - ``` ### start9+ @@ -6208,9 +6153,9 @@ Starts DTMF tone playing. This API uses an asynchronous callback to return the r **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -6223,7 +6168,6 @@ tonePlayer.start((err) => { console.info('callback call start success'); } }); - ``` ### start9+ @@ -6238,9 +6182,9 @@ Starts DTMF tone playing. This API uses a promise to return the result. **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -6250,7 +6194,6 @@ tonePlayer.start().then(() => { }).catch(() => { console.error('promise call start fail'); }); - ``` ### stop9+ @@ -6265,9 +6208,9 @@ Stops the tone that is being played. This API uses an asynchronous callback to r **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -6280,7 +6223,6 @@ tonePlayer.stop((err) => { console.error('callback call stop success '); } }); - ``` ### stop9+ @@ -6295,9 +6237,9 @@ Stops the tone that is being played. This API uses a promise to return the resul **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -6307,7 +6249,6 @@ tonePlayer.stop().then(() => { }).catch(() => { console.error('promise call stop fail'); }); - ``` ### release9+ @@ -6322,9 +6263,9 @@ Releases the resources associated with the **TonePlayer** instance. This API use **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :---------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -6337,7 +6278,6 @@ tonePlayer.release((err) => { console.info('callback call release success '); } }); - ``` ### release9+ @@ -6352,9 +6292,9 @@ Releases the resources associated with the **TonePlayer** instance. This API use **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| :------------- | :---------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -6364,7 +6304,6 @@ tonePlayer.release().then(() => { }).catch(() => { console.error('promise call release fail'); }); - ``` ## ActiveDeviceType(deprecated) @@ -6377,10 +6316,10 @@ Enumerates the active device types. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Value | Description | -| ------------- | ----- | ------------------------------------------------------------ | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | +| Name | Value | Description | +| ------------- | ------ | ---------------------------------------------------- | +| SPEAKER | 2 | Speaker. | +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links.| ## InterruptActionType(deprecated) @@ -6392,10 +6331,10 @@ Enumerates the returned event types for audio interruption events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Value | Description | -| -------------- | ----- | ------------------------- | -| TYPE_ACTIVATED | 0 | Focus gain event. | -| TYPE_INTERRUPT | 1 | Audio interruption event. | +| Name | Value | Description | +| -------------- | ------ | ------------------ | +| TYPE_ACTIVATED | 0 | Focus gain event.| +| TYPE_INTERRUPT | 1 | Audio interruption event.| ## AudioInterrupt(deprecated) @@ -6407,11 +6346,11 @@ Describes input parameters of audio interruption events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | -| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | -| contentType | [ContentType](#contenttype) | Yes | Audio content type. | -| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| --------------- | --------------------------- | ----| ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | +| contentType | [ContentType](#contenttype) | Yes | Audio content type. | +| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite.| ## InterruptAction(deprecated) @@ -6423,9 +6362,9 @@ Describes the callback invoked for audio interruption or focus gain events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | -| actionType | [InterruptActionType](#interruptactiontypedeprecated) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | -| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | -| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | -| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | \ No newline at end of file +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontypedeprecated) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.| +| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | +| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | +| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.| diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index 7efa6349694569c43954930e8fafdb8046a2446c..d9a98b7c17e79f588e60b199f8bf4530e781ce83 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -3,6 +3,7 @@ The **avSession** module provides APIs for media playback control so that applications can access the system's Media Controller. This module provides the following typical features related to media sessions: + - [AVSession](#avsession): used to set session metadata, playback state information, and more. - [AVSessionController](#avsessioncontroller): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. @@ -431,7 +432,7 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the casting is successful, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the casting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -453,13 +454,13 @@ let audioRoutingManager = audioManager.getRoutingManager(); let audioDevices; await audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { audioDevices = data; - console.info('Promise returned to indicate that the device list is obtained.'); + console.info(`Promise returned to indicate that the device list is obtained.`); }).catch((err) => { console.info(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`); }); avSession.castAudio('all', audioDevices).then(() => { - console.info('CreateController : SUCCESS'); + console.info(`CreateController : SUCCESS`); }).catch((err) => { console.info(`CreateController BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -485,7 +486,7 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | ------------ |--------------------------------------------| ---- | ------------------------------------------------------------ | | session | [SessionToken](#sessiontoken) | 'all' | Yes | Session token. **SessionToken** indicates a specific token, and **'all'** indicates all tokens.| | audioDevices | Array\<[audio.AudioDeviceDescriptor](js-apis-audio.md#audiodevicedescriptor)\> | Yes | Audio devices. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the casting is successful, **err** is **undefined**; otherwise, **err** is an error object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the casting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** @@ -507,7 +508,7 @@ let audioRoutingManager = audioManager.getRoutingManager(); let audioDevices; await audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { audioDevices = data; - console.info('Promise returned to indicate that the device list is obtained.'); + console.info(`Promise returned to indicate that the device list is obtained.`); }).catch((err) => { console.info(`GetDevices BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -516,7 +517,7 @@ avSession.castAudio('all', audioDevices, function (err) { if (err) { console.info(`CastAudio BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('CastAudio : SUCCESS '); + console.info(`CastAudio : SUCCESS `); } }); ``` @@ -634,7 +635,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js avSession.on('sessionServiceDie', () => { - console.info('on sessionServiceDie : session is Died '); + console.info(`on sessionServiceDie : session is Died `); }); ``` @@ -691,7 +692,7 @@ Sends a system key event to the top session. This API uses a promise to return t | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -710,7 +711,7 @@ let keyItem = {code:0x49, pressedTime:2, deviceId:0}; let event = {id:1, deviceId:0, actionTime:1, screenId:1, windowId:1, action:2, key:keyItem, unicodeChar:0, keys:[keyItem], ctrlKey:false, altKey:false, shiftKey:false, logoKey:false, fnKey:false, capsLock:false, numLock:false, scrollLock:false}; avSession.sendSystemAVKeyEvent(event).then(() => { - console.info('SendSystemAVKeyEvent Successfully'); + console.info(`SendSystemAVKeyEvent Successfully`); }).catch((err) => { console.info(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -734,7 +735,7 @@ Sends a system key event to the top session. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------- | | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -755,7 +756,7 @@ avSession.sendSystemAVKeyEvent(event, function (err) { if (err) { console.info(`SendSystemAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SendSystemAVKeyEvent : SUCCESS '); + console.info(`SendSystemAVKeyEvent : SUCCESS `); } }); ``` @@ -782,7 +783,7 @@ Sends a system control command to the top session. This API uses a promise to re | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -814,7 +815,7 @@ let avcommand = {command:cmd}; // let cmd : avSession.AVControlCommandType = 'toggleFavorite'; // let avcommand = {command:cmd, parameter:"false"}; avSession.sendSystemControlCommand(avcommand).then(() => { - console.info('SendSystemControlCommand successfully'); + console.info(`SendSystemControlCommand successfully`); }).catch((err) => { console.info(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -837,7 +838,7 @@ Sends a system control command to the top session. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ------------------------------------- | | command | [AVControlCommand](#avcontrolcommand) | Yes | Command to send. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -872,7 +873,7 @@ avSession.sendSystemControlCommand(avcommand, function (err) { if (err) { console.info(`SendSystemControlCommand BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('sendSystemControlCommand successfully'); + console.info(`sendSystemControlCommand successfully`); } }); ``` @@ -918,7 +919,7 @@ Sets session metadata. This API uses a promise to return the result. | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -949,7 +950,7 @@ let metadata = { nextAssetId: "121279", }; session.setAVMetadata(metadata).then(() => { - console.info('SetAVMetadata successfully'); + console.info(`SetAVMetadata successfully`); }).catch((err) => { console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -970,7 +971,7 @@ Sets session metadata. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------- | | data | [AVMetadata](#avmetadata) | Yes | Session metadata. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1004,7 +1005,7 @@ session.setAVMetadata(metadata, function (err) { if (err) { console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SetAVMetadata successfully'); + console.info(`SetAVMetadata successfully`); } }); ``` @@ -1029,10 +1030,9 @@ Sets information related to the session playback state. This API uses a promise | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1052,7 +1052,7 @@ let playbackState = { isFavorite:true, }; session.setAVPlaybackState(playbackState).then(() => { - console.info('SetAVPlaybackState successfully'); + console.info(`SetAVPlaybackState successfully`); }).catch((err) => { console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -1073,7 +1073,7 @@ Sets information related to the session playback state. This API uses an asynchr | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ---------------------------------------------- | | data | [AVPlaybackState](#avplaybackstate) | Yes | Information related to the session playback state.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** @@ -1099,14 +1099,14 @@ session.setAVPlaybackState(PlaybackState, function (err) { if (err) { console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SetAVPlaybackState successfully'); + console.info(`SetAVPlaybackState successfully`); } }); ``` ### setAVQueueItems10+ -setAVQueueItems(items: Array\): Promise +setAVQueueItems(items: Array\): Promise\ Sets a playlist. This API uses a promise to return the result. @@ -1124,7 +1124,7 @@ Sets a playlist. This API uses a promise to return the result. | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -1138,12 +1138,14 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js +let imageSource : imageImageSource = image.createImageSource(value.buffer); +let imagePixel : image.PixelMap = await imageSource.createPixelMap({desiredSize:{width: 150, height: 150}}); let queueItemDescription_1 = { mediaId: '001', title: 'music_name', subtitle: 'music_sub_name', description: 'music_description', - icon: PIXELMAP_OBJECT, + icon : imagePixel, iconUri: 'http://www.icon.uri.com', extras: {'extras':'any'} }; @@ -1157,7 +1159,7 @@ let queueItemDescription_2 = { subtitle: 'music_sub_name', description: 'music_description', icon: PIXELMAP_OBJECT, - iconUri: 'http://www.icon.uri.com', + iconUri: 'http://www.xxx.com', extras: {'extras':'any'} }; let queueItem_2 = { @@ -1166,7 +1168,7 @@ let queueItem_2 = { }; let queueItemsArray = [queueItem_1, queueItem_2]; session.setAVQueueItems(queueItemsArray).then(() => { - console.info('SetAVQueueItems successfully'); + console.info(`SetAVQueueItems successfully`); }).catch((err) => { console.info(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -1174,7 +1176,7 @@ session.setAVQueueItems(queueItemsArray).then(() => { ### setAVQueueItems10+ -setAVQueueItems(items: Array\, callback: AsyncCallback): void +setAVQueueItems(items: Array\, callback: AsyncCallback\): void Sets a playlist. This API uses an asynchronous callback to return the result. @@ -1187,7 +1189,7 @@ Sets a playlist. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ----------------------------------------------------------- | | items | Array<[AVQueueItem](#avqueueitem10)\> | Yes | Playlist to set. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1201,12 +1203,14 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js +let imageSource : imageImageSource = image.createImageSource(value.buffer); +let imagePixel : image.PixelMap = await imageSource.createPixelMap({desiredSize:{width: 150, height: 150}}); let queueItemDescription_1 = { mediaId: '001', title: 'music_name', subtitle: 'music_sub_name', description: 'music_description', - icon: PIXELMAP_OBJECT, + icon: imagePixel, iconUri: 'http://www.icon.uri.com', extras: {'extras':'any'} }; @@ -1232,7 +1236,7 @@ session.setAVQueueItems(queueItemsArray, function (err) { if (err) { console.info(`SetAVQueueItems BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SetAVQueueItems successfully'); + console.info(`SetAVQueueItems successfully`); } }); ``` @@ -1257,7 +1261,7 @@ Sets a name for the playlist. This API uses a promise to return the result. | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -1273,7 +1277,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js let queueTitle = 'QUEUE_TITLE'; session.setAVQueueTitle(queueTitle).then(() => { - console.info('SetAVQueueTitle successfully'); + console.info(`SetAVQueueTitle successfully`); }).catch((err) => { console.info(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -1281,7 +1285,7 @@ session.setAVQueueTitle(queueTitle).then(() => { ### setAVQueueTitle10+ -setAVQueueTitle(title: string, callback: AsyncCallback\): void +setAVQueueTitle(title: string, callback: AsyncCallback\): void Sets a name for the playlist. This API uses an asynchronous callback to return the result. @@ -1294,7 +1298,7 @@ Sets a name for the playlist. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ----------------------------------------------------------- | | title | string | Yes | Name of the playlist. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1313,7 +1317,7 @@ session.setAVQueueTitle(queueTitle, function (err) { if (err) { console.info(`SetAVQueueTitle BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SetAVQueueTitle successfully'); + console.info(`SetAVQueueTitle successfully`); } }); ``` @@ -1338,7 +1342,7 @@ Sets a launcher ability. This API uses a promise to return the result. | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -1384,7 +1388,7 @@ let wantAgentInfo = { wantAgent.getWantAgent(wantAgentInfo).then((agent) => { session.setLaunchAbility(agent).then(() => { - console.info('SetLaunchAbility successfully'); + console.info(`SetLaunchAbility successfully`); }).catch((err) => { console.info(`SetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -1406,7 +1410,7 @@ Sets a launcher ability. This API uses an asynchronous callback to return the re | Name | Type | Mandatory| Description | | -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1455,7 +1459,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((agent) => { if (err) { console.info(`SetLaunchAbility BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SetLaunchAbility successfully'); + console.info(`SetLaunchAbility successfully`); } }); }); @@ -1465,7 +1469,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((agent) => { dispatchSessionEvent(event: string, args: {[key: string]: Object}): Promise\ -Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses a promise to return the result. +Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses a promise to return the result. It is called by the provider. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -1478,11 +1482,15 @@ Dispatches a custom event in the session, including the event name and event con | event | string | Yes | Name of the session event.| | args | {[key: string]: any} | Yes | Event content in key-value pair format.| +> **NOTE** +> +> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want(Want)](./js-apis-app-ability-want.md). + **Return value** | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -1507,9 +1515,9 @@ await session.dispatchSessionEvent(eventName, args).catch((err) => { ### dispatchSessionEvent10+ -dispatchSessionEvent(event: string, args: {[key: string]: Object}, callback: AsyncCallback): void +dispatchSessionEvent(event: string, args: {[key: string]: Object}, callback: AsyncCallback\): void -Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses an asynchronous callback to return the result. +Dispatches a custom event in the session, including the event name and event content in key-value pair format. This API uses an asynchronous callback to return the result. It is called by the provider. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -1521,7 +1529,11 @@ Dispatches a custom event in the session, including the event name and event con | ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | | event | string | Yes | Name of the session event.| | args | {[key: string]: any} | Yes | Event content in key-value pair format.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +> **NOTE** +> +> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want(Want)](./js-apis-app-ability-want.md). **Error codes** @@ -1546,6 +1558,93 @@ await session.dispatchSessionEvent(eventName, args, (err) => { }) ``` +### setExtras10+ + +setExtras(extras: {[key: string]: Object}): Promise\ + +Sets a custom media packet in the form of key-value pairs. This API uses a promise to return the result. It is called by the provider. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | +| extras | {[key: string]: Object} | Yes | Key-value pairs of the custom media packet.| + +> **NOTE** +> +> The **extras** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want(Want)](./js-apis-app-ability-want.md). + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let extras = { + extras : "This is custom media packet" +} +await session.setExtras(extras).catch((err) => { + console.info(`setExtras BusinessError: code: ${err.code}, message: ${err.message}`); +}) +``` + +### setExtras10+ + +setExtras(extras: {[key: string]: Object}, callback: AsyncCallback\): void + +Sets a custom media packet in the form of key-value pairs. This API uses an asynchronous callback to return the result. It is called by the provider. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | +| extras | {[key: string]: any} | Yes | Key-value pairs of the custom media packet.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +> **NOTE** +> +> The **extras** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want(Want)](./js-apis-app-ability-want.md). + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | + +**Example** + +```js +let extras = { + extras : "This is custom media packet" +} +await session.setExtras(extras, (err) => { + if(err) { + console.info(`setExtras BusinessError: code: ${err.code}, message: ${err.message}`); + } +}) +``` + ### getController getController(): Promise\ @@ -1708,7 +1807,7 @@ Activates this session. A session can be used only after being activated. This A | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -1723,7 +1822,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js session.activate().then(() => { - console.info('Activate : SUCCESS '); + console.info(`Activate : SUCCESS `); }).catch((err) => { console.info(`Activate BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -1743,7 +1842,7 @@ Activates this session. A session can be used only after being activated. This A | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback | Yes | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1761,7 +1860,7 @@ session.activate(function (err) { if (err) { console.info(`Activate BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('Activate : SUCCESS '); + console.info(`Activate : SUCCESS `); } }); ``` @@ -1780,7 +1879,7 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -1795,7 +1894,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js session.deactivate().then(() => { - console.info('Deactivate : SUCCESS '); + console.info(`Deactivate : SUCCESS `); }).catch((err) => { console.info(`Deactivate BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -1817,7 +1916,7 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback | Yes | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1835,7 +1934,7 @@ session.deactivate(function (err) { if (err) { console.info(`Deactivate BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('Deactivate : SUCCESS '); + console.info(`Deactivate : SUCCESS `); } }); ``` @@ -1854,7 +1953,7 @@ Destroys this session. This API uses a promise to return the result. | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -1869,7 +1968,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js session.destroy().then(() => { - console.info('Destroy : SUCCESS '); + console.info(`Destroy : SUCCESS `); }).catch((err) => { console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -1889,7 +1988,7 @@ Destroys this session. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback | Yes | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1907,7 +2006,7 @@ session.destroy(function (err) { if (err) { console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('Destroy : SUCCESS '); + console.info(`Destroy : SUCCESS `); } }); ``` @@ -1942,25 +2041,25 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js session.on('play', () => { - console.info('on play entry'); + console.info(`on play entry`); }); session.on('pause', () => { - console.info('on pause entry'); + console.info(`on pause entry`); }); session.on('stop', () => { - console.info('on stop entry'); + console.info(`on stop entry`); }); session.on('playNext', () => { - console.info('on playNext entry'); + console.info(`on playNext entry`); }); session.on('playPrevious', () => { - console.info('on playPrevious entry'); + console.info(`on playPrevious entry`); }); session.on('fastForward', () => { - console.info('on fastForward entry'); + console.info(`on fastForward entry`); }); session.on('rewind', () => { - console.info('on rewind entry'); + console.info(`on rewind entry`); }); ``` @@ -2217,7 +2316,7 @@ Subscribes to custom control command changes. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The event **'commonCommand'** is reported when a custom control command changes.| -| callback | (commonCommand: string, args: {[key:string]: Object}) => void | Yes | Callback used for subscription. The **commonCommand** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command. | +| callback | (commonCommand: string, args: {[key:string]: Object}) => void | Yes | Callback used for subscription. The **commonCommand** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command. The parameters must be the same as those set in **sendCommand**. | **Error codes** @@ -2501,7 +2600,7 @@ session.off('outputDeviceChange'); ### off('commonCommand')10+ -off(type: 'commonCommand', callback?: (commonCommand: string, args: {[key:string]: Object}) => void): void +off(type: 'commonCommand', callback?: (command: string, args: {[key:string]: Object}) => void): void Unsubscribes from custom control command changes. @@ -2514,7 +2613,7 @@ Unsubscribes from custom control command changes. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'commonCommand'**. | -| callback | (commonCommand: string, args: {[key:string]: Object}) => void | No | Callback used for unsubscription. The **commonCommand** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | +| callback | (command: string, args: {[key:string]: Object}) => void | No | Callback used for unsubscription. The **command** parameter in the callback indicates the name of the changed custom control command, and **args** indicates the parameters carried in the command.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session. | **Error codes** @@ -2540,6 +2639,8 @@ An AV session controller is created by calling [avSession.createController](#avs **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + | Name | Type | Readable| Writable| Description | | :-------- | :----- | :--- | :--- | :-------------------------------------- | @@ -2792,7 +2893,7 @@ Sends the ID of an item in the playlist to the session for processing. The sessi | Type | Description | | -------------- | --------------------------------------------------------------- | -| Promise | Promise used to return the result. If the item ID is sent, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the item ID is sent, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -2808,7 +2909,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js let queueItemId = 0; controller.skipToQueueItem(queueItemId).then(() => { - console.info('SkipToQueueItem successfully'); + console.info(`SkipToQueueItem successfully`); }).catch((err) => { console.info(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -2829,7 +2930,7 @@ Sends the ID of an item in the playlist to the session for processing. The sessi | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ----------------------------------------------------------- | | itemId | number | Yes | ID of an item in the playlist. | -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -2848,7 +2949,7 @@ controller.skipToQueueItem(queueItemId, function (err) { if (err) { console.info(`SkipToQueueItem BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SkipToQueueItem successfully'); + console.info(`SkipToQueueItem successfully`); } }); ``` @@ -2996,6 +3097,92 @@ controller.getOutputDevice(function (err, deviceInfo) { }); ``` +### getExtras10+ + +getExtras(): Promise\<{[key: string]: Object}> + +Obtains the custom media packet set by the provider. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| ----------------------------------- | ----------------------------- | +| Promise<{[key: string]: Object}\> | Promise used to return the custom media packet. The content of the packet is the same as that set in **setExtras**.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**Example** +```js +let extras = await controller.getExtras().catch((err) => { + console.info(`getExtras BusinessError: code: ${err.code}, message: ${err.message}`); +}); +``` + +### getExtras10+ + +getExtras(callback: AsyncCallback\<{[key: string]: Object}>): void + +Obtains the custom media packet set by the provider. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback<{[key: string]: Object}\> | Yes | Callback used to return the custom media packet. The content of the packet is the same as that set in **setExtras**.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | + +**Example** +```js +let metadata = { + assetId: "121278", + title: "lose yourself", + artist: "Eminem", + author: "ST", + album: "Slim shady", + writer: "ST", + composer: "ST", + duration: 2222, + mediaImage: "https://www.example.com/example.jpg", + subtitle: "8 Mile", + description: "Rap", + lyric: "https://www.example.com/example.lrc", + previousAssetId: "121277", + nextAssetId: "121279", +}; +controller.getExtras(function (err, extras) { + if (err) { + console.info(`getExtras BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info(`getExtras : SUCCESS : assetId : ${metadata.assetId}`); + } +}); +``` + ### sendAVKeyEvent sendAVKeyEvent(event: KeyEvent): Promise\ @@ -3028,7 +3215,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| **Example** @@ -3037,7 +3224,7 @@ let keyItem = {code:0x49, pressedTime:2, deviceId:0}; let event = {action:2, key:keyItem, keys:[keyItem]}; controller.sendAVKeyEvent(event).then(() => { - console.info('SendAVKeyEvent Successfully'); + console.info(`SendAVKeyEvent Successfully`); }).catch((err) => { console.info(`SendAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -3058,7 +3245,7 @@ Sends a key event to the session corresponding to this controller. This API uses | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------- | | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -3082,7 +3269,7 @@ controller.sendAVKeyEvent(event, function (err) { if (err) { console.info(`SendAVKeyEvent BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SendAVKeyEvent Successfully'); + console.info(`SendAVKeyEvent Successfully`); } }); ``` @@ -3284,7 +3471,7 @@ Destroys this controller. A controller can no longer be used after being destroy | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -3299,7 +3486,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js controller.destroy().then(() => { - console.info('Destroy : SUCCESS '); + console.info(`Destroy : SUCCESS `); }).catch((err) => { console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -3319,7 +3506,7 @@ Destroys this controller. A controller can no longer be used after being destroy | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback | Yes | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -3337,7 +3524,7 @@ controller.destroy(function (err) { if (err) { console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('Destroy : SUCCESS '); + console.info(`Destroy : SUCCESS `); } }); ``` @@ -3422,6 +3609,10 @@ sendControlCommand(command: AVControlCommand): Promise\ Sends a control command to the session through the controller. This API uses a promise to return the result. +> **NOTE** +> +> Before using **sendControlCommand**, the controller must ensure that the AVSession has registered with the corresponding listener. For details about how to register the listener, see [Registering AVSession Listeners](#onplaypausestopplaynextplaypreviousfastforwardrewind). + **System capability**: SystemCapability.Multimedia.AVSession.Core **System API**: This is a system API. @@ -3436,7 +3627,7 @@ Sends a control command to the session through the controller. This API uses a p | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -3466,7 +3657,7 @@ let avCommand = {command:'play'}; // let avCommand = {command:'setLoopMode', parameter:avSession.LoopMode.LOOP_MODE_SINGLE}; // let avCommand = {command:'toggleFavorite', parameter:"false"}; controller.sendControlCommand(avCommand).then(() => { - console.info('SendControlCommand successfully'); + console.info(`SendControlCommand successfully`); }).catch((err) => { console.info(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`); }); @@ -3478,6 +3669,10 @@ sendControlCommand(command: AVControlCommand, callback: AsyncCallback\): v Sends a control command to the session through the controller. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> Before using **sendControlCommand**, the controller must ensure that the AVSession has registered with the corresponding listener. For details about how to register the listener, see [Registering AVSession Listeners](#onplaypausestopplaynextplaypreviousfastforwardrewind). + **System capability**: SystemCapability.Multimedia.AVSession.Core **System API**: This is a system API. @@ -3487,7 +3682,7 @@ Sends a control command to the session through the controller. This API uses an | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ------------------------------ | | command | [AVControlCommand](#avcontrolcommand) | Yes | Command to send.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** @@ -3520,7 +3715,7 @@ controller.sendControlCommand(avCommand, function (err) { if (err) { console.info(`SendControlCommand BusinessError: code: ${err.code}, message: ${err.message}`); } else { - console.info('SendControlCommand successfully'); + console.info(`SendControlCommand successfully`); } }); ``` @@ -3533,6 +3728,8 @@ Sends a custom control command to the session through the controller. This API u **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -3540,11 +3737,15 @@ Sends a custom control command to the session through the controller. This API u | command | string | Yes | Name of the custom control command.| | args | {[key: string]: any} | Yes | Parameters in key-value pair format carried in the custom control command.| +> **NOTE** +> +> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want(Want)](./js-apis-app-ability-want.md). + **Return value** | Type | Description | | -------------- | ----------------------------- | -| Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| +| Promise\ | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** @@ -3579,16 +3780,21 @@ Sends a custom control command to the session through the controller. This API u **System capability**: SystemCapability.Multimedia.AVSession.Core +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ------------------------------ | | command | string | Yes | Name of the custom control command.| | args | {[key: string]: any} | Yes | Parameters in key-value pair format carried in the custom control command.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | -**Error codes** +> **NOTE** +> +> The **args** parameter supports the following data types: string, number, Boolean, object, array, and file descriptor. For details, see [@ohos.app.ability.Want(Want)](./js-apis-app-ability-want.md). +**Error codes** For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -3698,7 +3904,7 @@ controller.on('playbackStateChange', playbackFilter, (playbackState) => { on(type: 'sessionEvent', callback: (sessionEvent: string, args: {[key:string]: Object}) => void): void -Subscribes to session event changes. +Subscribes to session event changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -3732,7 +3938,7 @@ controller.on('sessionEvent', (sessionEvent, args) => { on(type: 'queueItemsChange', callback: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void -Subscribes to playlist item changes. +Subscribes to playlist item changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -3766,7 +3972,7 @@ controller.on('queueItemsChange', (items) => { on(type: 'queueTitleChange', callback: (title: string) => void): void -Subscribes to playlist name changes. +Subscribes to playlist name changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -3796,6 +4002,41 @@ controller.on('queueTitleChange', (title) => { }); ``` +### on('extrasChange')10+ + +on(type: 'extrasChange', callback: (extras: {[key:string]: Object}) => void): void + +Subscribes to custom media packet changes. This API is called by the controller. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The event **'extrasChange'** is reported when the provider sets a custom media packet.| +| callback | (extras: {[key:string]: object}) => void | Yes | Callback used for subscription. The **extras** parameter in the callback indicates the custom media packet set by the provider. This packet is the same as that set in **dispatchSessionEvent**. | + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ------------------------------ | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | +| 401 | Parameter check failed | + +**Example** + +```js +controller.on('extrasChange', (extras) => { + console.info(`Caught extrasChange event,the new extra is: ${JSON.stringify(extras)}`); +}); +``` + ### on('sessionDestroy') on(type: 'sessionDestroy', callback: () => void) @@ -3826,7 +4067,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ```js controller.on('sessionDestroy', () => { - console.info('on sessionDestroy : SUCCESS '); + console.info(`on sessionDestroy : SUCCESS `); }); ``` @@ -3937,7 +4178,7 @@ controller.on('outputDeviceChange', (device) => { off(type: 'metadataChange', callback?: (data: AVMetadata) => void) -Unsubscribes from metadata changes. +Unsubscribes from metadata changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -3968,7 +4209,7 @@ controller.off('metadataChange'); off(type: 'playbackStateChange', callback?: (state: AVPlaybackState) => void) -Unsubscribes from playback state changes. +Unsubscribes from playback state changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -3999,7 +4240,7 @@ controller.off('playbackStateChange'); off(type: 'sessionEvent', callback?: (sessionEvent: string, args: {[key:string]: Obejct}) => void): void -Unsubscribes from session event changes. +Unsubscribes from session event changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -4030,7 +4271,7 @@ controller.off('sessionEvent'); off(type: 'queueItemsChange', callback?: (items: Array<[AVQueueItem](#avqueueitem10)\>) => void): void -Unsubscribes from playback item changes. +Unsubscribes from playback item changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -4061,7 +4302,7 @@ controller.off('queueItemsChange'); off(type: 'queueTitleChange', callback?: (title: string) => void): void -Unsubscribes from playlist name changes. +Unsubscribes from playlist name changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -4088,11 +4329,44 @@ For details about the error codes, see [AVSession Management Error Codes](../err controller.off('queueTitleChange'); ``` +### off('extrasChange')10+ + +off(type: 'extrasChange', callback?: (extras: {[key:string]: Object}) => void): void + +Unsubscribes from custom media packet changes. This API is called by the controller. + +**System capability**: SystemCapability.Multimedia.AVSession.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'extrasChange'**. | +| callback | ({[key:string]: Object}) => void | No | Callback used for unsubscription.
The **callback** parameter is optional. If it is not specified, all the subscriptions to the specified event are canceled for this session.| + +**Error codes** + +For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). + +| ID| Error Message| +| -------- | ---------------- | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | +| 401 | Parameter check failed | + +**Example** + +```js +controller.off('extrasChange'); +``` + ### off('sessionDestroy') off(type: 'sessionDestroy', callback?: () => void) -Unsubscribes from the session destruction event. +Unsubscribes from the session destruction event. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -4123,7 +4397,7 @@ controller.off('sessionDestroy'); off(type: 'activeStateChange', callback?: (isActive: boolean) => void) -Unsubscribes from session activation state changes. +Unsubscribes from session activation state changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -4154,7 +4428,7 @@ controller.off('activeStateChange'); off(type: 'validCommandChange', callback?: (commands: Array\) => void) -Unsubscribes from valid command changes. +Unsubscribes from valid command changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -4185,7 +4459,7 @@ controller.off('validCommandChange'); off(type: 'outputDeviceChange', callback?: (device: OutputDeviceInfo) => void): void -Unsubscribes from output device changes. +Unsubscribes from output device changes. This API is called by the controller. **System capability**: SystemCapability.Multimedia.AVSession.Core @@ -4363,6 +4637,8 @@ Describes the information related to the media playback state. | bufferedTime | number | No | Buffered time.| | loopMode | [LoopMode](#loopmode) | No | Loop mode.| | isFavorite | boolean | No | Whether the media asset is favorited.| +| activeItemId10+ | number | No | ID of the item that is being played.| +| extras10+ | {[key: string]: Object} | No | Custom media data.| ## PlaybackPosition @@ -4442,3 +4718,5 @@ Enumerates the error codes used in the media session. | ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command. | | ERR_CODE_SESSION_INACTIVE | 6600106 | The session is not activated. | | ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Too many commands or events. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md index 721a432caaf67116a6df882c0e8995e76b893a7e..8314dd92cfc15cdbc9ad8e1e232b3fab2b00380b 100644 --- a/en/application-dev/reference/apis/js-apis-batteryStatistics.md +++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -36,7 +36,7 @@ For details about the error codes, see [Thermal Manager Error Codes](../errorcod | Code | Error Message | |---------|---------| -| 4600101 | Operation failed. Cannot connect to service.| +| 4600101 | If connecting to the service failed. | **Example** @@ -72,7 +72,7 @@ For details about the error codes, see [Thermal Manager Error Codes](../errorcod | Code | Error Message | |---------|---------| -| 4600101 | Operation failed. Cannot connect to service.| +| 4600101 | If connecting to the service failed. | **Example** @@ -114,7 +114,7 @@ For details about the error codes, see [Thermal Manager Error Codes](../errorcod | Code | Error Message | |---------|---------| -| 4600101 | Operation failed. Cannot connect to service.| +| 4600101 | If connecting to the service failed. | **Example** @@ -155,7 +155,7 @@ For details about the error codes, see [Thermal Manager Error Codes](../errorcod | Code | Error Message | |---------|---------| -| 4600101 | Operation failed. Cannot connect to service.| +| 4600101 | If connecting to the service failed. | **Example** @@ -196,13 +196,13 @@ For details about the error codes, see [Thermal Manager Error Codes](../errorcod | Code | Error Message | |---------|---------| -| 4600101 | Operation failed. Cannot connect to service.| +| 4600101 | If connecting to the service failed. | **Example** ```js try { - var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + var value = batteryStats.getHardwareUnitPowerValue(batteryStats.ConsumptionType.CONSUMPTION_TYPE_SCREEN); console.info('battery statistics value of hardware is: ' + value); } catch(err) { console.error('get battery statistics percent of hardware failed, err: ' + err); @@ -237,13 +237,13 @@ For details about the error codes, see [Thermal Manager Error Codes](../errorcod | Code | Error Message | |---------|---------| -| 4600101 | Operation failed. Cannot connect to service.| +| 4600101 | If connecting to the service failed. | **Example** ```js try { - var percent = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + var percent = batteryStats.getHardwareUnitPowerPercent(batteryStats.ConsumptionType.CONSUMPTION_TYPE_SCREEN); console.info('battery statistics percent of hardware is: ' + percent); } catch(err) { console.error('get battery statistics percent of hardware failed, err: ' + err); diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index bd003733a485c1601ac251697461e78b863976a8..e6af63700029738f388f41edb5d980b51a9f9614 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -22,7 +22,7 @@ Sets the screen brightness. **System API**: This is a system API. -**System capability**: SystemCapability.PowerManager.DisplayPowerManager +**System capability:** SystemCapability.PowerManager.DisplayPowerManager **Parameters** @@ -34,9 +34,9 @@ Sets the screen brightness. For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md). -| Code | Error Message | +| ID | Error Message | |---------|---------| -| 4700101 | Operation failed. Cannot connect to service.| +| 4700101 | If connecting to the service failed. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index 5a014e7cfe5618c7e31741b43d32ce743d86a0b2..737c9f1dbf05e30e2f84e185b89e804642b0c39f 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -726,7 +726,7 @@ Checks whether this **Buffer** instance contains the specified value. | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| **Return value** @@ -758,7 +758,7 @@ Obtains the index of the first occurrence of the specified value in this **Buffe | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| **Return value** @@ -815,7 +815,7 @@ Obtains the index of the last occurrence of the specified value in this **Buffer | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| **Return value** @@ -838,7 +838,7 @@ console.log(buf.lastIndexOf('buffer').toString()); // Print: 17 readBigInt64BE(offset?: number): bigint -Reads a signed, big-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, big-endian, signed big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -872,14 +872,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigInt64BE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigInt64BE(0x0102030405060708n, 0); +let result = buf1.writeBigInt64BE(BigInt(0x0102030405060708), 0); ``` ### readBigInt64LE readBigInt64LE(offset?: number): bigint -Reads a signed, little-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, little-endian, signed big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -913,14 +913,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigInt64LE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigInt64BE(0x0102030405060708n, 0); +let result = buf1.writeBigInt64BE(BigInt(0x0102030405060708), 0); ``` ### readBigUInt64BE readBigUInt64BE(offset?: number): bigint -Reads an unsigned, big-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, big-endian, unsigned big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -954,14 +954,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigUInt64BE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); +let result = buf1.writeBigUInt64BE(BigInt(0xdecafafecacefade), 0); ``` ### readBigUInt64LE readBigUInt64LE(offset?: number): bigint -Reads an unsigned, little-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, little-endian, unsigned big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -995,14 +995,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigUInt64LE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); +let result = buf1.writeBigUInt64BE(BigInt(0xdecafafecacefade), 0); ``` ### readDoubleBE readDoubleBE(offset?: number): number -Reads a 64-bit, big-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 64-bit, big-endian, double-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1042,7 +1042,7 @@ let result = buf1.writeDoubleBE(123.456, 0); readDoubleLE(offset?: number): number -Reads a 64-bit, little-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 64-bit, little-endian, double-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1082,7 +1082,7 @@ let result = buf1.writeDoubleLE(123.456, 0); readFloatBE(offset?: number): number -Reads a 32-bit, big-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 32-bit, big-endian, single-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1122,7 +1122,7 @@ let result = buf1.writeFloatBE(0xcabcbcbc, 0); readFloatLE(offset?: number): number -Reads a 32-bit, little-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 32-bit, little-endian, single-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1162,7 +1162,7 @@ let result = buf1.writeFloatLE(0xcabcbcbc, 0); readInt8(offset?: number): number -Reads a signed 8-bit integer from this **Buffer** instance at the specified offset. +Reads a 8-bit signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1203,7 +1203,7 @@ let result = buf1.writeInt8(0x12); readInt16BE(offset?: number): number -Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, big-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1243,7 +1243,7 @@ let result = buf1.writeInt16BE(0x1234, 0); readInt16LE(offset?: number): number -Reads a signed, little-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, little-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1283,7 +1283,7 @@ let result = buf1.writeInt16BE(0x1234, 0); readInt32BE(offset?: number): number -Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, big-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1323,7 +1323,7 @@ let result = buf1.writeInt32BE(0x12345678, 0); readInt32LE(offset?: number): number -Reads a signed, little-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, little-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1449,7 +1449,7 @@ let result = buf1.writeIntLE(0x123456789011, 0, 6); readUInt8(offset?: number): number -Reads an unsigned 8-bit integer from this **Buffer** instance at the specified offset. +Reads a 8-bit unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1491,7 +1491,7 @@ let result = buf1.writeUInt8(0x42); readUInt16BE(offset?: number): number -Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, big-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1533,7 +1533,7 @@ let result = buf1.writeUInt16BE(0x1234, 0); readUInt16LE(offset?: number): number -Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, little-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1575,7 +1575,7 @@ let result = buf1.writeUInt16LE(0x1234, 0); readUInt32BE(offset?: number): number -Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, big-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1616,7 +1616,7 @@ let result = buf1.writeUInt32BE(0x12345678, 0); readUInt32LE(offset?: number): number -Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, little-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2013,7 +2013,7 @@ let length = buffer1.write('abcd', 8); writeBigInt64BE(value: bigint, offset?: number): number -Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, big-endian, signed big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2045,14 +2045,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigInt64BE(0x0102030405060708n, 0); +let result = buf.writeBigInt64BE(BigInt(0x0102030405060708), 0); ``` ### writeBigInt64LE writeBigInt64LE(value: bigint, offset?: number): number -Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, little-endian, signed big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2084,14 +2084,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigInt64LE(0x0102030405060708n, 0); +let result = buf.writeBigInt64LE(BigInt(0x0102030405060708), 0); ``` ### writeBigUInt64BE writeBigUInt64BE(value: bigint, offset?: number): number -Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, big-endian, unsigned big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2123,14 +2123,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigUInt64BE(0xdecafafecacefaden, 0); +let result = buf.writeBigUInt64BE(BigInt(0xdecafafecacefade), 0); ``` ### writeBigUInt64LE writeBigUInt64LE(value: bigint, offset?: number): number -Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, little-endian, unsigned big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2162,14 +2162,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigUInt64LE(0xdecafafecacefaden, 0); +let result = buf.writeBigUInt64LE(BigInt(0xdecafafecacefade), 0); ``` ### writeDoubleBE writeDoubleBE(value: number, offset?: number): number -Writes a big-endian double-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 64-bit, big-endian, double-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2208,7 +2208,7 @@ let result = buf.writeDoubleBE(123.456, 0); writeDoubleLE(value: number, offset?: number): number -Writes a little-endian double-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 64-bit, little-endian, double-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2247,7 +2247,7 @@ let result = buf.writeDoubleLE(123.456, 0); writeFloatBE(value: number, offset?: number): number -Writes a big-endian single-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 32-bit, big-endian, single-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2287,7 +2287,7 @@ let result = buf.writeFloatBE(0xcafebabe, 0); writeFloatLE(value: number, offset?: number): number -Writes a little-endian single-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 32-bit, little-endian, single-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2326,7 +2326,7 @@ let result = buf.writeFloatLE(0xcafebabe, 0); writeInt8(value: number, offset?: number): number -Writes a signed 8-bit integer to this **Buffer** instance at the specified offset. +Writes a 8-bit signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2367,7 +2367,7 @@ let result1 = buf.writeInt8(-2, 1); writeInt16BE(value: number, offset?: number): number -Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, big-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2407,7 +2407,7 @@ let result = buf.writeInt16BE(0x0102, 0); writeInt16LE(value: number, offset?: number): number -Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, little-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2446,7 +2446,7 @@ let result = buf.writeInt16LE(0x0304, 0); writeInt32BE(value: number, offset?: number): number -Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, big-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2486,7 +2486,7 @@ let result = buf.writeInt32BE(0x01020304, 0); writeInt32LE(value: number, offset?: number): number -Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, little-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2606,7 +2606,7 @@ let result = buf.writeIntLE(0x1234567890ab, 0, 6); writeUInt8(value: number, offset?: number): number -Writes an unsigned 8-bit integer to this **Buffer** instance at the specified offset. +Writes a 8-bit unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2648,7 +2648,7 @@ let result3 = buf.writeUInt8(0x42, 3); writeUInt16BE(value: number, offset?: number): number -Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, big-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2688,7 +2688,7 @@ let result1 = buf.writeUInt16BE(0xbeef, 2); writeUInt16LE(value: number, offset?: number): number -Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, little-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2728,7 +2728,7 @@ let result1 = buf.writeUInt16LE(0xbeef, 2); writeUInt32BE(value: number, offset?: number): number -Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, big-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2767,7 +2767,7 @@ let result = buf.writeUInt32BE(0xfeedface, 0); writeUInt32LE(value: number, offset?: number): number -Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, little-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index cef362d3702423395594a8ae52326b99e5aee191..0cea1311feadeba8b3dc9f7dd250894e57267c67 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -81,7 +81,7 @@ Unsubscribes from bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ---------------------------------------------------------- | | type| BundleChangedEvent| Yes | Type of the event to unsubscribe from. | -| callback | callback\| No | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| +| callback | callback\| No | Callback used for the unsubscription. By default, no value is passed, and all callbacks of the current event are unsubscribed from.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 9ba1dfa2ca3ef6a55b0e2a662f4f413b91d1013f..1f90664de26360d3099d9f0870baabaad1063b23 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -16,7 +16,7 @@ import call from '@ohos.telephony.call'; ## call.dialCall9+ -dialCall\(phoneNumber: string, callback: AsyncCallback\): void +dialCall\(phoneNumber: string, callback: AsyncCallback\\): void Initiates a call. This API uses an asynchronous callback to return the result. @@ -40,6 +40,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -57,7 +58,7 @@ call.dialCall("138xxxxxxxx", (err) => { ## call.dialCall9+ -dialCall\(phoneNumber: string, options: DialCallOptions, callback: AsyncCallback\): void +dialCall\(phoneNumber: string, options: DialCallOptions, callback: AsyncCallback\\): void Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result. @@ -82,6 +83,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -104,7 +106,7 @@ call.dialCall("138xxxxxxxx", { ## call.dialCall9+ -dialCall\(phoneNumber: string, options?: DialCallOptions\): Promise +dialCall\(phoneNumber: string, options?: DialCallOptions\): Promise\ Initiates a call. You can set call options as needed. This API uses a promise to return the result. @@ -119,7 +121,7 @@ Initiates a call. You can set call options as needed. This API uses a promise to | Name | Type | Mandatory| Description | | ----------- | ----------------------------------- | ---- | -------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [DialCallOptions](#dialcalloptions9)| No | Call options, which carry other configuration information of the call.| +| options | [DialCallOptions](#dialcalloptions9)| No | Call options, which carry other configuration information of the call.
If this parameter is not set, the following configuration is used by default. For details, see [DialCallOptions](#dialcalloptions9).
- **accountId**: 0 (card slot 1)
- **videoState**: voice call
- **dialScene**: common call
- **dialType**: carrier call | **Return value** @@ -134,6 +136,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -158,7 +161,7 @@ promise.then(() => { ## call.dial(deprecated) -dial\(phoneNumber: string, callback: AsyncCallback\): void +dial\(phoneNumber: string, callback: AsyncCallback\\): void Initiates a call. This API uses an asynchronous callback to return the result. @@ -188,7 +191,7 @@ call.dial("138xxxxxxxx", (err, data) => { ## call.dial(deprecated) -dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback\): void +dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback\\): void Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result. @@ -220,7 +223,7 @@ call.dial("138xxxxxxxx", { ## call.dial(deprecated) -dial\(phoneNumber: string, options?: DialOptions\): Promise +dial\(phoneNumber: string, options?: DialOptions\): Promise\ Initiates a call. You can set call options as needed. This API uses a promise to return the result. @@ -260,7 +263,7 @@ promise.then(data => { ## call.makeCall7+ -makeCall(phoneNumber: string, callback: AsyncCallback\): void +makeCall\(phoneNumber: string, callback: AsyncCallback\\): void Launches the call screen and displays the dialed number. This API uses an asynchronous callback to return the result. @@ -296,7 +299,7 @@ call.makeCall("138xxxxxxxx", err => { ## call.makeCall7+ -makeCall(phoneNumber: string): Promise\ +makeCall\(phoneNumber: string\): Promise\ Launches the call screen and displays the dialed number. This API uses a promise to return the result. @@ -339,7 +342,7 @@ promise.then(() => { ## call.hasCall -hasCall\(callback: AsyncCallback\): void +hasCall\(callback: AsyncCallback\\): void Checks whether a call is in progress. This API uses an asynchronous callback to return the result. @@ -362,7 +365,7 @@ call.hasCall((err, data) => { ## call.hasCall -hasCall\(\): Promise +hasCall\(\): Promise\ Checks whether a call is in progress. This API uses a promise to return the result. @@ -388,7 +391,7 @@ promise.then(data => { ## call.getCallState -getCallState\(callback: AsyncCallback\): void +getCallState\(callback: AsyncCallback\\): void Obtains the call status. This API uses an asynchronous callback to return the result. @@ -411,7 +414,7 @@ call.getCallState((err, data) => { ## call.getCallState -getCallState\(\): Promise +getCallState\(\): Promise\ Obtains the call status. This API uses a promise to return the result. @@ -436,7 +439,7 @@ promise.then(data => { ## call.hasVoiceCapability7+ -hasVoiceCapability(): boolean +hasVoiceCapability\(\): boolean Checks whether a device supports voice calls. @@ -455,7 +458,7 @@ console.log(`hasVoiceCapability: ${JSON.stringify(result)}`); ## call.isEmergencyPhoneNumber7+ -isEmergencyPhoneNumber\(phoneNumber: string, callback: AsyncCallback\): void +isEmergencyPhoneNumber\(phoneNumber: string, callback: AsyncCallback\\): void Checks whether the called number is an emergency number. This API uses an asynchronous callback to return the result. @@ -491,7 +494,7 @@ call.isEmergencyPhoneNumber("138xxxxxxxx", (err, data) => { ## call.isEmergencyPhoneNumber7+ -isEmergencyPhoneNumber\(phoneNumber: string, options: EmergencyNumberOptions, callback: AsyncCallback\): void +isEmergencyPhoneNumber\(phoneNumber: string, options: EmergencyNumberOptions, callback: AsyncCallback\\): void Checks whether the called number is an emergency number based on the phone number. This API uses an asynchronous callback to return the result. @@ -528,7 +531,7 @@ call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, data) => { ## call.isEmergencyPhoneNumber7+ -isEmergencyPhoneNumber\(phoneNumber: string, options?: EmergencyNumberOptions\): Promise +isEmergencyPhoneNumber\(phoneNumber: string, options?: EmergencyNumberOptions\): Promise\ Checks whether the called number is an emergency number based on the phone number. This API uses a promise to return the result. @@ -572,7 +575,7 @@ promise.then(data => { ## call.formatPhoneNumber7+ -formatPhoneNumber\(phoneNumber: string, callback: AsyncCallback\): void +formatPhoneNumber\(phoneNumber: string, callback: AsyncCallback\\): void Formats a phone number. This API uses an asynchronous callback to return the result. @@ -609,7 +612,7 @@ call.formatPhoneNumber("138xxxxxxxx", (err, data) => { ## call.formatPhoneNumber7+ -formatPhoneNumber\(phoneNumber: string, options: NumberFormatOptions, callback: AsyncCallback\): void +formatPhoneNumber\(phoneNumber: string, options: NumberFormatOptions, callback: AsyncCallback\\): void Formats a phone number based on specified formatting options. This API uses an asynchronous callback to return the result. @@ -650,7 +653,7 @@ call.formatPhoneNumber("138xxxxxxxx", { ## call.formatPhoneNumber7+ -formatPhoneNumber\(phoneNumber: string, options?: NumberFormatOptions\): Promise +formatPhoneNumber\(phoneNumber: string, options?: NumberFormatOptions\): Promise\ Formats a phone number based on specified formatting options. This API uses a promise to return the result. @@ -698,7 +701,7 @@ promise.then(data => { ## call.formatPhoneNumberToE1647+ -formatPhoneNumberToE164\(phoneNumber: string, countryCode: string, callback: AsyncCallback\): void +formatPhoneNumberToE164\(phoneNumber: string, countryCode: string, callback: AsyncCallback\\): void Converts a phone number into the E.164 format. This API uses an asynchronous callback to return the result. @@ -737,7 +740,7 @@ call.formatPhoneNumberToE164("138xxxxxxxx", "CN", (err, data) => { ## call.formatPhoneNumberToE1647+ -formatPhoneNumberToE164\(phoneNumber: string, countryCode: string\): Promise +formatPhoneNumberToE164\(phoneNumber: string, countryCode: string\): Promise\ Converts a phone number into the E.164 format. This API uses a promise to return the result. @@ -785,7 +788,7 @@ promise.then(data => { ## call.muteRinger8+ -muteRinger\(callback: AsyncCallback\): void +muteRinger\(callback: AsyncCallback\\): void Mutes the ringtone while it is playing. It does not work if the ringtone has been muted. This API uses an asynchronous callback to return the result. @@ -808,6 +811,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -825,7 +829,7 @@ call.muteRinger((err) => { ## call.muteRinger8+ -muteRinger\(\): Promise +muteRinger\(\): Promise\ Mutes the ringtone while it is playing. It does not work if the ringtone has been muted. This API uses a promise to return the result. @@ -848,6 +852,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -865,7 +870,7 @@ call.muteRinger().then(() => { ## call.answerCall9+ -answerCall\(callId: number, callback: AsyncCallback\): void +answerCall\(callId: number, callback: AsyncCallback\\): void Answers a call. This API uses an asynchronous callback to return the result. @@ -889,6 +894,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -906,7 +912,7 @@ call.answerCall(1, (err) => { ## call.answerCall9+ -answerCall(callId?: number\): Promise +answerCall(callId?: number\): Promise\ Answers a call. This API uses a promise to return the result. @@ -920,7 +926,7 @@ Answers a call. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.
If this parameter is not set, the latest ringing call will be connected.| **Return value** @@ -935,6 +941,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -954,7 +961,7 @@ call.answerCall(1).then(() => { ## call.answerCall9+ -answerCall\(callback: AsyncCallback\): void +answerCall\(callback: AsyncCallback\\): void Answers a call. This API uses an asynchronous callback to return the result. @@ -977,6 +984,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -994,7 +1002,7 @@ call.answerCall((err) => { ## call.hangUpCall9+ -hangUpCall\(callId: number, callback: AsyncCallback\): void +hangUpCall\(callId: number, callback: AsyncCallback\\): void Ends a call. This API uses an asynchronous callback to return the result. @@ -1018,6 +1026,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1035,7 +1044,7 @@ call.hangUpCall(1, (err) => { ## call.hangUpCall9+ -hangUpCall\(callId?: number\): Promise +hangUpCall\(callId?: number\): Promise\ Ends a call. This API uses a promise to return the result. @@ -1049,7 +1058,7 @@ Ends a call. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.
If this parameter is not set, the latest ongoing, dialed, or connected call will be ended.| **Return value** @@ -1064,6 +1073,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1083,7 +1093,7 @@ call.hangUpCall(1).then(() => { ## call.hangUpCall9+ -hangUpCall\(callback: AsyncCallback\): void +hangUpCall\(callback: AsyncCallback\\): void Ends a call. This API uses an asynchronous callback to return the result. @@ -1106,6 +1116,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1124,7 +1135,7 @@ call.hangUpCall((err) => { ## call.rejectCall9+ -rejectCall(callId: number, callback: AsyncCallback\): void +rejectCall\(callId: number, callback: AsyncCallback\\): void Rejects a call. This API uses an asynchronous callback to return the result. @@ -1148,6 +1159,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1166,7 +1178,7 @@ call.rejectCall(1, (err) => { ## call.rejectCall9+ -rejectCall\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void +rejectCall\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\\): void Rejects a call. This API uses an asynchronous callback to return the result. @@ -1191,6 +1203,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1211,7 +1224,7 @@ call.rejectCall(1, rejectMessageOptions, (err) => { ## call.rejectCall9+ -rejectCall(callId?: number, options?: RejectMessageOptions\): Promise +rejectCall\(callId?: number, options?: RejectMessageOptions\): Promise\ Rejects a call. This API uses a promise to return the result. @@ -1225,8 +1238,8 @@ Rejects a call. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | -| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| -| options | [RejectMessageOptions](#rejectmessageoptions7) | No | Options for the call rejection message. | +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.
If this parameter is not set, the latest ringing call will be rejected.| +| options | [RejectMessageOptions](#rejectmessageoptions7) | No | Options for the call rejection message. If this parameter is not set, no call rejection message will be sent.| **Return value** @@ -1241,6 +1254,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1263,7 +1277,7 @@ call.rejectCall(1, rejectMessageOptions).then(() => { ## call.rejectCall9+ -rejectCall\(callback: AsyncCallback\): void +rejectCall\(callback: AsyncCallback\\): void Rejects a call. This API uses an asynchronous callback to return the result. @@ -1286,6 +1300,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1303,7 +1318,7 @@ call.rejectCall((err) => { ## call.rejectCall9+ -rejectCall\(options: RejectMessageOptions, callback: AsyncCallback\): void +rejectCall\(options: RejectMessageOptions, callback: AsyncCallback\\): void Rejects a call. This API uses an asynchronous callback to return the result. @@ -1327,6 +1342,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1347,7 +1363,7 @@ call.rejectCall(rejectMessageOptions, (err) => { ## call.holdCall7+ -holdCall\(callId: number, callback: AsyncCallback\): void +holdCall\(callId: number, callback: AsyncCallback\\): void Holds a call based on the specified call ID. This API uses an asynchronous callback to return the result. @@ -1371,6 +1387,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1388,7 +1405,7 @@ call.holdCall(1, (err) => { ## call.holdCall7+ -holdCall\(callId: number\): Promise +holdCall\(callId: number\): Promise\ Holds a call based on the specified call ID. This API uses a promise to return the result. @@ -1417,6 +1434,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1435,7 +1453,7 @@ call.holdCall(1).then(() => { ## call.unHoldCall7+ -unHoldCall\(callId: number, callback: AsyncCallback\): void +unHoldCall\(callId: number, callback: AsyncCallback\\): void Unholds a call based on the specified call ID. This API uses an asynchronous callback to return the result. @@ -1459,6 +1477,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1476,7 +1495,7 @@ call.unHoldCall(1, (err) => { ## call.unHoldCall7+ -unHoldCall\(callId: number\): Promise +unHoldCall\(callId: number\): Promise\ Unholds a call based on the specified call ID. This API uses a promise to return the result. @@ -1505,6 +1524,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1523,7 +1543,7 @@ call.unHoldCall(1).then(() => { ## call.switchCall7+ -switchCall\(callId: number, callback: AsyncCallback\): void +switchCall\(callId: number, callback: AsyncCallback\\): void Switches a call. This API uses an asynchronous callback to return the result. @@ -1547,6 +1567,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1564,7 +1585,7 @@ call.switchCall(1, (err) => { ## call.switchCall7+ -switchCall\(callId: number\): Promise +switchCall\(callId: number\): Promise\ Switches a call. This API uses a promise to return the result. @@ -1593,6 +1614,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1611,7 +1633,7 @@ call.switchCall(1).then(() => { ## call.combineConference7+ -combineConference\(callId: number, callback: AsyncCallback\): void +combineConference\(callId: number, callback: AsyncCallback\\): void Combines two calls into a conference call. This API uses an asynchronous callback to return the result. @@ -1632,11 +1654,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1649,7 +1671,7 @@ call.combineConference(1, (err) => { ## call.combineConference7+ -combineConference\(callId: number\): Promise +combineConference\(callId: number\): Promise\ Combines two calls into a conference call. This API uses a promise to return the result. @@ -1675,11 +1697,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1693,7 +1715,7 @@ call.combineConference(1).then(() => { ## call.getMainCallId7+ -getMainCallId\(callId: number, callback: AsyncCallback\): void +getMainCallId\(callId: number, callback: AsyncCallback\\): void Obtains the main call ID. This API uses an asynchronous callback to return the result. @@ -1714,11 +1736,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1732,7 +1754,7 @@ call.getMainCallId(1, (err, data) => { ## call.getMainCallId7+ -getMainCallId\(callId: number\): Promise +getMainCallId\(callId: number\): Promise\ Obtains the main call ID. This API uses a promise to return the result. @@ -1758,11 +1780,12 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | + **Example** @@ -1777,7 +1800,7 @@ promise.then(data => { ## call.getSubCallIdList7+ -getSubCallIdList\(callId: number, callback: AsyncCallback\>\): void +getSubCallIdList\(callId: number, callback: AsyncCallback\\>\): void Obtains the list of subcall IDs. This API uses an asynchronous callback to return the result. @@ -1798,11 +1821,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1815,7 +1838,7 @@ call.getSubCallIdList(1, (err, data) => { ## call.getSubCallIdList7+ -getSubCallIdList\(callId: number\): Promise\> +getSubCallIdList\(callId: number\): Promise\\> Obtains the list of subcall IDs. This API uses a promise to return the result. @@ -1841,11 +1864,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1860,7 +1883,7 @@ promise.then(data => { ## call.getCallIdListForConference7+ -getCallIdListForConference\(callId: number, callback: AsyncCallback>\): void +getCallIdListForConference\(callId: number, callback: AsyncCallback\\>\): void Obtains the list of call IDs in a conference. This API uses an asynchronous callback to return the result. @@ -1881,11 +1904,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1898,7 +1921,7 @@ call.getCallIdListForConference(1, (err, data) => { ## call.getCallIdListForConference7+ -getCallIdListForConference\(callId: number\): Promise\> +getCallIdListForConference\(callId: number\): Promise\\> Obtains the list of call IDs in a conference. This API uses a promise to return the result. @@ -1924,11 +1947,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1943,7 +1966,7 @@ promise.then(data => { ## call.getCallWaitingStatus7+ -getCallWaitingStatus\(slotId: number, callback: AsyncCallback\): void +getCallWaitingStatus\(slotId: number, callback: AsyncCallback\\): void Obtains the call waiting status. This API uses an asynchronous callback to return the result. @@ -1967,11 +1990,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -1984,7 +2007,7 @@ call.getCallWaitingStatus(0, (err, data) => { ## call.getCallWaitingStatus7+ -getCallWaitingStatus\(slotId: number\): Promise +getCallWaitingStatus\(slotId: number\): Promise\ Obtains the call waiting status. This API uses a promise to return the result. @@ -2013,11 +2036,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2032,7 +2055,7 @@ promise.then(data => { ## call.setCallWaiting7+ -setCallWaiting\(slotId: number, activate: boolean, callback: AsyncCallback\): void +setCallWaiting\(slotId: number, activate: boolean, callback: AsyncCallback\\): void Sets the call waiting switch. This API uses an asynchronous callback to return the result. @@ -2057,11 +2080,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2074,7 +2097,7 @@ call.setCallWaiting(0, true, (err) => { ## call.setCallWaiting7+ -setCallWaiting\(slotId: number, activate: boolean\): Promise +setCallWaiting\(slotId: number, activate: boolean\): Promise\ Sets the call waiting switch. This API uses a promise to return the result. @@ -2104,11 +2127,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2122,7 +2145,7 @@ call.setCallWaiting(0, true).then(() => { ## call.startDTMF7+ -startDTMF\(callId: number, character: string, callback: AsyncCallback\): void +startDTMF\(callId: number, character: string, callback: AsyncCallback\\): void Enables DTMF. This API uses an asynchronous callback to return the result. @@ -2144,11 +2167,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2161,7 +2184,7 @@ call.startDTMF(1, "0", (err) => { ## call.startDTMF7+ -startDTMF\(callId: number, character: string\): Promise +startDTMF\(callId: number, character: string\): Promise\ Enables DTMF. This API uses a promise to return the result. @@ -2188,11 +2211,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2206,7 +2229,7 @@ call.startDTMF(1, "0").then(() => { ## call.stopDTMF7+ -stopDTMF\(callId: number, callback: AsyncCallback\): void +stopDTMF\(callId: number, callback: AsyncCallback\\): void Stops DTMF. This API uses an asynchronous callback to return the result. @@ -2227,11 +2250,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2244,7 +2267,7 @@ call.stopDTMF(1, (err) => { ## call.stopDTMF7+ -stopDTMF\(callId: number\): Promise +stopDTMF\(callId: number\): Promise\ Stops DTMF. This API uses a promise to return the result. @@ -2270,11 +2293,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2288,7 +2311,7 @@ call.stopDTMF(1).then(() => { ## call.isInEmergencyCall7+ -isInEmergencyCall\(callback: AsyncCallback\): void +isInEmergencyCall\(callback: AsyncCallback\\): void Checks whether a call is an emergency call. This API uses an asynchronous callback to return the result. @@ -2311,6 +2334,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2328,7 +2352,7 @@ call.isInEmergencyCall((err, data) => { ## call.isInEmergencyCall7+ -isInEmergencyCall\(\): Promise +isInEmergencyCall\(\): Promise\ Checks whether a call is an emergency call. This API uses a promise to return the result. @@ -2351,8 +2375,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -2370,7 +2393,7 @@ promise.then(data => { ## call.on('callDetailsChange')7+ -on\(type: 'callDetailsChange', callback: Callback\): void +on\(type: 'callDetailsChange', callback: Callback\\): void Subscribes to **callDetailsChange** events. This API uses an asynchronous callback to return the result. @@ -2394,6 +2417,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2410,7 +2434,7 @@ call.on('callDetailsChange', data => { ## call.on('callEventChange')8+ -on\(type: 'callEventChange', callback: Callback\): void +on\(type: 'callEventChange', callback: Callback\\): void Subscribes to **callEventChange** events. This API uses an asynchronous callback to return the result. @@ -2434,6 +2458,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2450,7 +2475,7 @@ call.on('callEventChange', data => { ## call.on('callDisconnectedCause')8+ -on\(type: 'callDisconnectedCause', callback: Callback): void +on\(type: 'callDisconnectedCause', callback: Callback\\): void Subscribes to **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. @@ -2474,6 +2499,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2490,7 +2516,7 @@ call.on('callDisconnectedCause', data => { ## call.on('mmiCodeResult')9+ -on\(type: 'mmiCodeResult', callback: Callback\): void +on\(type: 'mmiCodeResult', callback: Callback\\): void Subscribes to **mmiCodeResult** events. This API uses an asynchronous callback to return the result. @@ -2514,6 +2540,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2530,7 +2557,7 @@ call.on('mmiCodeResult', data => { ## call.off('callDetailsChange')7+ -off\(type: 'callDetailsChange', callback?: Callback\): void +off\(type: 'callDetailsChange', callback?: Callback\\): void Unsubscribes from **callDetailsChange** events. This API uses an asynchronous callback to return the result. @@ -2545,7 +2572,7 @@ Unsubscribes from **callDetailsChange** events. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------------- | ---- | ---------------------------------- | | type | string | Yes | Call details change. This field has a fixed value of **callDetailsChange**.| -| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | No | Callback used to return the result. | +| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | No | Callback used to return the result. If this parameter is not set, no subscription cancellation result will be received.| **Error codes** @@ -2554,6 +2581,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2570,7 +2598,7 @@ call.off('callDetailsChange', data => { ## call.off('callEventChange')8+ -off\(type: 'callEventChange', callback?: Callback\): void +off\(type: 'callEventChange', callback?: Callback\\): void Unsubscribes from **callEventChange** events. This API uses an asynchronous callback to return the result. @@ -2585,7 +2613,7 @@ Unsubscribes from **callEventChange** events. This API uses an asynchronous call | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ---------------------------------- | | type | string | Yes | Call event change. This field has a fixed value of **callEventChange**.| -| callback | Callback<[CallEventOptions](#calleventoptions8)> | No | Callback used to return the result. | +| callback | Callback<[CallEventOptions](#calleventoptions8)> | No | Callback used to return the result. If this parameter is not set, no subscription cancellation result will be received.| **Error codes** @@ -2594,6 +2622,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2610,7 +2639,7 @@ call.off('callEventChange', data => { ## call.off('callDisconnectedCause')8+ -off\(type: 'callDisconnectedCause', callback?: Callback\): void +off\(type: 'callDisconnectedCause', callback?: Callback\\): void Unsubscribes from **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. @@ -2625,7 +2654,7 @@ Unsubscribes from **callDisconnectedCause** events. This API uses an asynchronou | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------------------- | ---- | ------------------- | | type | string | Yes | Call disconnection cause. This field has a fixed value of **callDisconnectedCause**.| -| callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | No | Callback used to return the result. | +| callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | No | Callback used to return the result. If this parameter is not set, no subscription cancellation result will be received.| **Error codes** @@ -2634,6 +2663,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2650,7 +2680,7 @@ call.off('callDisconnectedCause', data => { ## call.off('mmiCodeResult')9+ -off\(type: 'mmiCodeResult', callback?: Callback\): void +off\(type: 'mmiCodeResult', callback?: Callback\\): void Unsubscribes from **mmiCodeResult** events. This API uses an asynchronous callback to return the result. @@ -2665,7 +2695,7 @@ Unsubscribes from **mmiCodeResult** events. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ----------- | | type | string | Yes | MMI code result. This field has a fixed value of **mmiCodeResult**.| -| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | No | Callback used to return the result. | +| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | No | Callback used to return the result. If this parameter is not set, no subscription cancellation result will be received.| **Error codes** @@ -2674,6 +2704,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2690,7 +2721,7 @@ call.off('mmiCodeResult', data => { ## call.isNewCallAllowed8+ -isNewCallAllowed\(callback: AsyncCallback\): void +isNewCallAllowed\(callback: AsyncCallback\\): void Checks whether a new call is allowed. This API uses an asynchronous callback to return the result. @@ -2710,6 +2741,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2727,7 +2759,7 @@ call.isNewCallAllowed((err, data) => { ## call.isNewCallAllowed8+ -isNewCallAllowed\(\): Promise +isNewCallAllowed\(\): Promise\ Checks whether a new call is allowed. This API uses a promise to return the result. @@ -2747,8 +2779,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -2766,7 +2797,7 @@ promise.then(data => { ## call.separateConference8+ -separateConference\(callId: number, callback: AsyncCallback\): void +separateConference\(callId: number, callback: AsyncCallback\\): void Separates calls from a conference call. This API uses an asynchronous callback to return the result. @@ -2787,6 +2818,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2804,7 +2836,7 @@ call.separateConference(1, (err) => { ## call.separateConference8+ -separateConference\(callId: number\): Promise +separateConference\(callId: number\): Promise\ Separates calls from a conference call. This API uses a promise to return the result. @@ -2830,6 +2862,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2848,7 +2881,7 @@ call.separateConference(1).then(() => { ## call.getCallRestrictionStatus8+ -getCallRestrictionStatus\(slotId: number, type: CallRestrictionType, callback: AsyncCallback\): void +getCallRestrictionStatus\(slotId: number, type: CallRestrictionType, callback: AsyncCallback\\): void Obtains the call restriction status. This API uses an asynchronous callback to return the result. @@ -2873,11 +2906,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2890,7 +2923,7 @@ call.getCallRestrictionStatus(0, 1, (err, data) => { ## call.getCallRestrictionStatus8+ -getCallRestrictionStatus\(slotId: number, type: CallRestrictionType\): Promise +getCallRestrictionStatus\(slotId: number, type: CallRestrictionType\): Promise\ Obtains the call restriction status. This API uses a promise to return the result. @@ -2920,11 +2953,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2939,7 +2972,7 @@ promise.then(data => { ## call.setCallRestriction8+ -setCallRestriction\(slotId: number, info: CallRestrictionInfo, callback: AsyncCallback\): void +setCallRestriction\(slotId: number, info: CallRestrictionInfo, callback: AsyncCallback\\): void Sets the call restriction status. This API uses an asynchronous callback to return the result. @@ -2964,11 +2997,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -2986,7 +3019,7 @@ call.setCallRestriction(0, callRestrictionInfo, (err) => { ## call.setCallRestriction8+ -setCallRestriction\(slotId: number, info: CallRestrictionInfo\): Promise +setCallRestriction\(slotId: number, info: CallRestrictionInfo\): Promise\ Sets the call restriction status. This API uses a promise to return the result. @@ -3016,11 +3049,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -3039,7 +3072,7 @@ call.setCallRestriction(0, callRestrictionInfo).then(() => { ## call.getCallTransferInfo8+ -getCallTransferInfo\(slotId: number, type: CallTransferType, callback: AsyncCallback\): void +getCallTransferInfo\(slotId: number, type: CallTransferType, callback: AsyncCallback\\): void Obtains call transfer information. This API uses an asynchronous callback to return the result. @@ -3064,11 +3097,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -3081,7 +3114,7 @@ call.getCallTransferInfo(0, call.CallTransferType.TRANSFER_TYPE_BUSY, (err, data ## call.getCallTransferInfo8+ -getCallTransferInfo\(slotId: number, type: CallTransferType): Promise +getCallTransferInfo\(slotId: number, type: CallTransferType\): Promise\ Obtains call transfer information. This API uses a promise to return the result. @@ -3111,11 +3144,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -3130,7 +3163,7 @@ promise.then(data => { ## call.setCallTransfer8+ -setCallTransfer\(slotId: number, info: CallTransferInfo, callback: AsyncCallback\): void +setCallTransfer\(slotId: number, info: CallTransferInfo, callback: AsyncCallback\\): void Sets call transfer information. This API uses an asynchronous callback to return the result. @@ -3155,11 +3188,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -3177,7 +3210,7 @@ call.setCallTransfer(0, callTransferInfo, (err) => { ## call.setCallTransfer8+ -setCallTransfer\(slotId: number, info: CallTransferInfo): Promise +setCallTransfer\(slotId: number, info: CallTransferInfo\): Promise\ Sets call transfer information. This API uses a promise to return the result. @@ -3207,11 +3240,11 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | -| 8300999 | Unknown error code. | **Example** @@ -3230,7 +3263,7 @@ call.setCallTransfer(0, callTransferInfo).then(() => { ## call.isRinging8+ -isRinging\(callback: AsyncCallback\): void +isRinging\(callback: AsyncCallback\\): void Checks whether the ringtone is playing. This API uses an asynchronous callback to return the result. @@ -3253,6 +3286,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3270,7 +3304,7 @@ call.isRinging((err, data) => { ## call.isRinging8+ -isRinging\(\): Promise +isRinging\(\): Promise\ Checks whether the ringtone is playing. This API uses a promise to return the result. @@ -3293,8 +3327,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -3312,7 +3345,7 @@ promise.then(data => { ## call.setMuted8+ -setMuted\(callback: AsyncCallback\): void +setMuted\(callback: AsyncCallback\\): void Sets call muting. This API uses an asynchronous callback to return the result. @@ -3332,6 +3365,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3349,7 +3383,7 @@ call.setMuted((err) => { ## call.setMuted8+ -setMuted\(\): Promise +setMuted\(\): Promise\ Sets call muting. This API uses a promise to return the result. @@ -3369,8 +3403,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -3387,7 +3420,7 @@ call.setMuted().then(() => { ## call.cancelMuted8+ -cancelMuted(callback: AsyncCallback): void +cancelMuted\(callback: AsyncCallback\\): void Cancels call muting. This API uses an asynchronous callback to return the result. @@ -3407,6 +3440,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3424,7 +3458,7 @@ call.cancelMuted((err) => { ## call.cancelMuted8+ -cancelMuted(): Promise +cancelMuted\(\): Promise\ Cancels call muting. This API uses a promise to return the result. @@ -3444,8 +3478,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -3462,7 +3495,7 @@ call.cancelMuted().then(() => { ## call.setAudioDevice8+ -setAudioDevice\(device: AudioDevice, callback: AsyncCallback\): void +setAudioDevice\(device: AudioDevice, callback: AsyncCallback\\): void Sets the audio device for a call. This API uses an asynchronous callback to return the result. @@ -3483,6 +3516,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3500,9 +3534,9 @@ call.setAudioDevice(1, (err) => { ## call.setAudioDevice9+ -setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback\): void +setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback\\): void -Sets the audio device for a call based on the specified options. This API uses an asynchronous callback to return the result. +Sets the audio device for a call. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -3522,6 +3556,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3542,7 +3577,7 @@ call.setAudioDevice(1, audioDeviceOptions, (err) => { ## call.setAudioDevice9+ -setAudioDevice(device: AudioDevice, options?: AudioDeviceOptions): Promise +setAudioDevice\(device: AudioDevice, options?: AudioDeviceOptions\): Promise\ Sets the audio device for a call based on the specified options. This API uses a promise to return the result. @@ -3569,6 +3604,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3590,7 +3626,7 @@ call.setAudioDevice(1, audioDeviceOptions).then(() => { ## call.joinConference8+ -joinConference(mainCallId: number, callNumberList: Array, callback: AsyncCallback): void +joinConference\(mainCallId: number, callNumberList: Array\, callback: AsyncCallback\\): void Joins a conference call. This API uses an asynchronous callback to return the result. @@ -3612,6 +3648,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3631,7 +3668,7 @@ call.joinConference(1, callNumberList, (err) => { ## call.joinConference8+ -joinConference(mainCallId: number, callNumberList: Array): Promise +joinConference\(mainCallId: number, callNumberList: Array\\): Promise\ Joins a conference call. This API uses a promise to return the result. @@ -3658,6 +3695,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3679,7 +3717,7 @@ call.joinConference(1, callNumberList).then(() => { ## call.updateImsCallMode8+ -updateImsCallMode(callId: number, mode: ImsCallMode, callback: AsyncCallback): void +updateImsCallMode\(callId: number, mode: ImsCallMode, callback: AsyncCallback\\): void Updates the IMS call mode. This API uses an asynchronous callback to return the result. @@ -3701,6 +3739,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3717,7 +3756,7 @@ call.updateImsCallMode(1, 1, (err) => { ## call.updateImsCallMode8+ -updateImsCallMode(callId: number, mode: ImsCallMode): Promise +updateImsCallMode\(callId: number, mode: ImsCallMode\): Promise\ Updates the IMS call mode. This API uses a promise to return the result. @@ -3744,6 +3783,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3762,7 +3802,7 @@ call.updateImsCallMode(1, 1).then(() => { ## call.enableImsSwitch8+ -enableImsSwitch(slotId: number, callback: AsyncCallback): void +enableImsSwitch\(slotId: number, callback: AsyncCallback\\): void Enables the IMS switch. This API uses an asynchronous callback to return the result. @@ -3786,6 +3826,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3802,7 +3843,7 @@ call.enableImsSwitch(0, (err) => { ## call.enableImsSwitch8+ -enableImsSwitch(slotId: number): Promise +enableImsSwitch\(slotId: number\): Promise\ Enables the IMS switch. This API uses a promise to return the result. @@ -3831,6 +3872,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3849,7 +3891,7 @@ call.enableImsSwitch(0).then(() => { ## call.disableImsSwitch8+ -disableImsSwitch(slotId: number, callback: AsyncCallback): void +disableImsSwitch\(slotId: number, callback: AsyncCallback\\): void Disables the IMS switch. This API uses an asynchronous callback to return the result. @@ -3873,6 +3915,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3889,7 +3932,7 @@ call.disableImsSwitch(0, (err) => { ## call.disableImsSwitch8+ -disableImsSwitch(slotId: number): Promise +disableImsSwitch\(slotId: number\): Promise\ Disables the IMS switch. This API uses a promise to return the result. @@ -3918,6 +3961,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3936,7 +3980,7 @@ call.disableImsSwitch(0).then(() => { ## call.isImsSwitchEnabled8+ -isImsSwitchEnabled(slotId: number, callback: AsyncCallback): void +isImsSwitchEnabled\(slotId: number, callback: AsyncCallback\\): void Checks whether the IMS switch is enabled. This API uses an asynchronous callback to return the result. @@ -3957,6 +4001,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3973,7 +4018,7 @@ call.isImsSwitchEnabled(0, (err, data) => { ## call.isImsSwitchEnabled8+ -isImsSwitchEnabled(slotId: number): Promise +isImsSwitchEnabled\(slotId: number\): Promise\ Checks whether the IMS switch is enabled. This API uses a promise to return the result. @@ -3999,6 +4044,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -4024,11 +4070,11 @@ Provides an option for determining whether a call is a video call. | Name | Type | Mandatory| Description | | ------------------------ | ---------------------------------- | ---- | ----------------------------------------------------------------------------------------------- | -| extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call| -| accountId 8+ | number | No | Account ID.
- **0**: card slot 1
- **1**: card slot 2
This is a system API. | -| videoState 8+ | [VideoStateType](#videostatetype7) | No | Video state type. This is a system API. | -| dialScene 8+ | [DialScene](#dialscene8) | No | Dialup scenario. This is a system API. | -| dialType 8+ | [DialType](#dialtype8) | No | Dialup type. This is a system API. | +| extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call | +| accountId 8+ | number | No | Account ID.
- **0**: card slot 1
- **1**: card slot 2
| +| videoState 8+ | [VideoStateType](#videostatetype7) | No | Video state type. | +| dialScene 8+ | [DialScene](#dialscene8) | No | Dialup scenario. | +| dialType 8+ | [DialType](#dialtype8) | No | Dialup type. | ## DialCallOptions9+ @@ -4409,7 +4455,7 @@ Enumerates call transfer states. ## DisconnectedDetails9+ -Defines the cause of a call disconnection. +Defines the call disconnection cause. **System API**: This is a system API. @@ -4417,12 +4463,12 @@ Defines the cause of a call disconnection. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------ | ---- | --------------- | -| reason | [DisconnectedReason](#disconnectedreason8) | Yes | Cause of the call disconnection. | -| message | string | Yes | Message indicating the call disconnection.| +| reason | [DisconnectedReason](#disconnectedreason8) | Yes | Call disconnection cause. | +| message | string | Yes | Call ending message.| ## DisconnectedReason8+ -Enumerates causes of call disconnection. +Enumerates call disconnection causes. **System API**: This is a system API. diff --git a/en/application-dev/reference/apis/js-apis-charger.md b/en/application-dev/reference/apis/js-apis-charger.md index 0b4f5dba51054c51fd2c74cc1867413340b9a687..4c5d43246672f37ea5cda135492ad71ed4f679da 100644 --- a/en/application-dev/reference/apis/js-apis-charger.md +++ b/en/application-dev/reference/apis/js-apis-charger.md @@ -17,6 +17,8 @@ import charger from '@ohos.charger'; Enumerates charging types. +**System API**: This is a system API. + **System capability**: SystemCapability.PowerManager.BatteryManager.Core | Name | Value | Description | diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 1496c18abf062e412dcc36368d046992b7f95c69..5a4af7f39f321fc486a4e359b567666dc359135a 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -3,6 +3,7 @@ The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. > **NOTE** +> > - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.commonEventManager](js-apis-commonEventManager.md). > > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -19,14 +20,16 @@ A system common event is an event that is published by a system service or syste For details about the definitions of all system common events, see [System Common Events](./commonEvent-definitions.md). -## CommonEvent.publish +## CommonEvent.publish(deprecated) -```ts -publish(event: string, callback: AsyncCallback): void -``` +publish(event: string, callback: AsyncCallback\): void Publishes a common event. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [commonEventManager.publish](js-apis-commonEventManager.md#commoneventmanagerpublish) instead. + **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -52,14 +55,16 @@ function publishCB(err) { CommonEvent.publish("event", publishCB); ``` -## CommonEvent.publish +## CommonEvent.publish(deprecated) -```ts -publish(event: string, options: CommonEventPublishData, callback: AsyncCallback): void -``` +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [commonEventManager.publish](js-apis-commonEventManager.md#commoneventmanagerpublish-1) instead. + **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -68,7 +73,7 @@ Publishes a common event with given attributes. This API uses an asynchronous ca | -------- | ---------------------- | ---- | ---------------------- | | event | string | Yes | Name of the common event to publish. | | options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes | Attributes of the common event to publish.| -| callback | syncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -94,14 +99,16 @@ function publishCB(err) { CommonEvent.publish("event", options, publishCB); ``` -## CommonEvent.publishAsUser8+ +## CommonEvent.publishAsUser(deprecated) -```ts -publishAsUser(event: string, userId: number, callback: AsyncCallback): void -``` +publishAsUser(event: string, userId: number, callback: AsyncCallback\): void Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [commonEventManager.publishAsUser](js-apis-commonEventManager.md#commoneventmanagerpublishasuser) instead. + **System capability**: SystemCapability.Notification.CommonEvent **System API**: This is a system API and cannot be called by third-party applications. @@ -133,14 +140,16 @@ let userId = 100; CommonEvent.publishAsUser("event", userId, publishCB); ``` -## CommonEvent.publishAsUser8+ +## CommonEvent.publishAsUser(deprecated) -```ts -publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback): void -``` +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [commonEventManager.publishAsUser](js-apis-commonEventManager.md#commoneventmanagerpublishasuser-1) instead. + **System capability**: SystemCapability.Notification.CommonEvent **System API**: This is a system API and cannot be called by third-party applications. @@ -180,14 +189,16 @@ let userId = 100; CommonEvent.publishAsUser("event", userId, options, publishCB); ``` -## CommonEvent.createSubscriber +## CommonEvent.createSubscriber(deprecated) -```ts -createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback): void -``` +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void Creates a subscriber. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [commonEventManager.createSubscriber](js-apis-commonEventManager.md#commoneventmanagercreatesubscriber) instead. + **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -222,14 +233,16 @@ function createCB(err, commonEventSubscriber) { CommonEvent.createSubscriber(subscribeInfo, createCB); ``` -## CommonEvent.createSubscriber +## CommonEvent.createSubscriber(deprecated) -```ts -createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise -``` +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ Creates a subscriber. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [commonEventManager.createSubscriber](js-apis-commonEventManager.md#commoneventmanagercreatesubscriber-1) instead. + **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -262,14 +275,16 @@ CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { }); ``` -## CommonEvent.subscribe +## CommonEvent.subscribe(deprecated) -```ts -subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback): void -``` +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void Subscribes to common events. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [commonEventManager.subscribe](js-apis-commonEventManager.md#commoneventmanagersubscribe) instead. + **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -314,14 +329,16 @@ function createCB(err, commonEventSubscriber) { CommonEvent.createSubscriber(subscribeInfo, createCB); ``` -## CommonEvent.unsubscribe +## CommonEvent.unsubscribe(deprecated) -```ts -unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback): void -``` +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void Unsubscribes from common events. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [commonEventManager.subscribe](js-apis-commonEventManager.md#commoneventmanagerunsubscribe) instead. + **System capability**: SystemCapability.Notification.CommonEvent **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md index 292df5cbe51d1b257f37fc42d99b17f7d08ad813..61d22613c35ceb0556ab66748f635c3e92c7b412 100644 --- a/en/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -39,7 +39,6 @@ Publishes a common event and executes an asynchronous callback after the event i | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1500004 | not System services. | | 1500007 | error sending message to Common Event Service. | | 1500008 | Common Event Service does not complete initialization. | @@ -87,7 +86,6 @@ Publishes a common event with given attributes. This API uses an asynchronous ca | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1500004 | not System services. | | 1500007 | error sending message to Common Event Service. | | 1500008 | Common Event Service does not complete initialization. | @@ -144,8 +142,6 @@ Publishes a common event to a specific user. This API uses an asynchronous callb | ID| Error Message | | -------- | ----------------------------------- | -| 202 | not system app. | -| 401 | The parameter check failed. | | 1500004 | not System services. | | 1500007 | error sending message to Common Event Service. | | 1500008 | Common Event Service does not complete initialization. | @@ -199,9 +195,7 @@ Publishes a common event with given attributes to a specific user. This API uses | ID| Error Message | | -------- | ----------------------------------- | -| 202 | not system app. | -| 401 | The parameter check failed. | -| 1500004 | not System services. | +| 1500004 | not System services or System app. | | 1500007 | error sending message to Common Event Service. | | 1500008 | Common Event Service does not complete initialization. | | 1500009 | error obtaining system parameters. | @@ -251,17 +245,8 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul | subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information. | | callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes | Callback used to return the result.| -**Error codes** - - For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). - -| ID| Error Message | -| -------- | ----------------------------------- | -| 401 | The parameter check failed. | - **Example** - ```ts let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. @@ -307,14 +292,6 @@ Creates a subscriber. This API uses a promise to return the result. | --------------------------------------------------------- | ---------------- | | Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the subscriber object.| -**Error codes** - - For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). - -| ID| Error Message | -| -------- | ----------------------------------- | -| 401 | The parameter check failed. | - **Example** ```ts @@ -356,7 +333,6 @@ Subscribes to common events. This API uses an asynchronous callback to return th | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 801 | capability not supported. | | 1500007 | error sending message to Common Event Service. | | 1500008 | Common Event Service does not complete initialization. | @@ -426,7 +402,6 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 801 | capability not supported. | | 1500007 | error sending message to Common Event Service. | | 1500008 | Common Event Service does not complete initialization. | @@ -495,6 +470,8 @@ Removes a sticky common event. This API uses an asynchronous callback to return **Required permissions**: ohos.permission.COMMONEVENT_STICKY +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | @@ -508,12 +485,9 @@ Removes a sticky common event. This API uses an asynchronous callback to return | ID| Error Message | | -------- | ----------------------------------- | -| 201 | The application dose not have permission to call the interface. | -| 202 | not system app. | -| 401 | The parameter check failed. | | 1500004 | not system service. | -| 1500007 | The message send error. | -| 1500008 | The CEMS error. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | **Example** @@ -525,7 +499,6 @@ CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => { return; } console.info(`Remove sticky event AsyncCallback success`); - } }); ``` @@ -539,6 +512,8 @@ Removes a sticky common event. This API uses a promise to return the result. **Required permissions**: ohos.permission.COMMONEVENT_STICKY +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type | Mandatory| Description | @@ -557,20 +532,102 @@ Removes a sticky common event. This API uses a promise to return the result. | ID| Error Message | | -------- | ----------------------------------- | -| 201 | The application dose not have permission to call the interface. | -| 202 | not system app. | -| 401 | The parameter check failed. | | 1500004 | not system service. | -| 1500007 | The message send error. | -| 1500008 | The CEMS error. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | **Example** ```ts -commonEventManager.removeStickyCommonEvent("sticky_event").then(() => { +CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => { console.info(`Remove sticky event AsyncCallback success`); }).catch ((err) => { console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); }); ``` + +## CommonEventManager.setStaticSubscriberState10+ + +setStaticSubscriberState(enable: boolean, callback: AsyncCallback\): void; + +Enables or disables static subscription for the current application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether static subscription is enabled.
**true**: enabled.
**false**: disabled.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + + For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | + +**Example** + + +```ts +CommonEventManager.setStaticSubscriberState(true, (err) => { + if (!err) { + console.info(`Set static subscriber state callback failed, err is null.`); + return; + } + if (err.code) { + console.info(`Set static subscriber state callback failed, errCode: ${err.code}, errMes: ${err.message}`); + return; + } + console.info(`Set static subscriber state callback success`); +}); +``` + +## CommonEventManager.setStaticSubscriberState10+ + +setStaticSubscriberState(enable: boolean): Promise\; + +Enables or disables static subscription for the current application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether static subscription is enabled.
**true**: enabled.
**false**: disabled.| + +**Return value** + +| Type | Description | +| -------------- | ---------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + + For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | + +**Example** + + +```ts +CommonEventManager.setStaticSubscriberState(false).then(() => { + console.info(`Set static subscriber state promise success`); +}).catch ((err) => { + console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index 4c66c928fb7ee6c5482d39db7b39acaa6793691e..8aad8fdf810b9f3246672b8c3d2e21df7733d94e 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -28,7 +28,7 @@ Converts an XML text into a JavaScript object. | Name | Type | Mandatory| Description | | ------- | --------------------------------- | ---- | --------------- | | xml | string | Yes | XML text to convert.| -| options | [ConvertOptions](#convertoptions) | No | Options for conversion. | +| options | [ConvertOptions](#convertoptions) | No | Options for conversion. The default value is a **ConvertOptions** object, which consists of the default values of the attributes in the object. | **Return value** @@ -89,7 +89,7 @@ Converts an XML text into a JavaScript object. | Name | Type | Mandatory| Description | | ------- | --------------------------------- | ---- | --------------- | | xml | string | Yes | XML text to convert.| -| options | [ConvertOptions](#convertoptions) | No | Options for conversion. | +| options | [ConvertOptions](#convertoptions) | No | Options for conversion. The default value is a **ConvertOptions** object, which consists of the default values of the attributes in the object. | **Return value** diff --git a/en/application-dev/reference/apis/js-apis-cooperate.md b/en/application-dev/reference/apis/js-apis-cooperate.md index d63729a9dcf6a08133dd28f7cdabc6e63f0a4b6e..da39b72f0cae0702e82eb18b80e034f03c60936d 100644 --- a/en/application-dev/reference/apis/js-apis-cooperate.md +++ b/en/application-dev/reference/apis/js-apis-cooperate.md @@ -1,12 +1,12 @@ # @ohos.multimodalInput.inputDeviceCooperate (Screen Hopping) -The **inputDeviceCooperate** module enables two or more networked devices to share the keyboard and mouse for collaborative operations. +The **inputDeviceCooperate** module implements screen hopping for two or more networked devices to share the keyboard and mouse for collaborative operations. > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs provided by this module are system APIs. - +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -66,7 +66,7 @@ Specifies whether to enable screen hopping. This API uses a promise to return th **Return value** -| Name | Description | +| Parameters | Description | | ------------------- | ------------------------------- | | Promise<void> | Promise used to return the result. | @@ -221,7 +221,7 @@ Stops screen hopping. This API uses a promise to return the result. | Name | Description | | -------- | ---------------------------- | -| Promise\ | Promise used to return the result. | +| Promise\ | Promise used to return the result. | **Example** @@ -287,7 +287,7 @@ Checks whether screen hopping is enabled. This API uses a promise to return the **Return value** -| Name | Description | +| Parameters | Description | | ------------------- | ------------------------------- | | Promise<{ state: boolean }>| Promise used to return the result. | @@ -296,6 +296,7 @@ Checks whether screen hopping is enabled. This API uses a promise to return the **Example** ```js +let deviceDescriptor = "descriptor"; try { inputDeviceCooperate.getState(deviceDescriptor).then((data) => { console.log(`Get the status success, data: ${JSON.stringify(data)}`); @@ -311,7 +312,7 @@ try { on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, eventMsg: EventMsg }>): void -Enables listening for screen hopping events. +Enables listening for screen hopping status change events. **System capability**: SystemCapability.MultimodalInput.Input.Cooperator @@ -340,7 +341,7 @@ try { off(type: 'cooperation', callback?: AsyncCallback\): void -Disables listening for screen hopping events. +Disables listening for screen hopping status change events. **System capability**: SystemCapability.MultimodalInput.Input.Cooperator @@ -388,7 +389,7 @@ Enumerates screen hopping event. **System capability**: SystemCapability.MultimodalInput.Input.Cooperator -| Name | Value | Description | +| Name | Value | Description | | -------- | --------- | ----------------- | | MSG_COOPERATE_INFO_START | 200 | Screen hopping starts. | | MSG_COOPERATE_INFO_SUCCESS | 201 | Screen hopping succeeds. | diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index 4b6512f5a040108714c782387e81393a9dab4df7..596d5a1666d0481558af56303d39811bfe4a32aa 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -232,7 +232,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ----------------------------------------- | -| 17700004 | The specified user ID is not found. | | 17700023 | The specified default app does not exist. | | 17700025 | The specified type is invalid. | @@ -415,7 +414,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ---------------------------------------------- | -| 17700004 | The specified user ID is not found. | | 17700025 | The specified type is invalid. | | 17700028 | The specified ability does not match the type. | @@ -574,7 +572,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ----------------------------------- | -| 17700004 | The specified user ID is not found. | | 17700025 | The specified type is invalid. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md new file mode 100644 index 0000000000000000000000000000000000000000..cada3fc494deced44ecf150dae636786f167bb3a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md @@ -0,0 +1,457 @@ +# @ohos.cooperate (Screen Hopping) + +The **cooperate** module implements screen hopping for two or more networked devices to share the keyboard and mouse for collaborative operations. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are system APIs. + +## Modules to Import + +```js +import cooperate from '@ohos.cooperate' +``` + +## cooperate.prepare + +prepare(callback: AsyncCallback<void>): void; + +Prepares for screen hopping. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------------------------- | +| callback | AsyncCallback<void> | Yes|Callback used to return the result. | + +**Example** + +```js +try { + cooperate.prepare((error) => { + if (error) { + console.log(`Keyboard mouse crossing prepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Keyboard mouse crossing prepare success.`); + }); +} catch (error) { + console.log(`Keyboard mouse crossing prepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## cooperate.prepare + +prepare(): Promise<void> + +Prepares for screen hopping. This API uses a promise to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Return value** + +| Parameters | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| + + + +**Example** + +```js +try { + cooperate.prepare().then(() => { + console.log(`Keyboard mouse crossing prepare success.`); + }, (error) => { + console.log(`Keyboard mouse crossing prepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Keyboard mouse crossing prepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + + + +## cooperate.unprepare + +unprepare(callback: AsyncCallback<void>): void; + +Cancels the preparation for screen hopping. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------ | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + cooperate.unprepare((error) => { + if (error) { + console.log(`Keyboard mouse crossing unprepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Keyboard mouse crossing unprepare success.`); + }); +} catch (error) { + console.log(`Keyboard mouse crossing unprepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + + + +## cooperate.unprepare + +unprepare(): Promise<void>; + +Cancels the preparation for screen hopping. This API uses a promise to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Return value** + +| Parameters | Description | +| ------------------- | --------------------------------------------- | +| Promise<void> | Promise used to return the result.| + +```js +try { + cooperate.unprepare().then(() => { + console.log(`Keyboard mouse crossing unprepare success.`); + }, (error) => { + console.log(`Keyboard mouse crossing unprepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Keyboard mouse crossing unprepare failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + + + +## cooperate.activate + +activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback<void>): void; + +Starts screen hopping. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| targetNetworkId | string | Yes | Descriptor of the target device for screen hopping. | +| inputDeviceId | number | Yes | Identifier of the input device for screen hopping.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Screen Hopping Error Codes](../errorcodes/errorcode-devicestatus.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. | + +**Example** + +```js +let targetNetworkId = "networkId"; +let inputDeviceId = 0; +try { + cooperate.activate(targetNetworkId, inputDeviceId, (error) => { + if (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Start Keyboard mouse crossing success.`); + }); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## cooperate.activate + +activate(targetNetworkId: string, inputDeviceId: number): Promise<void>; + +Starts screen hopping. This API uses a promise to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| targetNetworkId | string | Yes | Descriptor of the target device for screen hopping. | +| inputDeviceId | number | Yes | Identifier of the input device for screen hopping.| + + + +**Return value** + +| Name | Description | +| ---------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result. | + +**Error codes** + +For details about the error codes, see [Screen Hopping Error Codes](../errorcodes/errorcode-devicestatus.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. | + +**Example** + +```js +let targetNetworkId = "networkId"; +let inputDeviceId = 0; +try { + cooperate.activate(targetNetworkId, inputDeviceId).then(() => { + console.log(`Start Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## cooperate.deactivate + +deactivate(isUnchained: boolean, callback: AsyncCallback<void>): void; + +Stops screen hopping. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| isUnchained | boolean | Yes| Whether to disable the cross-device link.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + + + +**Example** + +```js +try { + cooperate.deactivate(false, (error) => { + if (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Stop Keyboard mouse crossing success.`); + }); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## cooperate.deactivate + +deactivate(isUnchained: boolean): Promise<void>; + +Stops screen hopping. This API uses a promise to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | ------------------ | +| isUnchained | boolean | Yes | Whether to disable the cross-device link.| + + + +**Return value** + +| Name | Description | +| -------- | ---------------------------- | +| Promise<void> | Promise used to return the result. | + + + +**Example** + +```js +try { + cooperate.deactivate(false).then(() => { + console.log(`Stop Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## cooperate.getCrossingSwitchState + +getCrossingSwitchState(networkId: string, callback: AsyncCallback<boolean>): void; + +Obtains the screen hopping status of the target device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------- | ---- | ---------------------------- | +| networkId | string | Yes | Descriptor of the target device for screen hopping. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +let deviceDescriptor = "networkId"; +try { + cooperate.getCrossingSwitchState(deviceDescriptor, (error, data) => { + if (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Get the status success, data: ${JSON.stringify(data)}`); + }); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## cooperate.getCrossingSwitchState + +getCrossingSwitchState(networkId: string): Promise<boolean>; + +Obtains the screen hopping status of the target device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------- | ---- | ---------------------------- | +| networkId | string | Yes | Descriptor of the target device for screen hopping. | + + + +**Return value** + +| Parameters | Description | +| ------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the result.| + + + +**Example** + +```js +let deviceDescriptor = "networkId"; +try { + cooperate.getCrossingSwitchState(deviceDescriptor).then((data) => { + console.log(`Get the status success, data: ${JSON.stringify(data)}`); + }, (error) => { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## on('cooperate') + +on(type: 'cooperate', callback: Callback<{ networkId: string, msg: CooperateMsg }>): void; + +Enables listening for screen hopping status change events. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| type | string | Yes | Event type. The value is **cooperate**.| +| callback | Callback<{ networkId: string, msg: [CooperateMsg](#cooperatemsg) }> | Yes | Callback used to return the result.| + + + +**Example** + +```js +try { + cooperate.on('cooperate', (data) => { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`); + }); +} catch (error) { + console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## off('cooperate') + +off(type: 'cooperate', callback?: Callback<void>): void; + +Disables listening for screen hopping status change events. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| type | string | Yes | Event type. The value is **cooperate**.| +| callback | AsyncCallback<void> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.| + + + +**Example** + +```js +// Unregister a single callback. +function callback(event) { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); + return false; +} +try { + cooperate.on('cooperate', callback); + cooperate.off("cooperate", callback); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` +```js +// Unregister all callbacks. +function callback(event) { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); + return false; +} +try { + cooperate.on('cooperate', callback); + cooperate.off("cooperate"); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## CooperateMsg + +Represents a screen hopping message notification. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Cooperate + +| Name | Value | Description | +| -------- | ----------------- | ----------------- | +| COOPERATE_PREPARE | 0 | The preparation for screen hopping is finished. | +| COOPERATE_UNPREPARE | 1 | The preparation for screen hopping is cancelled. | +| COOPERATE_ACTIVATE | 2 | Screen hopping starts. | +| COOPERATE_ACTIVATE_SUCCESS | 3 | Starting screen hopping succeeds.| +| COOPERATE_ACTIVATE_FAIL | 4 | Starting screen hopping fails.| +| COOPERATE_DEACTIVATE_SUCCESS | 5 | Stopping screen hopping succeeds.| +| COOPERATE_DEACTIVATE_FAIL | 6 | Stopping screen hopping fails.| diff --git a/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md b/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md index 3fa93ccd105819ea71a709d861a71287ae1312cc..4942ff0b537c71b02ccdc20700dc31978f12c990 100644 --- a/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md +++ b/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md @@ -3,10 +3,8 @@ The **cloudSyncManager** module provides APIs for changing the cloud and device service status and notifying the data changes. > **NOTE** -> > - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs and cannot be called by third-party applications. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import @@ -36,6 +34,15 @@ Changes the device-cloud file synchronization switch for an application. This AP | --------------------- | ---------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | + **Example** ```js @@ -65,6 +72,15 @@ Changes the device-cloud file synchronization switch for an application. This AP | status | boolean | Yes | State of the cloud-device file synchronization switch to set. The value **true** means to enable this function; the value **false** means the opposite.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | + **Example** ```js @@ -78,6 +94,7 @@ Changes the device-cloud file synchronization switch for an application. This AP } }); ``` + ## cloudSyncManager.notifyDataChange notifyDataChange(accountId: string, bundleName: string): Promise<void>; @@ -99,6 +116,15 @@ Notifies the cloud and device services of the application data change in the clo | --------------------- | ---------------- | | Promise<void> | Promise used to return the application data change in the cloud.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | + **Example** ```js @@ -127,6 +153,15 @@ Notifies the cloud and device services of the application data change in the clo | bundleName | string | Yes | Bundle name of the application.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the application data change in the cloud.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-environment.md b/en/application-dev/reference/apis/js-apis-file-environment.md index c87c8465d7909f495baf6babad02e8e5b118424c..fb48f1a4103cb29bff4fb48e076ef2d87c717ab2 100644 --- a/en/application-dev/reference/apis/js-apis-file-environment.md +++ b/en/application-dev/reference/apis/js-apis-file-environment.md @@ -1,12 +1,11 @@ # @ohos.file.environment (Directory Environment Capability) -The **Environment** module provides APIs for obtaining the root directories of the storage and public files. +The **Environment** module provides APIs for obtaining the root directories of the storage and user files. > **NOTE** > > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs and cannot be called by third-party applications. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import @@ -28,6 +27,15 @@ Obtains the root directory of the storage. This API uses a promise to return the | --------------------- | ---------------- | | Promise<string> | Promise used to return the root directory of the storage.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 202 | The caller is not a system application | +| 13900020 | Invalid argument | +| 13900042 | Unknown error | + **Example** ```js @@ -52,6 +60,15 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac | -------- | --------------------------- | ---- | -------------------------------- | | callback | AsyncCallback<string> | Yes | Asynchronous callback invoked to return the root directory of the storage.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 202 | The caller is not a system application | +| 13900020 | Invalid argument | +| 13900042 | Unknown error | + **Example** ```js @@ -68,7 +85,7 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac getUserDataDir():Promise<string> -Obtains the root directory of public files. This API uses a promise to return the result. +Obtains the root directory of user files. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.Environment @@ -76,7 +93,16 @@ Obtains the root directory of public files. This API uses a promise to return th | Type | Description | | --------------------- | ------------------ | -| Promise<string> | Promise returned with the root directory of public files.| +| Promise<string> | Promise used to return the root directory of user files.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 202 | The caller is not a system application | +| 13900020 | Invalid argument | +| 13900042 | Unknown error | **Example** @@ -92,7 +118,7 @@ Obtains the root directory of public files. This API uses a promise to return th getUserDataDir(callback:AsyncCallback<string>): void -Obtains the root directory of public files. This API uses an asynchronous callback to return the result. +Obtains the root directory of user files. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.Environment @@ -100,7 +126,16 @@ Obtains the root directory of public files. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of public files.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of user files.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +| ID | Error Message | +| ---------------------------- | ---------- | +| 202 | The caller is not a system application | +| 13900020 | Invalid argument | +| 13900042 | Unknown error | **Example** diff --git a/en/application-dev/reference/apis/js-apis-file-fileuri.md b/en/application-dev/reference/apis/js-apis-file-fileuri.md index f8c6717fab58f9ca5eacac6ebc3963a6faae63fa..1aa5fe9cf08005980285bd04ae87763e58de8751 100644 --- a/en/application-dev/reference/apis/js-apis-file-fileuri.md +++ b/en/application-dev/reference/apis/js-apis-file-fileuri.md @@ -41,9 +41,9 @@ Obtains the URI of a file in synchronous mode. **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| string | File URI obtained.| + | Type | Description | + | ---------------------------- | ---------- | + | string | File URI obtained.| **Error codes** @@ -52,7 +52,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod | ---------------------------- | ---------- | | 401 | The input parameter is invalid | - **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md index 897d38e76b6614eaa3f4078cbbcb4b5f6ddc893b..d063029b27f7b8a705bf61ef757cf5f997c1995b 100644 --- a/en/application-dev/reference/apis/js-apis-file-fs.md +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -14,7 +14,7 @@ import fs from '@ohos.file.fs'; ## Guidelines -Before using the APIs provided by this module to perform operations on a file or folder, obtain the application sandbox path of the file or folder as follows: +Before using the APIs provided by this module to perform operations on a file or directory, obtain the application sandbox path of the file or directory as follows: **Stage Model** @@ -29,7 +29,7 @@ export default class EntryAbility extends UIAbility { } ``` -**FA Model** +FA Model ```js import featureAbility from '@ohos.ability.featureAbility'; @@ -58,13 +58,13 @@ Obtains detailed file information. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| Promise<[Stat](#stat)> | Promise used to return the file information obtained.| + | Type | Description | + | ---------------------------- | ---------- | + | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -94,7 +94,7 @@ Obtains detailed file information. This API uses an asynchronous callback to ret **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -120,17 +120,17 @@ Obtains detailed file information synchronously. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| file | string\|number | Yes | Application sandbox path or FD of the file.| +| file | string\|number | Yes | Application sandbox path or file descriptor (FD) of the file.| **Return value** -| Type | Description | -| ------------- | ---------- | -| [Stat](#stat) | File information obtained.| + | Type | Description | + | ------------- | ---------- | + | [Stat](#stat) | File information obtained.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -155,13 +155,13 @@ Checks whether a file exists. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -193,7 +193,7 @@ Checks whether a file exists. This API uses an asynchronous callback to return t **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -226,13 +226,13 @@ Synchronously checks whether a file exists. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| boolean | Returns **true** if the file exists; returns **false** otherwise.| + | Type | Description | + | ------------------- | ---------------------------- | + | boolean | Returns **true** if the file exists; returns **false** otherwise.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -259,19 +259,19 @@ Closes a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | file | [File](#file)\|number | Yes | File object or FD of the file to close.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -296,14 +296,14 @@ Closes a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------ | -| file | [File](#file)\|number | Yes | File object or FD of the file to close.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | file | [File](#file)\|number | Yes | File object or FD of the file to close.| + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is closed.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -329,13 +329,13 @@ Synchronously closes a file. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | file | [File](#file)\|number | Yes | File object or FD of the file to close.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -355,21 +355,21 @@ Copies a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------- | ---- | ---------------------------------------- | -| src | string\|number | Yes | Path or FD of the file to copy. | -| dest | string\|number | Yes | Destination path of the file or FD of the file created. | -| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file of the same name.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string\|number | Yes | Path or FD of the file to copy. | + | dest | string\|number | Yes | Destination path of the file or FD of the file created. | + | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -393,16 +393,16 @@ Copies a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------- | ---- | ---------------------------------------- | -| src | string\|number | Yes | Path or FD of the file to copy. | -| dest | string\|number | Yes | Destination path of the file or FD of the file created. | -| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | -------------------------- | ---- | ---------------------------------------- | + | src | string\|number | Yes | Path or FD of the file to copy. | + | dest | string\|number | Yes | Destination path of the file or FD of the file created. | + | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is copied. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -429,15 +429,15 @@ Synchronously copies a file. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------- | ---- | ---------------------------------------- | -| src | string\|number | Yes | Path or FD of the file to copy. | -| dest | string\|number | Yes | Destination path of the file or FD of the file created. | -| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string\|number | Yes | Path or FD of the file to copy. | + | dest | string\|number | Yes | Destination path of the file or FD of the file created. | + | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -447,6 +447,93 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem fs.copyFileSync(srcPath, dstPath); ``` +## fs.copyDir10+ + +copyDir(src: string, dest: string, mode?: number): Promise\ + +Copies a directory to the specified directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the directory to copy.| + | dest | string | Yes | Application sandbox path of the destination directory.| + | mode | number | No | Copy mode. The default value is **0**.
- **0**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **1**: Forcibly overwrite the files with the same name in the destination directory.
If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| + +**Return value** + + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +**Example** + + ```js + // Copy srcPath to destPath. + let srcPath = pathDir + "/srcDir/"; + let destPath = pathDir + "/destDir/"; + fs.copyDir(srcPath, destPath, 0).then(() => { + console.info("copy directory succeed"); + }).catch((err) => { + if (err.code == 13900015) { + for (let i = 0; i < err.data.length; i++) { + console.info("copy directory failed with conflicting files: " + err.data[i].srcFile + + " " + err.data[i].destFile); + } + } else { + console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code); + } + }); + ``` + +## fs.copyDir10+ + +copyDir(src: string, dest: string, mode?: number, callback: AsyncCallback\): void + +Copies a directory to the specified directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the directory to copy.| + | dest | string | Yes | Application sandbox path of the destination directory.| + | mode | number | No | Copy mode. The default value is **0**.
- **0**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **1**: Forcibly overwrite the files with the same name in the destination directory.
If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the directory is copied. | + +**Error codes** + + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +**Example** + + ```js + // Copy srcPath to destPath. + let srcPath = pathDir + "/srcDir/"; + let destPath = pathDir + "/destDir/"; + fs.copyDir(srcPath, destPath, 0, (err) => { + if (err && err.code == 13900015) { + for (let i = 0; i < err.data.length; i++) { + console.info("copy directory failed with conflicting files: " + err.data[i].srcFile + + " " + err.data[i].destFile); + } + } else if (err) { + console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("copy directory succeed"); + } + }); + ``` + ## fs.mkdir mkdir(path: string): Promise<void> @@ -463,13 +550,13 @@ Creates a directory. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -499,7 +586,7 @@ Creates a directory. This API uses an asynchronous callback to return the result **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -530,7 +617,7 @@ Synchronously creates a directory. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -556,13 +643,13 @@ Opens a file. This API uses a promise to return the result. File uniform resourc **Return value** -| Type | Description | -| --------------------- | ----------- | -| Promise<[File](#file)> | Promise used to return the file object.| + | Type | Description | + | --------------------- | ----------- | + | Promise<[File](#file)> | Promise used to return the file object.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -593,7 +680,7 @@ Opens a file. This API uses an asynchronous callback to return the result. File **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -625,13 +712,13 @@ Synchronously opens a file. File URIs are supported. **Return value** -| Type | Description | -| ------ | ----------- | -| [File](#file) | File object opened.| + | Type | Description | + | ------ | ----------- | + | [File](#file) | File object opened.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -660,13 +747,13 @@ Reads data from a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<number> | Promise used to return the data read.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<number> | Promise used to return the data read.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -693,16 +780,16 @@ Reads data from a file. This API uses an asynchronous callback to return the res **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| -| callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -731,21 +818,21 @@ Synchronously reads data from a file. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data read.| + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -773,13 +860,13 @@ Deletes a directory. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -809,7 +896,7 @@ Deletes a directory. This API uses an asynchronous callback to return the result **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -840,7 +927,7 @@ Synchronously deletes a directory. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -865,13 +952,13 @@ Deletes a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -897,11 +984,11 @@ Deletes a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | +| callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is deleted. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -932,7 +1019,7 @@ Synchronously deletes a file. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -952,21 +1039,21 @@ Writes data into a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| **Return value** -| Type | Description | -| --------------------- | -------- | -| Promise<number> | Promise used to return the length of the data written.| + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Promise used to return the length of the data written.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -991,16 +1078,16 @@ Writes data into a file. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| -| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1027,21 +1114,21 @@ Synchronously writes data into a file. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data written in the file.| + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1070,13 +1157,13 @@ Truncates a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1108,7 +1195,7 @@ Truncates a file. This API uses an asynchronous callback to return the result. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1141,7 +1228,7 @@ Synchronously truncates a file. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1168,13 +1255,13 @@ Reads the text content of a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| --------------------- | ---------- | -| Promise<string> | Promise used to return the content read.| + | Type | Description | + | --------------------- | ---------- | + | Promise<string> | Promise used to return the content read.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1205,7 +1292,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1237,13 +1324,13 @@ Synchronously reads the text of a file. **Return value** -| Type | Description | -| ------ | -------------------- | -| string | Promise used to return the content of the file read.| + | Type | Description | + | ------ | -------------------- | + | string | Promise used to return the content of the file read.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1269,13 +1356,13 @@ Obtains information about a symbolic link. This API uses a promise to return the **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| + | Type | Description | + | ---------------------------- | ---------- | + | Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1305,7 +1392,7 @@ Obtains information about a symbolic link. This API uses an asynchronous callbac **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1336,13 +1423,13 @@ Obtains information about a symbolic link synchronously. **Return value** -| Type | Description | -| ------------- | ---------- | -| [Stat](#stat) | File information obtained.| + | Type | Description | + | ------------- | ---------- | + | [Stat](#stat) | File information obtained.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1368,13 +1455,13 @@ Renames a file or folder. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1406,7 +1493,7 @@ Renames a file or folder. This API uses an asynchronous callback to return the r **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1439,7 +1526,7 @@ Renames a file or folder synchronously. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1459,19 +1546,19 @@ Flushes data of a file to disk. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1495,14 +1582,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------------- | -| fd | number | Yes | FD of the file. | -| Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | FD of the file. | + | Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1530,13 +1617,13 @@ Flushes data of a file to disk synchronously. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1557,19 +1644,19 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1594,14 +1681,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------- | -| fd | number | Yes | FD of the file. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ----------------- | + | fd | number | Yes | FD of the file. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1628,13 +1715,13 @@ Synchronizes data in a file synchronously. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1662,13 +1749,13 @@ Creates a symbolic link based on a file path. This API uses a promise to return **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1700,7 +1787,7 @@ Creates a symbolic link based on a file path. This API uses an asynchronous call **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1733,7 +1820,7 @@ Synchronously creates a symbolic link based on a file path. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1750,34 +1837,34 @@ listFile(path: string, options?: { filter?: Filter; }): Promise -Lists all files in a directory. This API uses a promise to return the result.
This API supports recursive listing of all files (including files in subdirectories) and file filtering. +Lists all files in a folder. This API uses a promise to return the result.
This API supports recursive listing of all files (including files in subfolders) and file filtering. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| path | string | Yes | Application sandbox path of the folder.| -| options | Object | No | File filtering options. The files are not filtered by default.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| **options parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| -| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| -| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| + | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| **Return value** -| Type | Description | -| --------------------- | ---------- | -| Promise<string[]> | Promise used to return the files names listed.| + | Type | Description | + | --------------------- | ---------- | + | Promise<string[]> | Promise used to return the files names listed.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1809,27 +1896,27 @@ listFile(path: string, options?: { filter?: Filter; }, callback: AsyncCallback): void -Lists all files in a directory. This API uses an asynchronous callback to return the result.
This API supports recursive listing of all files (including files in subdirectories) and file filtering. +Lists all files in a folder. This API uses an asynchronous callback to return the result.
This API supports recursive listing of all files (including files in subfolders) and file filtering. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| path | string | Yes | Application sandbox path of the folder.| -| options | Object | No | File filtering options. The files are not filtered by default.| -| callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| + | callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | **options parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| -| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| -| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| + | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1864,32 +1951,32 @@ listFileSync(path: string, options?: { filter?: Filter; }): string[] -Lists all files in a directory synchronously. This API supports recursive listing of all files (including files in subdirectories) and file filtering. +Lists all files in a folder synchronously. This API supports recursive listing of all files (including files in subfolders) and file filtering. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| path | string | Yes | Application sandbox path of the folder.| -| options | Object | No | File filtering options. The files are not filtered by default.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| **options parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| -| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| -| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| + | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| **Return value** -| Type | Description | -| --------------------- | ---------- | -| string[] | File names listed.| + | Type | Description | + | --------------------- | ---------- | + | string[] | File names listed.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -1915,32 +2002,32 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem moveDir(src: string, dest: string, mode?: number): Promise\ -Moves a folder. This API uses a promise to return the result. +Moves a directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source folder.| -| dest | string | Yes | Application sandbox path of the destination folder.| -| mode | number | No | Mode for moving the folder. The default value is **0**.
- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.
- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.
- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.
- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the directory to move.| + | dest | string | Yes | Application sandbox path of the destination directory.| + | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **2**: Forcibly overwrite the conflicting files in the destination directory.
If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.
- **3**: Forcibly overwrite the conflicting directory.
Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** ```js - // move directory from srcPath to destPath/srcPath + // move directory from srcPath to destPath let srcPath = pathDir + "/srcDir/"; let destPath = pathDir + "/destDir/"; fs.moveDir(srcPath, destPath, 1).then(() => { @@ -1961,27 +2048,27 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\): void -Moves a folder. This API uses an asynchronous callback to return the result. +Moves a directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source folder.| -| dest | string | Yes | Application sandbox path of the destination folder.| -| mode | number | No | Mode for moving the folder. The default value is **0**.
- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.
- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.
- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.
- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the folder is moved. | + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source directory.| + | dest | string | Yes | Application sandbox path of the destination directory.| + | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **2**: Forcibly overwrite the conflicting files in the destination directory.
If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.
- **3**: Forcibly overwrite the conflicting directory.
Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is moved. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** ```js - // move directory from srcPath to destPath/srcPath + // move directory from srcPath to destPath let srcPath = pathDir + "/srcDir/"; let destPath = pathDir + "/destDir/"; fs.moveDir(srcPath, destPath, 1, (err) => { @@ -2008,21 +2095,21 @@ Moves a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source file.| -| dest | string | Yes | Application sandbox path of the destination file.| -| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| + | mode | number | No | Whether to overwrite the file with the same name in the destination directory.
The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.
The default value is **0**.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2046,16 +2133,16 @@ Moves a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source file.| -| dest | string | Yes | Application sandbox path of the destination file.| -| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| + | mode | number | No | Whether to overwrite the file with the same name in the destination directory.
The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.
The default value is **0**.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2081,15 +2168,15 @@ Moves a file synchronously. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source file.| -| dest | string | Yes | Application sandbox path of the destination file.| -| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| + | mode | number | No | Whether to overwrite the file with the same name in the destination directory.
The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.
The default value is **0**.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2110,19 +2197,19 @@ Creates a temporary directory. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** -| Type | Description | -| --------------------- | ---------- | -| Promise<string> | Promise used to return the unique directory generated.| + | Type | Description | + | --------------------- | ---------- | + | Promise<string> | Promise used to return the unique directory generated.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2144,14 +2231,14 @@ Creates a temporary directory. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| -| callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | --------------------------- | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2175,25 +2262,25 @@ Synchronously creates a temporary directory. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** -| Type | Description | -| ------ | ---------- | -| string | Unique path generated.| + | Type | Description | + | ------ | ---------- | + | string | Unique path generated.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** ```js let res = fs.mkdtempSync(pathDir + "/XXXXXX"); - ``` + ``` ## fs.createStream @@ -2212,13 +2299,13 @@ Creates a stream based on the file path. This API uses a promise to return the r **Return value** -| Type | Description | -| --------------------------------- | --------- | -| Promise<[Stream](#stream)> | Promise used to return the result.| + | Type | Description | + | --------------------------------- | --------- | + | Promise<[Stream](#stream)> | Promise used to return the result.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2250,7 +2337,7 @@ Creates a stream based on the file path. This API uses an asynchronous callback **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2282,13 +2369,13 @@ Synchronously creates a stream based on the file path. **Return value** -| Type | Description | -| ------------------ | --------- | -| [Stream](#stream) | Stream opened.| + | Type | Description | + | ------------------ | --------- | + | [Stream](#stream) | Stream opened.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2302,26 +2389,26 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem fdopenStream(fd: number, mode: string): Promise<Stream> -Opens a stream based on the FD. This API uses a promise to return the result. +Opens a stream based on the file descriptor. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** -| Type | Description | -| --------------------------------- | --------- | -| Promise<[Stream](#stream)> | Promise used to return the result.| + | Type | Description | + | --------------------------------- | --------- | + | Promise<[Stream](#stream)> | Promise used to return the result.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2340,21 +2427,21 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void -Opens a stream based on the FD. This API uses an asynchronous callback to return the result. +Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| -| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is opened. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2375,26 +2462,26 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem fdopenStreamSync(fd: number, mode: string): Stream -Synchronously opens a stream based on the FD. +Synchronously opens a stream based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| **Return value** -| Type | Description | -| ------------------ | --------- | -| [Stream](#stream) | Stream opened.| + | Type | Description | + | ------------------ | --------- | + | [Stream](#stream) | Stream opened.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2417,21 +2504,21 @@ Creates a **Watcher** object to observe file or directory changes. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| path | string | Yes | Application sandbox path of the file or directory to observe. | -| events | number | Yes | Events to observe. Multiple events can be separated by a bitwise OR operator (|)|.
- **0x1: IN_ACCESS**: A file is accessed.
- **0x2: IN_MODIFY**: The file content is modified.
- **0x4: IN_ATTRIB**: Metadata is changed.
- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.
- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.
- **0x20: IN_OPEN**: A file or directory is opened.
- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.
- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.
- **0x100: IN_CREATE**: A file or directory is created in the observed directory.
- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.
- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.
- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.
- **0xfff: IN_ALL_EVENTS**: All events.| -| listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. | + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Application sandbox path of the file or directory to observe. | + | events | number | Yes | Events to observe. Multiple events can be separated by a bitwise OR operator (|)|.
- **0x1: IN_ACCESS**: A file is accessed.
- **0x2: IN_MODIFY**: The file content is modified.
- **0x4: IN_ATTRIB**: Metadata is changed.
- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.
- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.
- **0x20: IN_OPEN**: A file or directory is opened.
- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.
- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.
- **0x100: IN_CREATE**: A file or directory is created in the observed directory.
- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.
- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.
- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.
- **0xfff: IN_ALL_EVENTS**: All events.| + | listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. | **Return value** -| Type | Description | -| ------------------ | --------- | -| [Watcher](#watcher10) | **Watcher** object created.| + | Type | Description | + | ------------------ | --------- | + | [Watcher](#watcher10) | **Watcher** object created.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2463,10 +2550,10 @@ Called when an observed event occurs. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| event | WatchEvent | Yes | Event for the callback to invoke. | - + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | event | WatchEvent | Yes | Event for the callback to invoke. | + ## WatchEvent10+ Defines the event to observe. @@ -2490,7 +2577,7 @@ Represents detailed file information. Before calling any API of the **Stat()** c ### Attributes | Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | +| ------ | ------ | ---- | ---- | ---------------------------------------- | | ino | number | Yes | No | File ID. Different files on the same device have different **ino**s.| | | mode | number | Yes | No | File permissions. The meaning of each bit is as follows:
- **0o400**: The owner has the read permission on a regular file or a directory entry.
- **0o200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o040**: The user group has the read permission on a regular file or a directory entry.
- **0o020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o004**: Other users have the permission to read a regular file or read a directory entry.
- **0o002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| | uid | number | Yes | No | ID of the file owner.| @@ -2510,13 +2597,13 @@ Checks whether this file is a block special file. A block special file supports **Return value** -| Type | Description | -| ------- | ---------------- | -| boolean | Whether the file is a block special file.| + | Type | Description | + | ------- | ---------------- | + | boolean | Whether the file is a block special file.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2535,13 +2622,13 @@ Checks whether this file is a character special file. A character special file s **Return value** -| Type | Description | -| ------- | ----------------- | -| boolean | Whether the file is a character special file.| + | Type | Description | + | ------- | ----------------- | + | boolean | Whether the file is a character special file.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2560,13 +2647,13 @@ Checks whether this file is a directory. **Return value** -| Type | Description | -| ------- | ------------- | -| boolean | Whether the file is a directory.| + | Type | Description | + | ------- | ------------- | + | boolean | Whether the file is a directory.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2585,13 +2672,13 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int **Return value** -| Type | Description | -| ------- | --------------------- | -| boolean | Whether the file is a FIFO.| + | Type | Description | + | ------- | --------------------- | + | boolean | Whether the file is a FIFO.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2610,13 +2697,13 @@ Checks whether this file is a regular file. **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the file is a regular file.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the file is a regular file.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2635,13 +2722,13 @@ Checks whether this file is a socket. **Return value** -| Type | Description | -| ------- | -------------- | -| boolean | Whether the file is a socket.| + | Type | Description | + | ------- | -------------- | + | boolean | Whether the file is a socket.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2660,13 +2747,13 @@ Checks whether this file is a symbolic link. **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the file is a symbolic link.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the file is a symbolic link.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2689,13 +2776,13 @@ Closes the stream. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ------------- | -| Promise<void> | Promise used to return the stream close result.| + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream close result.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2719,13 +2806,13 @@ Closes the stream. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the stream is closed.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2736,7 +2823,7 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem if (err) { console.info("close stream failed with error message: " + err.message + ", error code: " + err.code); } else { - console.info("close stream success"): + console.info("close stream success"); } }); ``` @@ -2751,7 +2838,7 @@ Synchronously closes the stream. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2771,13 +2858,13 @@ Flushes the stream. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ------------- | -| Promise<void> | Promise used to return the stream flushing result.| + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream flushing result.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2801,13 +2888,13 @@ Flushes the stream. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | -------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | -------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2833,7 +2920,7 @@ Synchronously flushes the stream. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2853,20 +2940,20 @@ Writes data into the stream. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to write. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| **Return value** -| Type | Description | -| --------------------- | -------- | -| Promise<number> | Promise used to return the length of the data written.| + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Promise used to return the length of the data written.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2890,15 +2977,15 @@ Writes data into the stream. This API uses an asynchronous callback to return th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| -| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + | Name | Type | Mandatory| Description | + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2926,20 +3013,20 @@ Synchronously writes data into the stream. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data written in the file.| + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2959,20 +3046,20 @@ Reads data from the stream. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.| **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<number> | Promise used to return the data read.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<number> | Promise used to return the data read.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -2998,15 +3085,15 @@ Reads data from the stream. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.| -| callback | AsyncCallback<number> | Yes | Callback invoked when data is read asynchronously from the stream. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.| + | callback | AsyncCallback<number> | Yes | Callback invoked when data is read asynchronously from the stream. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3034,20 +3121,20 @@ Synchronously reads data from the stream. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.
| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.
| **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data read.| + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3079,19 +3166,19 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<void> | Promise that returns no value.| **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3114,14 +3201,14 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is locked. | + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is locked. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3146,13 +3233,13 @@ Applies an exclusive lock or a shared lock on this file in non-blocking mode. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3172,7 +3259,7 @@ Unlocks this file synchronously. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3199,7 +3286,7 @@ Starts listening. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3222,7 +3309,7 @@ Stops listening. **Error codes** -For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). **Example** @@ -3266,3 +3353,14 @@ Defines the file filtering configuration, which can be used by **listFile()**. | fileSizeOver | number | Locate files that are greater than or equal to the specified size. | | lastModifiedAfter | number | Locate files whose last modification time is the same or later than the specified time. | | excludeMedia | boolean | Whether to exclude the files already in **Media**. | + +## ConflictFiles + +**System capability**: SystemCapability.FileManagement.File.FileIO + +Defines information about the conflicting files. It is used the **copyDir()** and **moveDir()**. + +| Name | Type | Description | +| ----------- | --------------- | ------------------ | +| srcFile | string | Path of the source file. | +| destFile | string | Path of the destination file.| diff --git a/en/application-dev/reference/apis/js-apis-file-hash.md b/en/application-dev/reference/apis/js-apis-file-hash.md index eb9247ab3ccc6ee628fbd12e8a8a51413abbda01..87592b5b9f7ea94fc46dac6e72c25803d2c658d2 100644 --- a/en/application-dev/reference/apis/js-apis-file-hash.md +++ b/en/application-dev/reference/apis/js-apis-file-hash.md @@ -1,11 +1,10 @@ # @ohos.file.hash (File Hash Processing) -The **fileHash** module implements hash processing on files. +The **FileHash** module implements hash processing on files. > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -17,7 +16,7 @@ import Hash from '@ohos.file.hash'; Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows: -**Stage Model** +Stage Model ```js import UIAbility from '@ohos.app.ability.UIAbility'; @@ -30,7 +29,7 @@ export default class EntryAbility extends UIAbility { } ``` -**FA Model** +FA Model ```js import featureAbility from '@ohos.ability.featureAbility'; @@ -64,6 +63,15 @@ Calculates a hash value for a file. This API uses a promise to return the result | --------------------- | -------------------------- | | Promise<string> | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900020 | Invalid argument | +| 13900042 | Unknown error | + **Example** ```js @@ -89,9 +97,19 @@ Calculates a hash value for a file. This API uses an asynchronous callback to re | --------- | --------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the file in the application sandbox. | | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| -| callback | AsyncCallback<string> | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900020 | Invalid argument | +| 13900042 | Unknown error | **Example** + ```js let filePath = pathDir + "/test.txt"; Hash.hash(filePath, "sha256", (err, str) => { diff --git a/en/application-dev/reference/apis/js-apis-file-picker.md b/en/application-dev/reference/apis/js-apis-file-picker.md index c61b79455e006756aa65993b1b0ebdf7da9d7b70..f08294549c59a444bd8b7f3d8d72e34533c9d59b 100644 --- a/en/application-dev/reference/apis/js-apis-file-picker.md +++ b/en/application-dev/reference/apis/js-apis-file-picker.md @@ -7,6 +7,7 @@ > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import + ```js import picker from '@ohos.file.picker'; ``` diff --git a/en/application-dev/reference/apis/js-apis-file-securityLabel.md b/en/application-dev/reference/apis/js-apis-file-securityLabel.md index c564516e66c0119dbec070c4a9eab744350d130f..d0005ee159065701ec3f6e483817a095b08c65b9 100644 --- a/en/application-dev/reference/apis/js-apis-file-securityLabel.md +++ b/en/application-dev/reference/apis/js-apis-file-securityLabel.md @@ -4,8 +4,7 @@ The **securityLabel** module provides APIs for managing data security levels of > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -60,9 +59,24 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t **Return value** -| Type | Description | -| ------------------- | ---------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900001 | Operation not permitted | +| 13900007 | Arg list too long | +| 13900015 | File exists | +| 13900020 | Invalid argument | +| 13900025 | No space left on device | +| 13900037 | No data available | +| 13900041 | Quota exceeded | +| 13900042 | Unknown error | **Example** @@ -91,6 +105,21 @@ Sets a security label for a file in asynchronous mode. This API uses an asynchro | type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900001 | Operation not permitted | +| 13900007 | Arg list too long | +| 13900015 | File exists | +| 13900020 | Invalid argument | +| 13900025 | No space left on device | +| 13900037 | No data available | +| 13900041 | Quota exceeded | +| 13900042 | Unknown error | + **Example** ```js @@ -119,6 +148,21 @@ Sets a security label for a file in synchronous mode. | path | string | Yes | Path of the target file. | | type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900001 | Operation not permitted | +| 13900007 | Arg list too long | +| 13900015 | File exists | +| 13900020 | Invalid argument | +| 13900025 | No space left on device | +| 13900037 | No data available | +| 13900041 | Quota exceeded | +| 13900042 | Unknown error | + **Example** ```js @@ -136,15 +180,30 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------- | -| path | string | Yes | Path of the target file.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------- | + | path | string | Yes | Path of the target file.| **Return value** -| Type | Description | -| --------------------- | ------------ | -| Promise<string> | Security label obtained.| + | Type | Description | + | --------------------- | ------------ | + | Promise<string> | Security label obtained.| + +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900001 | Operation not permitted | +| 13900007 | Arg list too long | +| 13900015 | File exists | +| 13900020 | Invalid argument | +| 13900025 | No space left on device | +| 13900037 | No data available | +| 13900041 | Quota exceeded | +| 13900042 | Unknown error | **Example** @@ -167,10 +226,25 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------------- | -| path | string | Yes | Path of the target file. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the security label obtained.| + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | -------------------------- | + | path | string | Yes | Path of the target file. | + | callback | AsyncCallback<string> | Yes | Callback invoked to return the security label obtained.| + +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900001 | Operation not permitted | +| 13900007 | Arg list too long | +| 13900015 | File exists | +| 13900020 | Invalid argument | +| 13900025 | No space left on device | +| 13900037 | No data available | +| 13900041 | Quota exceeded | +| 13900042 | Unknown error | **Example** @@ -184,6 +258,7 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb } }); ``` + ## securityLabel.getSecurityLabelSync getSecurityLabelSync(path:string):string @@ -204,6 +279,21 @@ Obtains the security label of a file in synchronous mode. | ------ | ------------ | | string | Security label obtained.| +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +| ID| Error Message| +| -------- | -------- | +| 13900001 | Operation not permitted | +| 13900007 | Arg list too long | +| 13900015 | File exists | +| 13900020 | Invalid argument | +| 13900025 | No space left on device | +| 13900037 | No data available | +| 13900041 | Quota exceeded | +| 13900042 | Unknown error | + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-statvfs.md b/en/application-dev/reference/apis/js-apis-file-statvfs.md index b7809c5f9f10fa9904ec0f64367ff025e7aafc94..34282138f7bddeadb0b9e3e2de45dc600c65c5ff 100644 --- a/en/application-dev/reference/apis/js-apis-file-statvfs.md +++ b/en/application-dev/reference/apis/js-apis-file-statvfs.md @@ -4,14 +4,14 @@ The **statfs** module provides APIs for obtaining file system information, inclu > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```js import statvfs from '@ohos.file.statvfs'; ``` + ## statvfs.getFreeSize getFreeSize(path:string):Promise<number> @@ -32,6 +32,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo | --------------------- | -------------- | | Promise<number> | Promise used to return the number of free bytes obtained.| +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + **Example** ```js @@ -58,6 +62,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo | path | string | Yes | File path of the file system.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of free bytes obtained.| +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + **Example** ```js @@ -91,6 +99,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m | --------------------- | ------------ | | Promise<number> | Promise used to return the total number of bytes obtained.| +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + **Example** ```js @@ -117,6 +129,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m | path | string | Yes | File path of the file system.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the total number of bytes obtained. | +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-storage-statistics.md b/en/application-dev/reference/apis/js-apis-file-storage-statistics.md index 716e0da462bf4e59d0cd969deb561e0adc23a351..01ffbea245309d4d2babf3ae81ec64e998dfeb67 100644 --- a/en/application-dev/reference/apis/js-apis-file-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-file-storage-statistics.md @@ -4,8 +4,8 @@ The **storageStatistics** module provides APIs for obtaining storage space infor > **NOTE** > -> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import ```js @@ -24,7 +24,6 @@ Obtains the total size (in bytes) of the specified volume in an external storage **System API**: This is a system API. - **Parameters** | Name | Type | Mandatory| Description| @@ -37,6 +36,19 @@ Obtains the total size (in bytes) of the specified volume in an external storage | --------------------- | ---------------- | | Promise<number> | Promise used to return the total volume size obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | + **Example** ```js @@ -60,7 +72,6 @@ Obtains the total size (in bytes) of the specified volume in an external storage **System API**: This is a system API. - **Parameters** | Name | Type | Mandatory| Description | @@ -68,6 +79,19 @@ Obtains the total size (in bytes) of the specified volume in an external storage | volumeUuid | string | Yes | UUID of the volume. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the total volume size obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | + **Example** ```js @@ -90,7 +114,6 @@ Obtains the available space (in bytes) of the specified volume in an external st **System API**: This is a system API. - **Parameters** | Name | Type | Mandatory| Description| @@ -103,6 +126,19 @@ Obtains the available space (in bytes) of the specified volume in an external st | --------------------- | ------------------ | | Promise<number> | Promise used to return the available volume space obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | + **Example** ```js @@ -127,7 +163,6 @@ Obtains the available space (in bytes) of the specified volume in an external st **System API**: This is a system API. - **Parameters** | Name | Type | Mandatory| Description | @@ -135,6 +170,19 @@ Obtains the available space (in bytes) of the specified volume in an external st | volumeUuid | string | Yes | UUID of the volume. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the available volume space obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | + **Example** ```js @@ -157,7 +205,6 @@ Obtains the space (in bytes) of an application. This API uses a promise to retur **System API**: This is a system API. - **Parameters** | Name | Type | Mandatory| Description | @@ -170,6 +217,19 @@ Obtains the space (in bytes) of an application. This API uses a promise to retur | ------------------------------------------ | -------------------------- | | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the application space obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | + **Example** ```js @@ -193,7 +253,6 @@ Obtains the space (in bytes) of an application. This API uses an asynchronous ca **System API**: This is a system API. - **Parameters** | Name | Type | Mandatory| Description | @@ -201,6 +260,19 @@ Obtains the space (in bytes) of an application. This API uses an asynchronous ca | packageName | string | Yes | Bundle name of the application.| | callback | AsyncCallback<[Bundlestats](#bundlestats9)> | Yes | Callback invoked to return the application space obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | + **Example** ```js @@ -225,6 +297,16 @@ Obtains the space (in bytes) of this third-party application. This API uses a pr | ------------------------------------------ | -------------------------- | | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the application space obtained. | +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -246,6 +328,16 @@ Obtains the space (in bytes) of this third-party application. This API uses an a | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback<[BundleStats](#bundlestats9)> | Yes | Callback invoked to return the application space obtained. | +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -265,7 +357,6 @@ Obtains the space (in bytes) of this third-party application. This API uses an a | cacheSize | number | Yes| No| Cache size of the application, in bytes. | | dataSize | number | Yes| No| Total data size of the application, in bytes.| - ## storageStatistics.getTotalSize9+ getTotalSize(): Promise<number> @@ -284,6 +375,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses a promi | --------------------- | ------------------ | | Promise<number> | Promise used to return the built-in storage size obtained. | +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -309,6 +412,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn | -------- | ------------------------------------ | ---- | ------------------------ | | callback | AsyncCallback<number> | Yes | Callback invoked to return the built-in storage size obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -318,7 +433,6 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn }); ``` - ## storageStatistics.getFreeSize9+ getFreeSize(): Promise<number> @@ -337,6 +451,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses a | --------------------- | ------------------ | | Promise<number> | Promise used to return the available space of the built-in storage obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -344,7 +470,6 @@ Obtains the available space (in bytes) of the built-in storage. This API uses a console.info("getFreeSize successfully:"+ JSON.stringify(number)); ``` - ## storageStatistics.getFreeSize9+ getFreeSize(callback: AsyncCallback<number>): void @@ -363,6 +488,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses an | -------- | ------------------------------------ | ---- | ------------------------- | | callback | AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in storage obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -384,13 +521,24 @@ Obtains the system data space, in bytes. This API uses a promise to return the r **System API**: This is a system API. - **Return value** | Type | Description | | --------------------- | ---------------- | | Promise<number> | Promise used to return the system data space obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -419,6 +567,18 @@ Obtains the system data space, in bytes. This API uses an asynchronous callback | ---------- | ------------------------------------ | ---- | -------------------------- | | callback | AsyncCallback<number> | Yes | Callback invoked to return the system data space obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -446,6 +606,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses a promise | --------------------- | ---------------- | | Promise<[StorageStats](#storagestats9)> | Promise used to return the information obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -474,6 +646,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses an asynchr | ---------- | ------------------------------------ | ---- | -------------------------- | | callback | AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | + **Example** ```js @@ -482,6 +666,9 @@ Obtains the storage statistics (in bytes) of this user. This API uses an asynchr console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); }); ``` + +## storageStatistics.getUserStorageStats9+ + getUserStorageStats(userId: number): Promise<StorageStats> Obtains the storage statistics (in bytes) of the specified user. This API uses a promise to return the result. @@ -504,6 +691,19 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a | --------------------- | ---------------- | | Promise<[StorageStats](#storagestats9)> | Promise used to return the information obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600009 | User if out of range. | +| 13900032 | Unknown error. | + **Example** ```js @@ -534,6 +734,19 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a | userId | number | Yes | User ID.| | callback | AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600009 | User if out of range. | +| 13900032 | Unknown error. | + **Example** ```js @@ -544,7 +757,6 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a }); ``` - ## StorageStats9+ **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics diff --git a/en/application-dev/reference/apis/js-apis-file-volumemanager.md b/en/application-dev/reference/apis/js-apis-file-volumemanager.md index c2628ce063d93233af5ee6f6641a422e1a163c37..bec02a0f6780883260a9e152441558f58039d59b 100644 --- a/en/application-dev/reference/apis/js-apis-file-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-file-volumemanager.md @@ -6,7 +6,6 @@ The **volumeManager** module provides APIs for volume and disk management, inclu > > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs provided by this module are system APIs. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import @@ -26,9 +25,21 @@ Obtains information about all volumes of this external storage device. This API **Return value** -| Type | Description | -| ---------------------------------- | -------------------------- | -| Promise<[Volume](#volume)[]> | Promise used to return information about all available volumes.| + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)[]> | Promise used to return information about all available volumes.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | **Example** @@ -52,9 +63,21 @@ Obtains information about all volumes of this external storage device. This API **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return information about all available volumes.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------------------- | ---- | ------------------------------------ | + | callback | AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return information about all available volumes.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13900032 | Unknown error. | **Example** @@ -65,7 +88,6 @@ Obtains information about all volumes of this external storage device. This API }); ``` - ## volumemanager.mount mount(volumeId: string): Promise<void> @@ -78,15 +100,31 @@ Asynchronously mounts a volume. This API uses a promise to return the result. Cu **Parameters** -| Name | Type | Mandatory| Description| -| -------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| **Return value** -| Type | Description | -| ---------------------- | ---------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------- | ---------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600003 | Failed to mount. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -111,10 +149,26 @@ Asynchronously mounts a volume. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| volumeId | string | Yes | Volume ID. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------- | ---- | -------------------- | + | volumeId | string | Yes | Volume ID. | + | callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600003 | Failed to mount. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -137,15 +191,31 @@ Asynchronously unmounts a volume. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description| -| -------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| **Return value** -| Type | Description | -| ---------------------- | ---------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------- | ---------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600004 | Failed to unmount. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -170,10 +240,26 @@ Asynchronously unmounts a volume. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| volumeId | string | Yes | Volume ID. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------- | ---- | -------------------- | + | volumeId | string | Yes | Volume ID. | + | callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600004 | Failed to unmount. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -196,15 +282,28 @@ Obtains information about a volume based on the universally unique identifier (U **Parameters** -| Name | Type | Mandatory| Description| -| -------- | ------ | ---- | ---- | -| uuid | string | Yes | UUID of the volume.| + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| **Return value** -| Type | Description | -| ---------------------------------- | -------------------------- | -| Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -229,10 +328,23 @@ Obtains information about a volume based on the UUID. This API uses an asynchron **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | -------------------- | -| uuid | string | Yes | UUID of the volume. | -| callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------------------ | ---- | -------------------- | + | uuid | string | Yes | UUID of the volume. | + | callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -255,15 +367,28 @@ Obtains information about a volume based on the volume ID. This API uses a promi **Parameters** -| Name | Type | Mandatory | Description| -| -------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| + | Name | Type | Mandatory | Description| + | -------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| **Return value** -| Type | Description | -| ---------------------------------- | -------------------------- | -| Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -288,10 +413,23 @@ Obtains information about a volume based on the volume ID. This API uses an asyn **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| volumeId | string | Yes | Volume ID. | -| callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained. | + | Name | Type | Mandatory| Description | + | -------- | ------------------------- | ---- | ----------------------------- | + | volumeId | string | Yes | Volume ID. | + | callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained. | + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -314,16 +452,31 @@ Sets volume description. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description| -| --------- | ------ | ---- | ---- | -| uuid | string | Yes | UUID of the volume.| -| description | string | Yes | Volume description to set.| + | Name | Type | Mandatory| Description| + | --------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| + | description | string | Yes | Volume description to set.| **Return value** -| Type | Description | -| ---------------------- | -------------------------- | -| Promise<void> | Promise that returns no value. | + | Type | Description | + | ---------------------- | -------------------------- | + | Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -349,11 +502,26 @@ Sets volume description. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ---------------- | -| uuid | string | Yes | UUID of the volume. | -| description | string | Yes | Volume description to set. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + | Name | Type | Mandatory| Description | + | ---------- | --------------------------------------- | ---- | ---------------- | + | uuid | string | Yes | UUID of the volume. | + | description | string | Yes | Volume description to set. | + | callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -377,16 +545,31 @@ Formats a volume. This API uses a promise to return the result. Currently, only **Parameters** -| Name | Type | Mandatory| Description| -| ----------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| -| fsType | string | Yes | File system type, which can be VFAT or exFAT.| + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| + | fsType | string | Yes | File system type, which can be VFAT or exFAT.| **Return value** -| Type | Description | -| ---------------------- | ---------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------- | ---------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -412,11 +595,26 @@ Formats a volume. This API uses an asynchronous callback to return the result. C **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| volumeId | string | Yes | Volume ID. | -| fsType | string | Yes | File system type, which can be VFAT or exFAT.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + | Name | Type | Mandatory| Description | + | -------- | ------------------------- | ---- | ----------------------------- | + | volumeId | string | Yes | Volume ID. | + | fsType | string | Yes | File system type, which can be VFAT or exFAT.| + | callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600002 | Not supported filesystem. | +| 13600005 | Incorrect volume state. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -440,16 +638,29 @@ Partitions a disk. This API uses a promise to return the result. The system supp **Parameters** -| Name | Type | Mandatory| Description| -| ----------- | ------ | ---- | ---- | -| diskId | string | Yes | ID of the disk to partition.| -| type | number | Yes | Partition type. | + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | diskId | string | Yes | ID of the disk to partition.| + | type | number | Yes | Partition type. | **Return value** -| Type | Description | -| --------------------- | ----------------------- | -| Promise<void> | Promise used to return the result. | + | Type | Description | + | --------------------- | ----------------------- | + | Promise<void> | Promise used to return the result. | + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** @@ -475,11 +686,24 @@ Asynchronously partitions a disk. This API uses a callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ---------------- | -| diskId | string | Yes | ID of the disk to partition. | -| type | number | Yes | Partition type. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + | Name | Type | Mandatory| Description | + | -------- | --------------------------------------- | ---- | ---------------- | + | diskId | string | Yes | ID of the disk to partition. | + | type | number | Yes | Partition type. | + | callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Error codes** + +For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 401 | The input parameter is invalid. | +| 13600001 | IPC error. | +| 13600008 | No such object. | +| 13900032 | Unknown error. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-fileShare.md b/en/application-dev/reference/apis/js-apis-fileShare.md index b99d2d029bc8f9abf2d6df865a0023140e8b25c0..3908fbf3996f1d87ccc0aa51efb326241c63080e 100644 --- a/en/application-dev/reference/apis/js-apis-fileShare.md +++ b/en/application-dev/reference/apis/js-apis-fileShare.md @@ -1,6 +1,6 @@ # @ohos.fileshare (File Sharing) -The **fileShare** module provides APIs for granting the access permissions on a user file to another application by the Uniform Resource Identifier (URI). Then, the authorized application can access the file by using the APIs provided by [@ohos.file.fs](js-apis-file-fs.md). +The **fileshare** module provides APIs for granting the access permissions on a user file to another application by the Uniform Resource Identifier (URI). Then, the authorized application can access the file by using the APIs provided by [@ohos.file.fs](js-apis-file-fs.md). > **NOTE** > @@ -31,7 +31,7 @@ Grants permissions on a user file by the URI to an application. This API uses an | uri | string | Yes | URI of a user file.| | bundleName | string | Yes | Bundle name of the application to be grated with the permissions.| | mode | number | Yes | Permissions to grant. For details, see [wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags).
**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file.
**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Error codes** @@ -44,7 +44,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod | 401 | The input parameter is invalid | | 143000001 | IPC error | - **Example** ```js @@ -66,7 +65,6 @@ try { } ``` - ## fileShare.grantUriPermission grantUriPermission(uri: string, bundleName: string, mode: number): Promise<void> @@ -89,10 +87,9 @@ Grants permissions on a user file by the URI to an application. This API uses a **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| Promise<void> | Promise that returns no value.| - + | Type | Description | + | ---------------------------- | ---------- | + | Promise<void> | Promise that returns no value.| **Error codes** @@ -105,7 +102,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod | 401 | The input parameter is invalid | | 143000001 | IPC error | - **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index c798d91a2cee8c4b750201cce4deef26bcc7bc40..9f49f9bb61eda42dfc3232ac545f6d080aa3758e 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -45,7 +45,8 @@ httpRequest.request( connectTimeout: 60000 // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms. usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. - usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. + usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10. + caPath: "", // Optional. The preset CA certificate is used by default. This field is supported since API version 10. }, (err, data) => { if (!err) { // data.result carries the HTTP response. Parse the response based on service requirements. @@ -68,7 +69,7 @@ httpRequest.request( > **NOTE** > If the data in **console.info()** contains a newline character, the data will be truncated. -## http.createHttp +## http.createHttp6+ createHttp(): HttpRequest @@ -94,7 +95,7 @@ let httpRequest = http.createHttp(); Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp()](#httpcreatehttp) to create an **HttpRequestTask** object. -### request +### request6+ request(url: string, callback: AsyncCallback\):void @@ -116,14 +117,38 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback **Error codes** -| Code | Error Message | +| ID | Error Message | |---------|-------------------------------------------------------| | 401 | Parameter error. | | 201 | Permission denied. | +| 2300001 | Unsupported protocol. | | 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | | 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | | 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | | 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | | 2300999 | Unknown Other Error. | > **NOTE** @@ -145,7 +170,7 @@ httpRequest.request("EXAMPLE_URL", (err, data) => { }); ``` -### request +### request6+ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\):void @@ -168,7 +193,7 @@ Initiates an HTTP request containing specified options to a given URL. This API **Error codes** -| Code | Error Message | +| ID | Error Message | |---------|-------------------------------------------------------| | 401 | Parameter error. | | 201 | Permission denied. | @@ -231,7 +256,7 @@ httpRequest.request("EXAMPLE_URL", }); ``` -### request +### request6+ request(url: string, options? : HttpRequestOptions): Promise\ @@ -259,7 +284,7 @@ Initiates an HTTP request containing specified options to a given URL. This API **Error codes** -| Code | Error Message | +| ID | Error Message | |---------|-------------------------------------------------------| | 401 | Parameter error. | | 201 | Permission denied. | @@ -353,14 +378,38 @@ Initiates an HTTP request containing specified options to a given URL. This API **Error codes** -| Code | Error Message | +| ID | Error Message | |---------|-------------------------------------------------------| | 401 | Parameter error. | | 201 | Permission denied. | +| 2300001 | Unsupported protocol. | | 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | | 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | | 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | | 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | | 2300999 | Unknown Other Error. | > **NOTE** @@ -383,7 +432,7 @@ httpRequest.request2("EXAMPLE_URL", (err, data) => { request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void -Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. +Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. **Required permissions**: ohos.permission.INTERNET @@ -399,7 +448,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback **Error codes** -| Code | Error Message | +| ID | Error Message | |---------|-------------------------------------------------------| | 401 | Parameter error. | | 201 | Permission denied. | @@ -482,7 +531,7 @@ Initiates an HTTP request containing specified options to a given URL. This API **Error codes** -| Code | Error Message | +| ID | Error Message | |---------|-------------------------------------------------------| | 401 | Parameter error. | | 201 | Permission denied. | @@ -757,7 +806,7 @@ httpRequest.off('dataEnd'); ### on('dataProgress')10+ -on(type: 'dataProgress', callback: AsyncCallback\<{ receiveSize: number, totalSize: number }\>): void +on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void Registers an observer for events indicating progress of receiving HTTP streaming responses. @@ -802,7 +851,7 @@ Unregisters the observer for events indicating progress of receiving HTTP stream httpRequest.off('dataProgress'); ``` -## HttpRequestOptions +## HttpRequestOptions6+ Specifies the type and value range of the optional parameters in the HTTP request. @@ -819,9 +868,10 @@ Specifies the type and value range of the optional parameters in the HTTP reques | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms.
The value **0** indicates no timeout.| | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | | usingProtocol9+ | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | -| usingProxy10+ | boolean \| Object | No | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.
- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.
- If **usingProxy** is of the **object** type, the specified network proxy is used. | +| usingProxy10+ | boolean \| Object | No | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.
- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.
- If **usingProxy** is of the **object** type, the specified network proxy is used. +| caPath10+ | string | No | Path of the CA certificate. If this parameter is set, the system uses the CA certificate in the specified path. Otherwise, the system uses the preset CA certificate. | -## RequestMethod +## RequestMethod6+ Defines an HTTP request method. @@ -838,7 +888,7 @@ Defines an HTTP request method. | TRACE | "TRACE" | TRACE method. | | CONNECT | "CONNECT" | CONNECT method.| -## ResponseCode +## ResponseCode6+ Enumerates the response codes for an HTTP request. @@ -882,7 +932,7 @@ Enumerates the response codes for an HTTP request. | GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. | | VERSION | 505 | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request. | -## HttpResponse +## HttpResponse6+ Defines the response to an HTTP request. diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 17f012a1af194cfbb0ebb93dc319a5691c3b5913..f2569456cc3430e9a72189e6a6fe5b3ce06ea8a3 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -865,8 +865,8 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback | uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | method | string | Yes | Name of the API to call. | | arg | string | Yes | Parameter to pass in. | -| extras | [PacMap](js-apis-inner-application-pacMap.md) | Yes | Key-value pair parameter. | -| callback | AsyncCallback\<[PacMap](js-apis-inner-application-pacMap.md)> | Yes| Callback used to return the result. | +| extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Yes | Key-value pair parameter. | +| callback | AsyncCallback\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | Yes| Callback used to return the result. | **Example** @@ -901,13 +901,13 @@ Calls an extended API of the DataAbility. This API uses a promise to return the | uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | method | string | Yes | Name of the API to call. | | arg | string | Yes | Parameter to pass in. | -| extras | [PacMap](js-apis-inner-application-pacMap.md) | Yes | Key-value pair parameter. | +| extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Yes | Key-value pair parameter. | **Return value** | Type| Description| |------ | ------- | -|Promise\<[PacMap](js-apis-inner-application-pacMap.md)> | Promise used to return the result.| +|Promise\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | Promise used to return the result.| **Example** @@ -998,3 +998,13 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi }); ``` + +## PacMap + +[key: string]: number | string | boolean | Array\ | null; + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name| Type| Mandatory| Description| +| ------ | ------ | ------ | ------ | +| [key: string] | number \| string \| boolean \| Array\ \| null | Yes| Data stored in key-value pairs.| \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md index f8823b905ffe42199ec68fb57b052bd0af65e08e..7e6211f628986e02503c8c130614770b57656b74 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -72,6 +72,6 @@ import Want from '@ohos.app.ability.Want'; // ... ``` -- For more details and examples, see [Want](../../application-models/want-overview.md). +- For more details and examples, see [Application Model](../../application-models/application-model-composition.md). diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md index a73c80d7c5fa09e19f901b3c947f445eb61989e1..a8afc035794c4e35fbdf9d68a715fe2bb67e7b36 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md @@ -1,5 +1,10 @@ # CommonEventData +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + **System capability**: SystemCapability.Notification.CommonEvent | Name | Type | Readable| Writable| Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md index 94963860fe1b57a6abfd6fff6fdba38816a63294..332fd934c7ee9799d4356acc45996d3632b4f9d2 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventPublishData.md @@ -1,5 +1,9 @@ # CommonEventPublishData +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + **System capability**: SystemCapability.Notification.CommonEvent | Name | Type | Readable| Writable| Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md index 2b9db9ec46f479d5d0607c33f07601b1ef721446..c5de47b81e6b928a7d26909a54aa9ba798078417 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscribeInfo.md @@ -1,5 +1,9 @@ # CommonEventSubscribeInfo +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + **System capability**: SystemCapability.Notification.CommonEvent | Name | Type | Readable| Writable| Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md index 18eeac506b75dc96b27b56b9369070215ff8892a..02112d5b265e73139c9cd662246a819bc16c0b1f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md @@ -1,11 +1,40 @@ # CommonEventSubscriber -## getCode +> **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. + +## Usage + +Before using the **CommonEventSubscriber** module, you must obtain a **subscriber** object by calling **CommonEvent.createSubscriber**. ```ts -getCode(callback: AsyncCallback): void +import CommonEvent from '@ohos.commonEvent'; +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +let subscribeInfo = { + events: ["event"] +}; + +// Callback for subscriber creation. +function createCB(err, commonEventSubscriber) { + if (err.code) { + console.error(`createSubscriber failed, code is ${err.code}`); + } else { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + } +} + +// Create a subscriber. +CommonEvent.createSubscriber(subscribeInfo, createCB); ``` +## getCode + +getCode(callback: AsyncCallback\): void + Obtains the code of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -19,8 +48,6 @@ Obtains the code of this common event. This API uses an asynchronous callback to **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for result code obtaining of an ordered common event. function getCodeCB(err, code) { if (err.code) { @@ -34,9 +61,7 @@ subscriber.getCode(getCodeCB); ## getCode -```ts -getCode(): Promise -``` +getCode(): Promise\ Obtains the code of this common event. This API uses a promise to return the result. @@ -51,8 +76,6 @@ Obtains the code of this common event. This API uses a promise to return the res **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.getCode().then((code) => { console.info("getCode " + JSON.stringify(code)); }).catch((err) => { @@ -62,9 +85,7 @@ subscriber.getCode().then((code) => { ## setCode -```ts -setCode(code: number, callback: AsyncCallback): void -``` +setCode(code: number, callback: AsyncCallback\): void Sets the code for this common event. This API uses an asynchronous callback to return the result. @@ -80,8 +101,6 @@ Sets the code for this common event. This API uses an asynchronous callback to r **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for result code setting of an ordered common event. function setCodeCB(err) { if (err.code) { @@ -95,9 +114,7 @@ subscriber.setCode(1, setCodeCB); ## setCode -```ts -setCode(code: number): Promise -``` +setCode(code: number): Promise\ Sets the code for this common event. This API uses a promise to return the result. @@ -118,8 +135,6 @@ Sets the code for this common event. This API uses a promise to return the resul **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.setCode(1).then(() => { console.info("setCode"); }).catch((err) => { @@ -129,9 +144,7 @@ subscriber.setCode(1).then(() => { ## getData -```ts -getData(callback: AsyncCallback): void -``` +getData(callback: AsyncCallback\): void Obtains the data of this common event. This API uses an asynchronous callback to return the result. @@ -146,8 +159,6 @@ Obtains the data of this common event. This API uses an asynchronous callback to **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for result data obtaining of an ordered common event. function getDataCB(err, data) { if (err.code) { @@ -161,9 +172,7 @@ subscriber.getData(getDataCB); ## getData -```ts -getData(): Promise -``` +getData(): Promise\ Obtains the data of this common event. This API uses a promise to return the result. @@ -178,8 +187,6 @@ Obtains the data of this common event. This API uses a promise to return the res **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.getData().then((data) => { console.info("getData " + JSON.stringify(data)); }).catch((err) => { @@ -205,8 +212,6 @@ Sets the data for this common event. This API uses an asynchronous callback to r **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for result data setting of an ordered common event function setDataCB(err) { if (err.code) { @@ -220,9 +225,7 @@ subscriber.setData("publish_data_changed", setDataCB); ## setData -```ts -setData(data: string): Promise -``` +setData(data: string): Promise\ Sets the data for this common event. This API uses a promise to return the result. @@ -243,8 +246,6 @@ Sets the data for this common event. This API uses a promise to return the resul **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.setData("publish_data_changed").then(() => { console.info("setData"); }).catch((err) => { @@ -254,9 +255,7 @@ subscriber.setData("publish_data_changed").then(() => { ## setCodeAndData -```ts -setCodeAndData(code: number, data: string, callback:AsyncCallback): void -``` +setCodeAndData(code: number, data: string, callback:AsyncCallback\): void Sets the code and data for this common event. This API uses an asynchronous callback to return the result. @@ -273,8 +272,6 @@ Sets the code and data for this common event. This API uses an asynchronous call **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for code and data setting of an ordered common event. function setCodeDataCB(err) { if (err.code) { @@ -288,9 +285,7 @@ subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); ## setCodeAndData -```ts -setCodeAndData(code: number, data: string): Promise -``` +setCodeAndData(code: number, data: string): Promise\ Sets the code and data for this common event. This API uses a promise to return the result. @@ -312,8 +307,6 @@ Sets the code and data for this common event. This API uses a promise to return **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); }).catch((err) => { @@ -323,9 +316,7 @@ subscriber.setCodeAndData(1, "publish_data_changed").then(() => { ## isOrderedCommonEvent -```ts -isOrderedCommonEvent(callback: AsyncCallback): void -``` +isOrderedCommonEvent(callback: AsyncCallback\): void Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. @@ -340,8 +331,6 @@ Checks whether this common event is an ordered one. This API uses an asynchronou **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for checking whether the current common event is an ordered one. function isOrderedCB(err, isOrdered) { if (err.code) { @@ -355,9 +344,7 @@ subscriber.isOrderedCommonEvent(isOrderedCB); ## isOrderedCommonEvent -```ts -isOrderedCommonEvent(): Promise -``` +isOrderedCommonEvent(): Promise\ Checks whether this common event is an ordered one. This API uses a promise to return the result. @@ -372,8 +359,6 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); }).catch((err) => { @@ -383,9 +368,7 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { ## isStickyCommonEvent -```ts -isStickyCommonEvent(callback: AsyncCallback): void -``` +isStickyCommonEvent(callback: AsyncCallback\): void Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. @@ -400,8 +383,6 @@ Checks whether this common event is a sticky one. This API uses an asynchronous **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for checking whether the current common event is a sticky one. function isStickyCB(err, isSticky) { if (err.code) { @@ -415,9 +396,7 @@ subscriber.isStickyCommonEvent(isStickyCB); ## isStickyCommonEvent -```ts -isStickyCommonEvent(): Promise -``` +isStickyCommonEvent(): Promise\ Checks whether this common event is a sticky one. This API uses a promise to return the result. @@ -432,8 +411,6 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); }).catch((err) => { @@ -443,9 +420,7 @@ subscriber.isStickyCommonEvent().then((isSticky) => { ## abortCommonEvent -```ts -abortCommonEvent(callback: AsyncCallback): void -``` +abortCommonEvent(callback: AsyncCallback\): void Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -460,8 +435,6 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for common event aborting. function abortCB(err) { if (err.code) { @@ -475,9 +448,7 @@ subscriber.abortCommonEvent(abortCB); ## abortCommonEvent -```ts -abortCommonEvent(): Promise -``` +abortCommonEvent(): Promise\ Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -492,8 +463,6 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); }).catch((err) => { @@ -503,9 +472,7 @@ subscriber.abortCommonEvent().then(() => { ## clearAbortCommonEvent -```ts -clearAbortCommonEvent(callback: AsyncCallback): void -``` +clearAbortCommonEvent(callback: AsyncCallback\): void Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -520,8 +487,6 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for clearing the aborted state of the current common event. function clearAbortCB(err) { if (err.code) { @@ -535,9 +500,7 @@ subscriber.clearAbortCommonEvent(clearAbortCB); ## clearAbortCommonEvent -```ts -clearAbortCommonEvent(): Promise -``` +clearAbortCommonEvent(): Promise\ Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -552,8 +515,6 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); }).catch((err) => { @@ -563,9 +524,7 @@ subscriber.clearAbortCommonEvent().then(() => { ## getAbortCommonEvent -```ts -getAbortCommonEvent(callback: AsyncCallback): void -``` +getAbortCommonEvent(callback: AsyncCallback\): void Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -580,8 +539,6 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for checking whether the current common event is in the aborted state. function getAbortCB(err, abortEvent) { if (err.code) { @@ -595,9 +552,7 @@ subscriber.getAbortCommonEvent(getAbortCB); ## getAbortCommonEvent -```ts -getAbortCommonEvent(): Promise -``` +getAbortCommonEvent(): Promise\ Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -612,8 +567,6 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.getAbortCommonEvent().then((abortEvent) => { console.info("abortCommonEvent " + JSON.stringify(abortEvent)); }).catch((err) => { @@ -623,9 +576,7 @@ subscriber.getAbortCommonEvent().then((abortEvent) => { ## getSubscribeInfo -```ts -getSubscribeInfo(callback: AsyncCallback): void -``` +getSubscribeInfo(callback: AsyncCallback\): void Obtains the subscriber information. This API uses an asynchronous callback to return the result. @@ -640,8 +591,6 @@ Obtains the subscriber information. This API uses an asynchronous callback to re **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for subscriber information obtaining. function getCB(err, subscribeInfo) { if (err.code) { @@ -655,9 +604,7 @@ subscriber.getSubscribeInfo(getCB); ## getSubscribeInfo -```ts -getSubscribeInfo(): Promise -``` +getSubscribeInfo(): Promise\ Obtains the subscriber information. This API uses a promise to return the result. @@ -672,8 +619,6 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.getSubscribeInfo().then((subscribeInfo) => { console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); }).catch((err) => { @@ -683,9 +628,7 @@ subscriber.getSubscribeInfo().then((subscribeInfo) => { ## finishCommonEvent9+ -```ts -finishCommonEvent(callback: AsyncCallback): void -``` +finishCommonEvent(callback: AsyncCallback\): void Finishes this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -700,14 +643,13 @@ Finishes this common event. This API takes effect only for ordered common events **Example** ```ts -let subscriber; // Subscriber object successfully created. - // Callback for ordered common event finishing. function finishCB(err) { if (err.code) { console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); -} else { + } else { console.info("FinishCommonEvent"); + } } subscriber.finishCommonEvent(finishCB); @@ -715,9 +657,7 @@ subscriber.finishCommonEvent(finishCB); ## finishCommonEvent9+ -```ts -finishCommonEvent(): Promise -``` +finishCommonEvent(): Promise\ Finishes this common event. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -732,8 +672,6 @@ Finishes this common event. This API takes effect only for ordered common events **Example** ```ts -let subscriber; // Subscriber object successfully created. - subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); }).catch((err) => { diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md index 88e58e4bea766398e24ae1870c061e0dc385953a..ee7f0e37c7d85cdfdde76ae9b852bb05964af358 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationActionButton.md @@ -8,9 +8,9 @@ The **NotificationActionButton** module describes the button displayed in the no **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | --------- | ----------------------------------------------- | --- | ---- | ------------------------- | -| title | string | Yes | Yes | Button title. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** of the button.| -| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | -| userInput8+ | [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) | Yes | Yes | User input object. | +| title | string | No | Yes | Button title. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | Yes | **WantAgent** of the button.| +| extras | { [key: string]: any } | No | No | Extra information of the button. | +| userInput8+ | [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) | No | No | User input object. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md index dcd2a4ce8de27431ea343b27bb933d829fcad74c..48f8c4cc28912aab4b3cc0446c951fe539b6ba4e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationCommonDef.md @@ -10,7 +10,7 @@ Provides the bundle information of an application. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Mandatory| Description | -| ------ | ------ |---- | ------ | -| bundle | string | Yes| Bundle information of the application.| -| uid | number | No| User ID.| +| Name | Type | Read-only| Mandatory| Description | +| ------ | ------ | ---- | ---- | ------ | +| bundle | string | No | Yes| Bundle information of the application.| +| uid | number | No | No| User ID.| diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md index 7c2b3a78da9b2c22c7ae9967552655f6e70a6c8c..9f5de8d911f2533c0dd789fd3bce1eeaf1adeef6 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationContent.md @@ -8,13 +8,13 @@ The **NotificationContent** module describes the notification content. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | -| contentType | [ContentType](./js-apis-notificationManager.md#contenttype) | Yes | Yes | Notification content type. | -| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | -| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| -| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | -| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | +| contentType | [ContentType](./js-apis-notificationManager.md#contenttype) | No | Yes | Notification content type. | +| normal | [NotificationBasicContent](#notificationbasiccontent) | No | No | Normal text. | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | No | No | Long text.| +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | No | No | Multi-line text. | +| picture | [NotificationPictureContent](#notificationpicturecontent) | No | No | Picture-attached. | ## NotificationBasicContent @@ -22,11 +22,11 @@ Describes the normal text notification. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | -------------- | ------ | ---- | ---- | ---------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| +| title | string | No | Yes | Notification title. | +| text | string | No | Yes | Notification content. | +| additionalText | string | No | No | Additional information of the notification.| ## NotificationLongTextContent @@ -35,14 +35,14 @@ Describes the long text notification. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | -------------- | ------ | ---- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| longText | string | Yes | Yes | Long text of the notification. | -| briefText | string | Yes | Yes | Brief text of the notification.| -| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| title | string | No | Yes | Notification title. | +| text | string | No | Yes | Notification content. | +| additionalText | string | No | No | Additional information of the notification.| +| longText | string | No | Yes | Long text of the notification. | +| briefText | string | No | Yes | Brief text of the notification. | +| expandedTitle | string | No | Yes | Title of the notification in the expanded state. | ## NotificationMultiLineContent @@ -53,12 +53,12 @@ Describes the multi-line text notification. | Name | Type | Readable| Writable| Description | | -------------- | --------------- | --- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| briefText | string | Yes | Yes | Brief text of the notification.| -| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | -| lines | Array\ | Yes | Yes | Multi-line text of the notification. | +| title | string | No | Yes | Notification title. | +| text | string | No | Yes | Notification content. | +| additionalText | string | No | No | Additional information of the notification.| +| briefText | string | No | Yes | Brief text of the notification.| +| longTitle | string | No | Yes | Title of the notification in the expanded state. | +| lines | Array\ | No | Yes | Multi-line text of the notification. | ## NotificationPictureContent @@ -69,9 +69,9 @@ Describes the picture-attached notification. | Name | Type | Readable| Writable| Description | | -------------- | -------------- | ---- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| briefText | string | Yes | Yes | Brief text of the notification.| -| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | -| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Picture attached to the notification. | +| title | string | No | Yes | Notification title. | +| text | string | No | Yes | Notification content. | +| additionalText | string | No | No | Additional information of the notification.| +| briefText | string | No | Yes | Brief text of the notification.| +| expandedTitle | string | No | Yes | Title of the notification in the expanded state. | +| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | No | Yes | Picture attached to the notification. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md index f7e1a995b51bcc193e2cd21115eb8e934233eec5..e0b84a9fbac8e59070b598960bdb447c9cc24dbe 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationFlags.md @@ -8,7 +8,7 @@ The **NotificationFlags** module implements a **NotificationFlags** instance. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | ---------------- | ---------------------- | ---- | ---- | --------------------------------- | | soundEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable the sound alert for the notification. | | vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable vibration for the notification. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md index 205a6c04bdf7fff97c80e44b882fb487712e2c01..ac3646f424f7701e2fa85c671a76ba90c511d212 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md @@ -8,45 +8,45 @@ The **NotificationRequest** module describes the notification request. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | -| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | Yes | Yes | Notification content. | -| id | number | Yes | Yes | Notification ID. | -| slotType | [SlotType](js-apis-notificationManager.md#slottype) | Yes | Yes | Notification slot type. | -| isOngoing | boolean | Yes | Yes | Whether the notification is an ongoing notification. | -| isUnremovable | boolean | Yes | Yes | Whether the notification can be removed. | -| deliveryTime | number | Yes | Yes | Time when the notification is sent. | -| tapDismissed | boolean | Yes | Yes | Whether the notification is automatically cleared. | -| autoDeletedTime | number | Yes | Yes | Time when the notification is automatically cleared. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected after being clicked.| -| extraInfo | {[key: string]: any} | Yes | Yes | Extended parameters. | -| color | number | Yes | Yes | Background color of the notification. Not supported currently.| -| colorEnabled | boolean | Yes | Yes | Whether the notification background color can be enabled. Not supported currently.| -| isAlertOnce | boolean | Yes | Yes | Whether the notification triggers an alert only once.| -| isStopwatch | boolean | Yes | Yes | Whether to display the stopwatch. | -| isCountDown | boolean | Yes | Yes | Whether to display the countdown time. | -| isFloatingIcon | boolean | Yes | Yes | Whether the notification is displayed as a floating icon in the status bar. | -| label | string | Yes | Yes | Notification label. | -| badgeIconStyle | number | Yes | Yes | Notification badge type. | -| showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | -| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | Yes | Yes | Buttons in the notification. Up to three buttons are allowed. | -| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| -| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | No | Yes | Notification content. | +| id | number | No | No | Notification ID. | +| slotType | [SlotType](js-apis-notificationManager.md#slottype) | Yes | No | Notification slot type. | +| isOngoing | boolean | No | No | Whether the notification is an ongoing notification. | +| isUnremovable | boolean | No | No | Whether the notification can be removed. | +| deliveryTime | number | No | No | Time when the notification is sent. | +| tapDismissed | boolean | No | No | Whether the notification is automatically cleared. | +| autoDeletedTime | number | No | No | Time when the notification is automatically cleared. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | No | **WantAgent** instance to which the notification will be redirected after being clicked.| +| extraInfo | {[key: string]: any} | No | No | Extended parameters. | +| color | number | No | No | Background color of the notification. Not supported currently.| +| colorEnabled | boolean | No | No | Whether the notification background color can be enabled. Not supported currently.| +| isAlertOnce | boolean | No | No | Whether the notification triggers an alert only once.| +| isStopwatch | boolean | No | No | Whether to display the stopwatch. | +| isCountDown | boolean | No | No | Whether to display the countdown time. | +| isFloatingIcon | boolean | No | No | Whether the notification is displayed as a floating icon in the status bar. | +| label | string | No | No | Notification label. | +| badgeIconStyle | number | No | No | Notification badge type. Not supported currently. | +| showDeliveryTime | boolean | No | No | Whether to display the time when the notification is delivered. | +| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | No | No | Buttons in the notification. Up to three buttons are allowed. | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | No | No | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | No | No | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| | creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | | creatorUid8+ | number | Yes | No | UID used for creating the notification. | | creatorPid | number | Yes | No | PID used for creating the notification. | -| creatorUserId| number | Yes | No | ID of the user who creates the notification. | +| creatorUserId | number | Yes | No | ID of the user who creates the notification. | | hashCode | string | Yes | No | Unique ID of the notification. | -| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | -| groupName8+ | string | Yes | Yes | Notification group name. | -| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | Yes | Yes | Notification template. | +| classification | string | No | No | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName8+ | string | No | No | Notification group name. | +| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | No | No | Notification template. | | isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | | source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| distributedOption8+ | [DistributedOptions](#distributedoptions) | Yes | Yes | Distributed notification options. | +| distributedOption8+ | [DistributedOptions](#distributedoptions) | No | No | Distributed notification options. | | deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationflags#notificationFlags) | Yes | No | Notification flags. | -| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected when it is removed. | -| badgeNumber9+ | number | Yes | Yes | Number of notifications displayed on the application icon. | +| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationFlags.md#notificationflags) | Yes | No | Notification flags. | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | No | No | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | number | No | No | Number of notifications displayed on the application icon. | ## DistributedOptions @@ -55,9 +55,9 @@ Describes distributed notification options. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | ---------------------- | -------------- | ---- | ---- | ---------------------------------- | -| isDistributed8+ | boolean | Yes | Yes | Whether the notification is a distributed notification. | -| supportDisplayDevices8+ | Array\ | Yes | Yes | List of the devices to which the notification can be synchronized. | -| supportOperateDevices8+ | Array\ | Yes | Yes | List of the devices on which the notification can be opened. | +| isDistributed8+ | boolean | No | No | Whether the notification is a distributed notification. | +| supportDisplayDevices8+ | Array\ | No | No | List of the devices to which the notification can be synchronized. | +| supportOperateDevices8+ | Array\ | No | No | List of the devices on which the notification can be opened. | | remindType8+ | number | Yes | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md index 8bf9e286d59504be03ff8454d59ce60c31a9a597..9757ef2c007501439c509adc691e8f57aa3b354c 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSlot.md @@ -8,17 +8,17 @@ The **NotificationSlot** module describes the notification slot. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | -------------------- | --------------------- | ---- | --- | ------------------------------------------ | -| type | [SlotType](js-apis-notificationManager.md#slottype) | Yes | Yes | Notification slot type. | -| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value that corresponds to the notification slot type is used.| -| desc | string | Yes | Yes | Notification slot description. | -| badgeFlag | boolean | Yes | Yes | Whether to display the badge. | -| bypassDnd | boolean | Yes | Yes | Whether to bypass DND mode in the system. | -| lockscreenVisibility | number | Yes | Yes | Mode for displaying the notification on the lock screen. | -| vibrationEnabled | boolean | Yes | Yes | Whether to enable vibration for the notification. | -| sound | string | Yes | Yes | Notification alert tone. | -| lightEnabled | boolean | Yes | Yes | Whether the indicator blinks for the notification. | -| lightColor | number | Yes | Yes | Indicator color of the notification. | -| vibrationValues | Array\ | Yes | Yes | Vibration mode of the notification. | +| type | [SlotType](js-apis-notificationManager.md#slottype) | No | Yes | Notification slot type. | +| level | number | No | No | Notification level. If this parameter is not set, the default value that corresponds to the notification slot type is used.| +| desc | string | No | No | Notification slot description. | +| badgeFlag | boolean | No | No | Whether to display the badge. | +| bypassDnd | boolean | No | No | Whether to bypass DND mode in the system. | +| lockscreenVisibility | number | No | No | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | boolean | No | No | Whether to enable vibration for the notification. | +| sound | string | No | No | Notification alert tone. | +| lightEnabled | boolean | No | No | Whether the indicator blinks for the notification. | +| lightColor | number | No | No | Indicator color of the notification. | +| vibrationValues | Array\ | No | No | Vibration mode of the notification. | | enabled9+ | boolean | Yes | No | Whether the notification slot is enabled. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md new file mode 100644 index 0000000000000000000000000000000000000000..8062a16f3ac0305025130bcd73f91bd41ba6abdf --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md @@ -0,0 +1,17 @@ +# NotificationSorting + +Provides sorting information of active notifications. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Read-only| Mandatory| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | Yes | Yes | Notification slot type. | +| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | string | Yes | Yes | Description of the notification slot. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSortingMap.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSortingMap.md new file mode 100644 index 0000000000000000000000000000000000000000..0e75e98d2ce00b55aefc7d640f6590332782b451 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSortingMap.md @@ -0,0 +1,17 @@ +# NotificationSortingMap + +Provides sorting information of active notifications in all subscribed notifications. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Read-only| Mandatory| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| sortings | { [key: string]: [NotificationSorting](js-apis-inner-notification-notificationSorting.md) } | Yes | Yes | Array of notification sorting information.| +| sortedHashCode | Array\ | Yes | Yes | Hash codes for notification sorting.| + diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSubscribeInfo.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSubscribeInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..8bd477d99c99ba3cc5f494b12fb83c993b0ca682 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSubscribeInfo.md @@ -0,0 +1,16 @@ +# NotificationSubscribeInfo + +Provides the information about the publisher for notification subscription. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Read-only| Mandatory| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| bundleNames | Array\ | No | No | Bundle names of the applications whose notifications are to be subscribed to. | +| userId | number | No | No | User ID. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSubscriber.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSubscriber.md new file mode 100644 index 0000000000000000000000000000000000000000..cd23687ebc1da6055172deede38ab03b62e68c0c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSubscriber.md @@ -0,0 +1,402 @@ +# NotificationSubscriber + +Provides callbacks for receiving or removing notifications and serves as the input parameter of [subscribe](js-apis-notificationSubscribe.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import notificationSubscribe from '@ohos.notificationSubscribe'; +``` + +**System API**: This is a system API and cannot be called by third-party applications. + +### onConsume + +onConsume?: (data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void + +Called when a new notification is received. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | Yes| Information about the notification received.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onConsumeCallback(data) { + console.info('===> onConsume in test'); + let req = data.request; + console.info('===> onConsume callback req.id:' + req.id); +}; + +let subscriber = { + onConsume: onConsumeCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onCancel + +onCancel?:(data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void + +Called when a notification is canceled. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | Yes| Information about the notification to cancel.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onCancelCallback(data) { + console.info('===> onCancel in test'); + let req = data.request; + console.info('===> onCancel callback req.id:' + req.id); +} + +let subscriber = { + onCancel: onCancelCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onUpdate + +onUpdate?:(data: [NotificationSortingMap](js-apis-notification.md#notificationsortingmap)) => void + +Called when notification sorting is updated. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [NotificationSortingMap](js-apis-notification.md#notificationsortingmap) | Yes| Latest notification sorting list.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onUpdateCallback(map) { + console.info('===> onUpdateCallback map:' + JSON.stringify(map)); +} + +let subscriber = { + onUpdate: onUpdateCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onConnect + +onConnect?:() => void + +Called when the subscription is complete. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onConnectCallback() { + console.info('===> onConnect in test'); +} + +let subscriber = { + onConnect: onConnectCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onDisconnect + +onDisconnect?:() => void + +Called when unsubscription is complete. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; +function unsubscribeCallback(err) { + if (err.code) { + console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("unsubscribeCallback"); + } +}; + +function onConnectCallback() { + console.info('===> onConnect in test'); +} +function onDisconnectCallback() { + console.info('===> onDisconnect in test'); +} + +let subscriber = { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback +}; + +// The onConnect callback is invoked when subscription to the notification is complete. +notificationSubscribe.subscribe(subscriber, subscribeCallback); +// The onDisconnect callback is invoked when unsubscription to the notification is complete. +notificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); +``` + +### onDestroy + +onDestroy?:() => void + +Called when the service is disconnected. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onDestroyCallback() { + console.info('===> onDestroy in test'); +} + +let subscriber = { + onDestroy: onDestroyCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onDoNotDisturbDateChange8+ + +onDoNotDisturbDateChange?:(mode: notification.[DoNotDisturbDate](js-apis-notificationManager.md#donotdisturbdate)) => void + +Called when the DND time settings are changed. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| mode | notification.[DoNotDisturbDate](js-apis-notificationManager.md#DoNotDisturbDate) | Yes| DND time setting updates.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onDoNotDisturbDateChangeCallback(mode) { + console.info('===> onDoNotDisturbDateChange:' + mode); +} + +let subscriber = { + onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + + +### onEnabledNotificationChanged8+ + +onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata8)) => void + +Listens for the notification enabled status changes. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\<[EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata8)\> | Yes| Callback used to return the result.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onEnabledNotificationChangedCallback(callbackData) { + console.info("bundle: ", callbackData.bundle); + console.info("uid: ", callbackData.uid); + console.info("enable: ", callbackData.enable); +}; + +let subscriber = { + onEnabledNotificationChanged: onEnabledNotificationChangedCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onBadgeChanged10+ + + onBadgeChanged?:(data: [BadgeNumberCallbackData](#badgenumbercallbackdata10)) => void + +Listens for the change of the notification badge number. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\<[BadgeNumberCallbackData](#badgenumbercallbackdata10)\> | Yes | Callback used to return the result.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onBadgeChangedCallback(data) { + console.info("bundle: ", data.bundle); + console.info("uid: ", data.uid); + console.info("badgeNumber: ", data.badgeNumber); +}; + +let subscriber = { + onBadgeChanged: onBadgeChangedCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +## SubscribeCallbackData + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Read-only| Mandatory| Description | +| --------------- | ------------------------------------------------- | ---- | --- | -------- | +| request | [NotificationRequest](js-apis-inner-notification-notificationRequest#notificationrequest) | Yes | Yes | Notification content.| +| sortingMap | [NotificationSortingMap](js-apis-inner-notification-notificationSortingMap.md) | Yes | No | Notification sorting information.| +| reason | number | Yes | No | Reason for deletion.| +| sound | string | Yes | No | Sound used for notification.| +| vibrationValues | Array\ | Yes | No | Vibration used for notification.| + + +## EnabledNotificationCallbackData8+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Read-only| Mandatory| Description | +| ------ | ------- | ---- | --- | ---------------- | +| bundle | string | Yes | Yes | Bundle name of the application. | +| uid | number | Yes | Yes | UID of the application. | +| enable | boolean | Yes | Yes | Notification enabled status of the application.| + + +## BadgeNumberCallbackData10+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Read-only| Mandatory| Description | +| ----------- | ------ | ---- | ---- | ------------ | +| bundle | string | Yes | Yes | Bundle name of the application.| +| uid | number | Yes | Yes | UID of the application. | +| badgeNumber | number | Yes | Yes | Number of notifications displayed on the application icon. | diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md index 557fad664de00eb37567cb2d055c0c0ec2f8d484..3f9825e1d8cf63848d70e2282498e0d85f37cab0 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationTemplate.md @@ -8,7 +8,7 @@ The **NotificationTemplate** module describes the notification template. **System capability**: SystemCapability.Notification.Notification -| Name| Type | Readable| Writable| Description | +| Name| Type | Read-only| Mandatory| Description | | ---- | ---------------------- | ---- | ---- | ---------- | -| name | string | Yes | Yes | Template name.| -| data | {[key:string]: Object} | Yes | Yes | Template data.| +| name | string | No | Yes | Template name.| +| data | {[key:string]: Object} | No | Yes | Template data.| diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md index 76e673c886d4208354b680501c6ddbb0000e6438..bfda17b7872a816c4eb05a3af9fc5c10098f0a90 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationUserInput.md @@ -8,6 +8,6 @@ The **NotificationUserInput** module provides the notification user input. **System capability**: SystemCapability.Notification.Notification -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | -------- | ------ | --- | ---- | ----------------------------- | -| inputKey | string | Yes | Yes | Key to identify the user input.| +| inputKey | string | No | Yes | Key to identify the user input.| diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index fc1fe9ef77b77ef0eaae619f5c0f630b39a6bb40..146996b85330695f1f3a9392a62fff3136e8387e 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -122,6 +122,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700036 | Failed to install the HSP because lacks appropriate permissions. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 17700041 | Failed to install because enterprise device management disallow install. | +| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. | +| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). | +| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. | +| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. | **Example** @@ -185,6 +189,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700036 | Failed to install the HSP because lacks appropriate permissions. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 17700041 | Failed to install because enterprise device management disallow install. | +| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. | +| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). | +| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. | +| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. | **Example** @@ -226,7 +234,7 @@ Installs a bundle. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | hapFilePaths | Array\ | Yes | Paths where the HAP files of the bundle are stored, which are the data directories. If only one directory is passed, the HAP files in the directory must belong to the same bundle and have the same signature.| -| installParam | [InstallParam](#installparam) | No | Parameters required for the installation. | +| installParam | [InstallParam](#installparam) | No | Parameters required for the installation. For details about their default values, see [InstallParam](#installparam). | **Return value** @@ -252,6 +260,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700036 | Failed to install the HSP because lacks appropriate permissions. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 17700041 | Failed to install because enterprise device management disallow install. | +| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. | +| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). | +| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. | +| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. | **Example** @@ -310,6 +322,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700004 | The specified user ID is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | +| 17700045 | Failed to uninstall because enterprise device management disallow uninstall. | **Example** @@ -367,6 +380,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700001 | The specified bundle name is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | +| 17700045 | Failed to uninstall because enterprise device management disallow uninstall. | **Example** @@ -407,7 +421,7 @@ Uninstalls a bundle. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | bundleName | string | Yes | Name of the target bundle. | -| installParam | [InstallParam](#installparam) | No | Parameters required for the uninstall. | +| installParam | [InstallParam](#installparam) | No | Parameters required for the uninstall. For details about their default values, see [InstallParam](#installparam). | **Return value** @@ -422,9 +436,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17700001 | The specified bundle name is not found. | -| 17700004 | The specified userId is not existed. | +| 17700004 | The specified user ID is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | +| 17700045 | Failed to uninstall because enterprise device management disallow uninstall. | **Example** ```ts @@ -577,7 +592,7 @@ Rolls back a bundle to the initial installation state. This API uses a promise t | Name | Type | Mandatory| Description | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | bundleName | string | Yes | Name of the target bundle. | -| installParam | [InstallParam](#installparam) | No | Parameters required for the recovery. | +| installParam | [InstallParam](#installparam) | No | Parameters required for the recovery. For details about their default values, see [InstallParam](#installparam). | **Return value** @@ -755,12 +770,12 @@ Defines the parameters that need to be specified for bundle installation, uninst | Name | Type | Mandatory | Description | | ------------------------------ | ------------------------------ | ------------------ | ------------------ | -| userId | number | No | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId) to obtain the user of the current process.| -| installFlag | number | No | Installation flag. The value **0** means initial installation and **1** means overwrite installation.| -| isKeepData | boolean | No | Whether to retain the data directory during bundle uninstall.| -| hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. | -| crowdtestDeadline| number | No |End date of crowdtesting.| -| sharedBundleDirPaths10+ | Array\ | No|Paths of the shared bundle files.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. You can call [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId) to obtain the user ID of the current process.| +| installFlag | number | No | Installation flag. The value **0** means initial installation and **1** means overwrite installation. The default value is **0**.| +| isKeepData | boolean | No | Whether to retain the data directory during bundle uninstall. The default value is **false**.| +| hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. By default, no value is passed. | +| crowdtestDeadline| number | No |End date of crowdtesting. The default value is **-1**.| +| sharedBundleDirPaths10+ | Array\ | No|Paths of the shared bundle files. By default, no value is passed.| ## UninstallParam10+ @@ -773,4 +788,4 @@ Defines the parameters required for the uninstallation of a shared bundle. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | | bundleName | string | Yes | Name of the shared bundle. | -| versionCode | number | No | Version number of the shared bundle. If this parameter is not set, all shared bundles of the specified name are uninstalled.| +| versionCode | number | No | Version number of the shared bundle. By default, no value is passed, and all shared bundles of the specified name are uninstalled.| diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 813d7c830bc37076654863fb7d8d17b1f039d14c..34705e77e7d0b1e4f2705faf4ae78e0526aad25c 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -11,7 +11,7 @@ The network connection management module provides basic network management capab import connection from '@ohos.net.connection' ``` -## connection.createNetConnection +## connection.createNetConnection8+ createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection @@ -46,7 +46,7 @@ let netConnectionCellular = connection.createNetConnection({ }) ``` -## connection.getDefaultNet +## connection.getDefaultNet8+ getDefaultNet(callback: AsyncCallback\): void @@ -79,7 +79,7 @@ connection.getDefaultNet(function (error, data) { }) ``` -## connection.getDefaultNet +## connection.getDefaultNet8+ getDefaultNet(): Promise\ @@ -444,7 +444,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -## connection.getAllNets +## connection.getAllNets8+ getAllNets(callback: AsyncCallback<Array<NetHandle>>): void @@ -477,7 +477,7 @@ connection.getAllNets(function (error, data) { }); ``` -## connection.getAllNets +## connection.getAllNets8+ getAllNets(): Promise<Array<NetHandle>> @@ -509,7 +509,7 @@ connection.getAllNets().then(function (data) { }); ``` -## connection.getConnectionProperties +## connection.getConnectionProperties8+ getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void @@ -547,7 +547,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -## connection.getConnectionProperties +## connection.getConnectionProperties8+ getConnectionProperties(netHandle: NetHandle): Promise\ @@ -589,7 +589,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -## connection.getNetCapabilities +## connection.getNetCapabilities8+ getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): void @@ -627,7 +627,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -## connection.getNetCapabilities +## connection.getNetCapabilities8+ getNetCapabilities(netHandle: NetHandle): Promise\ @@ -734,7 +734,7 @@ connection.isDefaultNetMetered().then(function (data) { }) ``` -## connection.hasDefaultNet +## connection.hasDefaultNet8+ hasDefaultNet(callback: AsyncCallback\): void @@ -767,7 +767,7 @@ connection.hasDefaultNet(function (error, data) { }) ``` -## connection.hasDefaultNet +## connection.hasDefaultNet8+ hasDefaultNet(): Promise\ @@ -799,7 +799,7 @@ connection.hasDefaultNet().then(function (data) { }) ``` -## connection.enableAirplaneMode +## connection.enableAirplaneMode8+ enableAirplaneMode(callback: AsyncCallback\): void @@ -821,6 +821,7 @@ Enables the airplane mode. This API uses an asynchronous callback to return the | ID| Error Message | | ------- | ----------------------------- | +| 202 | Non-system applications use system APIs.| | 2100002 | Operation failed. Cannot connect to service.| | 2100003 | System internal error. | @@ -832,7 +833,7 @@ connection.enableAirplaneMode(function (error) { }) ``` -## connection.enableAirplaneMode +## connection.enableAirplaneMode8+ enableAirplaneMode(): Promise\ @@ -854,6 +855,7 @@ Enables the airplane mode. This API uses a promise to return the result. | ID| Error Message | | ------- | ----------------------------- | +| 202 | Non-system applications use system APIs.| | 2100002 | Operation failed. Cannot connect to service.| | 2100003 | System internal error. | @@ -865,7 +867,7 @@ connection.enableAirplaneMode().then(function (error) { }) ``` -## connection.disableAirplaneMode +## connection.disableAirplaneMode8+ disableAirplaneMode(callback: AsyncCallback\): void @@ -887,6 +889,7 @@ Disables the airplane mode. This API uses an asynchronous callback to return the | ID| Error Message | | ------- | ----------------------------- | +| 202 | Non-system applications use system APIs.| | 2100002 | Operation failed. Cannot connect to service.| | 2100003 | System internal error. | @@ -898,7 +901,7 @@ connection.disableAirplaneMode(function (error) { }) ``` -## connection.disableAirplaneMode +## connection.disableAirplaneMode8+ disableAirplaneMode(): Promise\ @@ -920,6 +923,7 @@ Disables the airplane mode. This API uses a promise to return the result. | ID| Error Message | | ------- | ----------------------------- | +| 202 | Non-system applications use system APIs.| | 2100002 | Operation failed. Cannot connect to service.| | 2100003 | System internal error. | @@ -931,7 +935,7 @@ connection.disableAirplaneMode().then(function (error) { }) ``` -## connection.reportNetConnected +## connection.reportNetConnected8+ reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void @@ -968,7 +972,7 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` -## connection.reportNetConnected +## connection.reportNetConnected8+ reportNetConnected(netHandle: NetHandle): Promise<void> @@ -1009,7 +1013,7 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` -## connection.reportNetDisconnected +## connection.reportNetDisconnected8+ reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void @@ -1046,7 +1050,7 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` -## connection.reportNetDisconnected +## connection.reportNetDisconnected8+ reportNetDisconnected(netHandle: NetHandle): Promise<void> @@ -1087,7 +1091,7 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` -## connection.getAddressesByName +## connection.getAddressesByName8+ getAddressesByName(host: string, callback: AsyncCallback\>): void @@ -1124,7 +1128,7 @@ connection.getAddressesByName(host, function (error, data) { }) ``` -## connection.getAddressesByName +## connection.getAddressesByName8+ getAddressesByName(host: string): Promise\> @@ -1174,7 +1178,7 @@ Represents the network connection handle. > When a device changes to the network disconnected state, the **netLost** event will be triggered. > When a device switches from a Wi-Fi network to a cellular network, the **netLost** event will be first triggered to indicate that the Wi-Fi network is lost and then the **netAvaliable** event will be triggered to indicate that the cellular network is available. -### register +### register8+ register(callback: AsyncCallback\): void @@ -1195,9 +1199,10 @@ Registers a listener for network status changes. | ID| Error Message | | ------- | ----------------------------- | | 201 | Permission denied. | +| 401 | Parameter error. | | 2100002 | Operation failed. Cannot connect to service.| | 2100003 | System internal error. | -| 2101008 | The callback is not exists. | +| 2101008 | The same callback exists. | | 2101022 | The number of requests exceeded the maximum. | **Example** @@ -1208,7 +1213,7 @@ netConnection.register(function (error) { }) ``` -### unregister +### unregister8+ unregister(callback: AsyncCallback\): void @@ -1226,9 +1231,11 @@ Unregisters the listener for network status changes. | ID| Error Message | | ------- | ----------------------------- | +| 201 | Permission denied.| +| 401 | Parameter error. | | 2100002 | Operation failed. Cannot connect to service.| | 2100003 | System internal error. | -| 2101007 | The same callback exists. | +| 2101007 | The callback is not exists. | **Example** @@ -1238,7 +1245,7 @@ netConnection.unregister(function (error) { }) ``` -### on('netAvailable') +### on('netAvailable')8+ on(type: 'netAvailable', callback: Callback\): void @@ -1277,7 +1284,7 @@ netCon.unregister(function (error) { }) ``` -### on('netBlockStatusChange') +### on('netBlockStatusChange')8+ on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void @@ -1316,7 +1323,7 @@ netCon.unregister(function (error) { }) ``` -### on('netCapabilitiesChange') +### on('netCapabilitiesChange')8+ on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void @@ -1355,7 +1362,7 @@ netCon.unregister(function (error) { }) ``` -### on('netConnectionPropertiesChange') +### on('netConnectionPropertiesChange')8+ on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void @@ -1395,7 +1402,7 @@ netCon.unregister(function (error) { }) ``` -### on('netLost') +### on('netLost')8+ on(type: 'netLost', callback: Callback\): void @@ -1434,7 +1441,7 @@ netCon.unregister(function (error) { }) ``` -### on('netUnavailable') +### on('netUnavailable')8+ on(type: 'netUnavailable', callback: Callback\): void @@ -1473,7 +1480,7 @@ netCon.unregister(function (error) { }) ``` -## NetHandle +## NetHandle8+ Defines the handle of the data network. @@ -1640,7 +1647,7 @@ connection.getDefaultNet().then((netHandle) => { }) ``` -### getAddressesByName +### getAddressesByName8+ getAddressesByName(host: string, callback: AsyncCallback\>): void @@ -1679,7 +1686,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -### getAddressesByName +### getAddressesByName8+ getAddressesByName(host: string): Promise\> @@ -1722,7 +1729,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -### getAddressByName +### getAddressByName8+ getAddressByName(host: string, callback: AsyncCallback\): void @@ -1761,7 +1768,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -### getAddressByName +### getAddressByName8+ getAddressByName(host: string): Promise\ @@ -1804,7 +1811,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -## NetCap +## NetCap8+ Defines the network capability. @@ -1818,7 +1825,7 @@ Defines the network capability. | NET_CAPABILITY_NOT_VPN | 15 | The network does not use a virtual private network (VPN).| | NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the connection management module.| -## NetBearType +## NetBearType8+ Enumerates network types. @@ -1842,7 +1849,7 @@ Defines the global HTTP proxy configuration of the network. | port | number | No | Host port.| | exclusionList | Array | No | Exclusion list of hosts that do not use the proxy server. The length of the combined elements in the list cannot exceed 96 bytes.
For example, the length of **baidu.com,zhihu.com** is 20 bytes.| -## NetSpecifier +## NetSpecifier8+ Provides an instance that bears data network capabilities. @@ -1853,7 +1860,7 @@ Provides an instance that bears data network capabilities. | netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | | bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| -## NetCapabilities +## NetCapabilities8+ Defines the network capability set. @@ -1866,7 +1873,7 @@ Defines the network capability set. | networkCap | Array\<[NetCap](#netcap)> | No| Network capability. | | bearerTypes | Array\<[NetBearType](#netbeartype)> | Yes| Network type. | -## ConnectionProperties +## ConnectionProperties8+ Defines the network connection properties. @@ -1881,7 +1888,7 @@ Defines the network connection properties. | dnses | Array\<[NetAddress](#netaddress)> | Yes|Network address. For details, see [NetAddress](#netaddress).| | mtu | number | Yes|Maximum transmission unit (MTU). | -## RouteInfo +## RouteInfo8+ Defines network route information. @@ -1895,7 +1902,7 @@ Defines network route information. | hasGateway | boolean | Yes|Whether a gateway is present. | | isDefaultRoute | boolean | Yes|Whether the route is the default route.| -## LinkAddress +## LinkAddress8+ Defines network link information. @@ -1906,7 +1913,7 @@ Defines network link information. | address | [NetAddress](#netaddress) | Yes| Link address. | | prefixLength | number | Yes|Length of the link address prefix.| -## NetAddress +## NetAddress8+ Defines a network address. diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index 3a04cbb3a501fd64d8315b5c929beaf6c2407355..ec15531de49c13ab4b2c85b0da9eacf37400d195 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -11,7 +11,7 @@ The **ethernet** module provides wired network capabilities, which allow users t import ethernet from '@ohos.net.ethernet' ``` -## ethernet.setIfaceConfig +## ethernet.setIfaceConfig9+ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void @@ -36,13 +36,15 @@ Sets the network interface configuration. This API uses an asynchronous callback | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | -| 2201005 | The device information does not exist. | -| 2201006 | Device disconnected. | -| 2201007 | Failed to write the user configuration. | +| 2201004 | Invalid Ethernet profile. | +| 2201005 | Device information does not exist. | +| 2201006 | Ethernet device not connected. | +| 2201007 | Ethernet failed to write user configuration information. | **Example** @@ -64,7 +66,7 @@ ethernet.setIfaceConfig("eth0", { }); ``` -## ethernet.setIfaceConfig +## ethernet.setIfaceConfig9+ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ @@ -94,13 +96,15 @@ Sets the network interface configuration. This API uses a promise to return the | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | -| 2201005 | The device information does not exist. | -| 2201006 | Device disconnected. | -| 2201007 | Failed to write the user configuration. | +| 2201004 | Invalid Ethernet profile. | +| 2201005 | Device information does not exist. | +| 2201006 | Ethernet device not connected. | +| 2201007 | Ethernet failed to write user configuration information. | **Example** @@ -120,7 +124,7 @@ ethernet.setIfaceConfig("eth0", { }); ``` -## ethernet.getIfaceConfig +## ethernet.getIfaceConfig9+ getIfaceConfig(iface: string, callback: AsyncCallback\): void @@ -144,11 +148,12 @@ Obtains the configuration of a network interface. This API uses an asynchronous | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | -| 2201005 | The device information does not exist. | +| 2201005 | Device information does not exist. | **Example** @@ -168,7 +173,7 @@ ethernet.getIfaceConfig("eth0", (error, value) => { }); ``` -## ethernet.getIfaceConfig +## ethernet.getIfaceConfig9+ getIfaceConfig(iface: string): Promise\ @@ -197,11 +202,12 @@ Obtains the configuration of a network interface. This API uses a promise to ret | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | -| 2201005 | The device information does not exist. | +| 2201005 | Device information does not exist. | **Example** @@ -219,7 +225,7 @@ ethernet.getIfaceConfig("eth0").then((data) => { }); ``` -## ethernet.isIfaceActive +## ethernet.isIfaceActive9+ isIfaceActive(iface: string, callback: AsyncCallback\): void @@ -243,11 +249,12 @@ Checks whether a network interface is active. This API uses an asynchronous call | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | -| 2201005 | The device information does not exist. | +| 2201005 | Device information does not exist. | **Example** @@ -261,7 +268,7 @@ ethernet.isIfaceActive("eth0", (error, value) => { }); ``` -## ethernet.isIfaceActive +## ethernet.isIfaceActive9+ isIfaceActive(iface: string): Promise\ @@ -290,11 +297,12 @@ Checks whether a network interface is active. This API uses a promise to return | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | -| 2201005 | The device information does not exist. | +| 2201005 | Device information does not exist. | **Example** @@ -306,7 +314,7 @@ ethernet.isIfaceActive("eth0").then((data) => { }); ``` -## ethernet.getAllActiveIfaces +## ethernet.getAllActiveIfaces9+ getAllActiveIfaces(callback: AsyncCallback\>): void @@ -329,6 +337,7 @@ Obtains the list of all active network interfaces. This API uses an asynchronous | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | @@ -347,7 +356,7 @@ ethernet.getAllActiveIfaces((error, value) => { }); ``` -## ethernet.getAllActiveIfaces +## ethernet.getAllActiveIfaces9+ getAllActiveIfaces(): Promise\> @@ -370,6 +379,7 @@ Obtains the list of all active network interfaces. This API uses a promise to re | ID| Error Message | | ------- | ----------------------------------------| | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 2200002 | Operation failed. Cannot connect to service.| | 2200003 | System internal error. | @@ -403,21 +413,19 @@ Registers an observer for NIC hot swap events. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event type. The value is **interfaceStateChange**.| -| callback | Callback\<{ iface: string, active: boolean }\> | Yes | Callback used to return the result.
**iface**: NIC name.
**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.| +| callback | AsyncCallback\<{ iface: string, active: boolean }\> | Yes | Callback used to return the result.
**iface**: NIC name.
**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.| **Error codes** | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 202 | Applicable only to system applications. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** ```js -ethernet.on('interfaceStateChange', (data) => { - console.log('on interfaceSharingStateChange: ' + JSON.stringify(data.iface) + JSON.stringify(data.active)); + ethernet.on('interfaceStateChange', (data) => { + console.log('on interfaceSharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -438,15 +446,13 @@ Unregisters the observer for NIC hot swap events. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event type. The value is **interfaceStateChange**.| -| callback | Callback\<{ iface: string, active: boolean }> | No | Callback used to return the result.
**iface**: NIC name.
**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.| +| callback | AsyncCallback\<{ iface: string, active: boolean }> | No | Callback used to return the result.
**iface**: NIC name.
**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.| **Error codes** | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 202 | Applicable only to system applications. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** @@ -454,7 +460,7 @@ Unregisters the observer for NIC hot swap events. This API uses an asynchronous ethernet.off('interfaceStateChange'); ``` -## InterfaceConfiguration +## InterfaceConfiguration9+ Defines the network configuration for the Ethernet connection. @@ -471,7 +477,7 @@ Defines the network configuration for the Ethernet connection. | netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| | dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| -## IPSetMode +## IPSetMode9+ Defines the configuration mode of the Ethernet connection. diff --git a/en/application-dev/reference/apis/js-apis-net-mdns.md b/en/application-dev/reference/apis/js-apis-net-mdns.md index 2190dbe59ceca1336096944b8203826263c5294e..c84b3ae6dce748f686f50f001fa18fd13b78049d 100644 --- a/en/application-dev/reference/apis/js-apis-net-mdns.md +++ b/en/application-dev/reference/apis/js-apis-net-mdns.md @@ -11,7 +11,7 @@ Multicast DNS (mDNS) provides functions such as adding, removing, discovering, a import mdns from '@ohos.net.mdns' ``` -## mdns.addLocalService +## mdns.addLocalService10+ addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\): void @@ -100,7 +100,7 @@ mdns.addLocalService(context, localServiceInfo, function (error, data) { }); ``` -## mdns.addLocalService +## mdns.addLocalService10+ addLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\ @@ -192,7 +192,7 @@ mdns.addLocalService(context, localServiceInfo).then(function (data) { }); ``` -## mdns.removeLocalService +## mdns.removeLocalService10+ removeLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\): void @@ -216,7 +216,7 @@ Removes an mDNS service. This API uses an asynchronous callback to return the re | 2100002 | Operation failed. Cannot connect to service. | | 2100003 | System internal error. | | 2204002 | Callback not found. | -| 2204008 | Service instance duplicated. | +| 2204008 | Service instance not found. | | 2204010 | Send packet failed. | > **NOTE** @@ -281,7 +281,7 @@ mdns.removeLocalService(context, localServiceInfo, function (error, data) { }); ``` -## mdns.removeLocalService +## mdns.removeLocalService10+ removeLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\ @@ -310,7 +310,7 @@ Removes an mDNS service. This API uses a promise to return the result. | 2100002 | Operation failed. Cannot connect to service. | | 2100003 | System internal error. | | 2204002 | Callback not found. | -| 2204008 | Service instance duplicated. | +| 2204008 | Service instance not found. | | 2204010 | Send packet failed. | > **NOTE** @@ -373,7 +373,7 @@ mdns.removeLocalService(context, localServiceInfo).then(function (data) { }); ``` -## mdns.createDiscoveryService +## mdns.createDiscoveryService10+ createDiscoveryService(context: Context, serviceType: string): DiscoveryService @@ -423,7 +423,7 @@ let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); ``` -## mdns.resolveLocalService +## mdns.resolveLocalService10+ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\): void @@ -512,7 +512,7 @@ mdns.resolveLocalService(context, localServiceInfo, function (error, data) { }); ``` -## mdns.resolveLocalService +## mdns.resolveLocalService10+ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\ @@ -603,11 +603,11 @@ mdns.resolveLocalService(context, localServiceInfo).then(function (data) { console.log(JSON.stringify(data)); }); ``` -## DiscoveryService +## DiscoveryService10+ Defines a **DiscoveryService** object for discovering mDNS services of the specified type. -### startSearchingMDNS +### startSearchingMDNS10+ startSearchingMDNS(): void @@ -644,7 +644,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); ``` -### stopSearchingMDNS +### stopSearchingMDNS10+ stopSearchingMDNS(): void @@ -681,7 +681,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.stopSearchingMDNS(); ``` -### on('discoveryStart') +### on('discoveryStart')10+ on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void @@ -710,7 +710,7 @@ discoveryService.on('discoveryStart', (data) => { discoveryService.stopSearchingMDNS(); ``` -### on('discoveryStop') +### on('discoveryStop')10+ on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void @@ -739,7 +739,7 @@ discoveryService.on('discoveryStop', (data) => { discoveryService.stopSearchingMDNS(); ``` -### on('serviceFound') +### on('serviceFound')10+ on(type: 'serviceFound', callback: Callback\): void @@ -768,7 +768,7 @@ discoveryService.on('serviceFound', (data) => { discoveryService.stopSearchingMDNS(); ``` -### on('serviceLost') +### on('serviceLost')10+ on(type: 'serviceLost', callback: Callback\): void @@ -797,7 +797,7 @@ discoveryService.on('serviceLost', (data) => { discoveryService.stopSearchingMDNS(); ``` -## LocalServiceInfo +## LocalServiceInfo10+ Defines the mDNS service information. @@ -811,7 +811,7 @@ Defines the mDNS service information. | host | [NetAddress](js-apis-net-connection.md#netaddress) | No| IP address of the device that provides the mDNS service. The IP address is not effective when an mDNS service is added or removed. | | serviceAttribute | serviceAttribute\<[ServiceAttribute](#serviceattribute)> | No| mDNS service attribute information. | -## ServiceAttribute +## ServiceAttribute10+ Defines the mDNS service attribute information. diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index 0cda70aa2939c0da8f5aec7875d75bb48d309120..49796b225c56a3ff08a1ae51e986d4860b3edb77 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -12,7 +12,7 @@ The **sharing** module allows you to share your device's Internet connection wit import sharing from '@ohos.net.sharing' ``` -## sharing.isSharingSupported +## sharing.isSharingSupported9+ isSharingSupported(callback: AsyncCallback\): void @@ -48,7 +48,7 @@ sharing.isSharingSupported((error, data) => { }); ``` -## sharing.isSharingSupported +## sharing.isSharingSupported9+ isSharingSupported(): Promise\ @@ -85,7 +85,7 @@ sharing.isSharingSupported().then(data => { }); ``` -## sharing.isSharing +## sharing.isSharing9+ isSharing(callback: AsyncCallback\): void @@ -108,8 +108,10 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal | ID| Error Message | | ------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 2200002 | Operation failed. Cannot connect to service. | | 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | **Example** @@ -120,7 +122,7 @@ sharing.isSharing((error, data) => { }); ``` -## sharing.isSharing +## sharing.isSharing9+ isSharing(): Promise\ @@ -143,8 +145,10 @@ Checks whether network sharing is in progress. This API uses a promise to return | ID| Error Message | | ------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 2200002 | Operation failed. Cannot connect to service. | | 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | **Example** @@ -156,7 +160,7 @@ sharing.isSharing().then(data => { }); ``` -## sharing.startSharing +## sharing.startSharing9+ startSharing(type: SharingIfaceType, callback: AsyncCallback\): void @@ -201,7 +205,7 @@ sharing.startSharing(SHARING_WIFI, (error) => { }); ``` -## sharing.startSharing +## sharing.startSharing9+ startSharing(type: SharingIfaceType): Promise\ @@ -253,7 +257,7 @@ sharing.startSharing(SHARING_WIFI).then(() => { }); ``` -## sharing.stopSharing +## sharing.stopSharing9+ stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void @@ -277,10 +281,12 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac | ID| Error Message | | ------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service. | | 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | | 2202005 | WiFi sharing failed. | | 2202006 | Bluetooth sharing failed. | | 2202011 | Cannot get network sharing configuration. | @@ -296,7 +302,7 @@ sharing.stopSharing(SHARING_WIFI, (error) => { }); ``` -## sharing.stopSharing +## sharing.stopSharing9+ stopSharing(type: SharingIfaceType): Promise\ @@ -325,10 +331,12 @@ Stops network sharing of a specified type. This API uses a promise to return the | ID| Error Message | | ------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 2200001 | Invalid parameter value. | | 2200002 | Operation failed. Cannot connect to service. | | 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | | 2202005 | WiFi sharing failed. | | 2202006 | Bluetooth sharing failed. | | 2202011 | Cannot get network sharing configuration. | @@ -346,7 +354,7 @@ sharing.stopSharing(SHARING_WIFI).then(() => { }); ``` -## sharing.getStatsRxBytes +## sharing.getStatsRxBytes9+ getStatsRxBytes(callback: AsyncCallback\): void @@ -381,7 +389,7 @@ sharing.getStatsRxBytes((error, data) => { }); ``` -## sharing.getStatsRxBytes +## sharing.getStatsRxBytes9+ getStatsRxBytes(): Promise\ @@ -417,7 +425,7 @@ sharing.getStatsRxBytes().then(data => { }); ``` -## sharing.getStatsTxBytes +## sharing.getStatsTxBytes9+ getStatsTxBytes(callback: AsyncCallback\): void @@ -452,7 +460,7 @@ sharing.getStatsTxBytes((error, data) => { }); ``` -## sharing.getStatsTxBytes +## sharing.getStatsTxBytes9+ getStatsTxBytes(): Promise\ @@ -488,7 +496,7 @@ sharing.getStatsTxBytes().then(data => { }); ``` -## sharing.getStatsTotalBytes +## sharing.getStatsTotalBytes9+ getStatsTotalBytes(callback: AsyncCallback\): void @@ -523,7 +531,7 @@ sharing.getStatsTotalBytes((error, data) => { }); ``` -## sharing.getStatsTotalBytes +## sharing.getStatsTotalBytes9+ getStatsTotalBytes(): Promise\ @@ -559,7 +567,7 @@ sharing.getStatsTotalBytes().then(data => { }); ``` -## sharing.getSharingIfaces +## sharing.getSharingIfaces9+ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\>): void @@ -600,7 +608,7 @@ sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { }); ``` -## sharing.getSharingIfaces +## sharing.getSharingIfaces9+ getSharingIfaces(state: SharingIfaceState): Promise\> @@ -647,7 +655,7 @@ sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { }); ``` -## sharing.getSharingState +## sharing.getSharingState9+ getSharingState(type: SharingIfaceType, callback: AsyncCallback\): void @@ -688,7 +696,7 @@ sharing.getSharingState(SHARING_WIFI, (error, data) => { }); ``` -## sharing.getSharingState +## sharing.getSharingState9+ getSharingState(type: SharingIfaceType): Promise\ @@ -735,7 +743,7 @@ sharing.getSharingState(SHARING_WIFI).then(data => { }); ``` -## sharing.getSharableRegexes +## sharing.getSharableRegexes9+ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\>): void @@ -776,7 +784,7 @@ sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { }); ``` -## sharing.getSharableRegexes +## sharing.getSharableRegexes9+ getSharableRegexes(type: SharingIfaceType): Promise\> @@ -823,7 +831,7 @@ sharing.getSharableRegexes(SHARING_WIFI).then(data => { }); ``` -## sharing.on('sharingStateChange') +## sharing.on('sharingStateChange')9+ on(type: 'sharingStateChange', callback: Callback\): void @@ -846,8 +854,7 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** @@ -857,7 +864,7 @@ sharing.on('sharingStateChange', (data) => { }); ``` -## sharing.off('sharingStateChange') +## sharing.off('sharingStateChange')9+ off(type: 'sharingStateChange', callback?: Callback\): void @@ -880,8 +887,7 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** @@ -891,7 +897,7 @@ sharing.off('sharingStateChange', (data) => { }); ``` -## sharing.on('interfaceSharingStateChange') +## sharing.on('interfaceSharingStateChange')9+ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void @@ -915,8 +921,7 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** @@ -926,7 +931,7 @@ sharing.on('interfaceSharingStateChange', (data) => { }); ``` -## sharing.off('interfaceSharingStateChange') +## sharing.off('interfaceSharingStateChange')9+ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void @@ -950,8 +955,7 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** @@ -961,7 +965,7 @@ sharing.off('interfaceSharingStateChange', (data) => { }); ``` -## sharing.on('sharingUpstreamChange') +## sharing.on('sharingUpstreamChange')9+ on(type: 'sharingUpstreamChange', callback: Callback\): void @@ -984,8 +988,7 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** @@ -995,7 +998,7 @@ sharing.on('sharingUpstreamChange', (data) => { }); ``` -## sharing.off('sharingUpstreamChange') +## sharing.off('sharingUpstreamChange')9+ off(type: 'sharingUpstreamChange', callback?: Callback\): void @@ -1018,8 +1021,7 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba | ID| Error Message | | ------- | -------------------------------------------- | -| 201 | Permission denied. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | **Example** @@ -1029,7 +1031,7 @@ sharing.off('sharingUpstreamChange', (data) => { }); ``` -## SharingIfaceState +## SharingIfaceState9+ Enumerates the network sharing states of an NIC. @@ -1043,7 +1045,7 @@ Enumerates the network sharing states of an NIC. | SHARING_NIC_CAN_SERVER | 2 | Network sharing is supported.| | SHARING_NIC_ERROR | 3 | An error occurred during network sharing.| -## SharingIfaceType +## SharingIfaceType9+ Enumerates the network sharing types of an NIC. diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 1075dd58f8f78bd7597903806a51d0c6ca5c2955..f7f5b2b9362ed875d776c645be7d596de2755bfd 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -767,7 +767,7 @@ Defines the **TagInfo** object, which provides information about the tag technol | uid9+ | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| | technology9+ | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.| | supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [technology](#taginfo).| -| extrasData9+ | [PacMap](js-apis-inner-application-pacMap.md)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| | tagRfDiscId9+ | number | Yes| No| ID allocated when the tag is discovered.
**System API**: This is a system API.| | remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.
**System API**: This is a system API.| diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index b0ad704b1848025f7b049f9c0cda6d12f2175554..646f07fc4d30ec6ad4585eacd840a99954b34973 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -566,7 +566,7 @@ Notification.getSlot(slotType).then((data) => { ## Notification.getSlots -getSlots(callback: AsyncCallback>): void +getSlots(callback: AsyncCallback\>): void Obtains all notification slots. This API uses an asynchronous callback to return the result. @@ -576,7 +576,7 @@ Obtains all notification slots. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | Callback used to return the result.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Example** @@ -726,7 +726,7 @@ Subscribes to a notification with the subscription information specified. This A | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ---------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| subscriber | [NotificationSubscriber](js-apis-inner-notification-notificationSubscriber.md#notificationsubscriber) | Yes | Notification subscriber. | | info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Notification subscription information.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -769,7 +769,7 @@ Subscribes to notifications of all applications under this user. This API uses a | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | ---------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| subscriber | [NotificationSubscriber](js-apis-inner-notification-notificationSubscriber.md#notificationsubscriber) | Yes | Notification subscriber. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -807,7 +807,7 @@ Subscribes to a notification with the subscription information specified. This A | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ------------ | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| subscriber | [NotificationSubscriber](js-apis-inner-notification-notificationSubscriber.md#notificationsubscriber) | Yes | Notification subscriber.| | info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Notification subscription information. | **Example** @@ -840,7 +840,7 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | -------------------- | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| subscriber | [NotificationSubscriber](js-apis-inner-notification-notificationSubscriber.md#notificationsubscriber) | Yes | Notification subscriber. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -878,7 +878,7 @@ Unsubscribes from a notification. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | ------------ | -| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| subscriber | [NotificationSubscriber](js-apis-inner-notification-notificationSubscriber.md#notificationsubscriber) | Yes | Notification subscriber.| **Example** @@ -910,7 +910,7 @@ Sets whether to enable notification for a specified application. This API uses a | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -946,7 +946,7 @@ Sets whether to enable notification for a specified application. This API uses a | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| | enable | boolean | Yes | Whether to enable notification. | **Example** @@ -976,7 +976,7 @@ Checks whether notification is enabled for a specified application. This API use | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1011,7 +1011,7 @@ Checks whether notification is enabled for a specified application. This API use | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| **Return value** @@ -1078,7 +1078,7 @@ Checks whether notification is enabled for this application. This API uses a pro | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| **Return value** @@ -1110,7 +1110,7 @@ Sets whether to enable the notification badge for a specified application. This | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1146,7 +1146,7 @@ Sets whether to enable the notification badge for a specified application. This | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| | enable | boolean | Yes | Whether to enable notification. | **Example** @@ -1176,7 +1176,7 @@ Checks whether the notification badge is enabled for a specified application. Th | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1211,7 +1211,7 @@ Checks whether the notification badge is enabled for a specified application. Th | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| **Return value** @@ -1246,7 +1246,7 @@ Sets the notification slot for a specified application. This API uses an asynchr | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | slot | [NotificationSlot](#notificationslot) | Yes | Notification slot. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1285,7 +1285,7 @@ Sets the notification slot for a specified application. This API uses a promise | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| | slot | [NotificationSlot](#notificationslot) | Yes | Notification slot.| **Example** @@ -1304,7 +1304,7 @@ Notification.setSlotByBundle(bundle, notificationSlot).then(() => { ## Notification.getSlotsByBundle -getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void +getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback\>): void Obtains the notification slots of a specified application. This API uses an asynchronous callback to return the result. @@ -1318,8 +1318,8 @@ Obtains the notification slots of a specified application. This API uses an asyn | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Example** @@ -1339,7 +1339,7 @@ Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); ## Notification.getSlotsByBundle -getSlotsByBundle(bundle: BundleOption): Promise> +getSlotsByBundle(bundle: BundleOption): Promise\> Obtains the notification slots of a specified application. This API uses a promise to return the result. @@ -1353,13 +1353,13 @@ Obtains the notification slots of a specified application. This API uses a promi | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| **Return value** | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** @@ -1388,7 +1388,7 @@ Obtains the number of notification slots of a specified application. This API us | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1423,7 +1423,7 @@ Obtains the number of notification slots of a specified application. This API us | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| **Return value** @@ -1458,9 +1458,9 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | --------------- | ----------------------------------| ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | +| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1500,9 +1500,9 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | --------------- | --------------- | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| -| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| +| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](#onconsume) callback.| -| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | +| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback. | +| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| -| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | +| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -1601,7 +1601,7 @@ Removes all notifications for a specified application. This API uses an asynchro | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1668,7 +1668,7 @@ Removes all notifications for a specified application. This API uses a promise t | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | No | Bundle information of the application.| +| bundle | [BundleOption](#bundleoptiondeprecated) | No | Bundle information of the application.| **Example** @@ -1743,7 +1743,7 @@ Notification.removeAll(userId).then(() => { ## Notification.getAllActiveNotifications -getAllActiveNotifications(callback: AsyncCallback>): void +getAllActiveNotifications(callback: AsyncCallback\>): void Obtains all active notifications. This API uses an asynchronous callback to return the result. @@ -1757,7 +1757,7 @@ Obtains all active notifications. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Example** @@ -1775,7 +1775,7 @@ Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); ## Notification.getAllActiveNotifications -getAllActiveNotifications(): Promise\\> +getAllActiveNotifications(): Promise\> Obtains all active notifications. This API uses a promise to return the result. @@ -1789,7 +1789,7 @@ Obtains all active notifications. This API uses a promise to return the result. | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** @@ -1969,7 +1969,7 @@ Removes notifications under a notification group of a specified application. Thi | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | groupName | string | Yes | Name of the notification group. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2006,7 +2006,7 @@ Removes notifications under a notification group of a specified application. Thi | Name | Type | Mandatory| Description | | --------- | ------------ | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | groupName | string | Yes | Name of the notification group.| **Example** @@ -2035,7 +2035,7 @@ Sets the DND time. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------- | -| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| date | [DoNotDisturbDate](#donotdisturbdate8-deprecated) | Yes | DND time to set. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2074,7 +2074,7 @@ Sets the DND time. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ---------------- | ---- | -------------- | -| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| +| date | [DoNotDisturbDate](#donotdisturbdate8-deprecated) | Yes | DND time to set.| **Example** @@ -2106,7 +2106,7 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------- | -| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| date | [DoNotDisturbDate](#donotdisturbdate8-deprecated) | Yes | DND time to set. | | userId | number | Yes | ID of the user for whom you want to set the DND time.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2147,7 +2147,7 @@ Sets the DND time for a specified user. This API uses a promise to return the re | Name | Type | Mandatory| Description | | ------ | ---------------- | ---- | -------------- | -| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| +| date | [DoNotDisturbDate](#donotdisturbdate8-deprecated) | Yes | DND time to set.| | userId | number | Yes | ID of the user for whom you want to set the DND time.| **Example** @@ -2183,7 +2183,7 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ---------------------- | -| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8-deprecated)\> | Yes | Callback used to return the result.| **Example** @@ -2215,7 +2215,7 @@ Obtains the DND time. This API uses a promise to return the result. | Type | Description | | ------------------------------------------------- | ----------------------------------------- | -| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| +| Promise\<[DoNotDisturbDate](#donotdisturbdate8-deprecated)\> | Promise used to return the result.| **Example** @@ -2242,7 +2242,7 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ---------------------- | -| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8-deprecated)\> | Yes | Callback used to return the result.| | userId | number | Yes | User ID.| **Example** @@ -2283,7 +2283,7 @@ Obtains the DND time of a specified user. This API uses a promise to return the | Type | Description | | ------------------------------------------------- | ----------------------------------------- | -| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| +| Promise\<[DoNotDisturbDate](#donotdisturbdate8-deprecated)\> | Promise used to return the result.| **Example** @@ -2589,7 +2589,7 @@ Sets whether a specified application supports distributed notifications. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether the device supports distributed notifications. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2629,7 +2629,7 @@ Sets whether a specified application supports distributed notifications. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Application bundle. | | enable | boolean | Yes | Whether the device supports distributed notifications. | **Example** @@ -2661,7 +2661,7 @@ Obtains whether an application supports distributed notifications based on the b | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Application bundle. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2698,7 +2698,7 @@ Checks whether a specified application supports distributed notifications. This | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Application bundle. | **Return value** @@ -2735,7 +2735,7 @@ Obtains the notification reminder type. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | -------------------------- | -| callback | AsyncCallback\<[DeviceRemindType](#deviceremindtype8)\> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[DeviceRemindType](#deviceremindtype8-deprecated)\> | Yes | Callback used to return the result.| **Example** @@ -2767,7 +2767,7 @@ Obtains the notification reminder type. This API uses a promise to return the re | Type | Description | | ------------------ | --------------- | -| Promise\<[DeviceRemindType](#deviceremindtype8)\> | Promise used to return the result.| +| Promise\<[DeviceRemindType](#deviceremindtype8-deprecated)\> | Promise used to return the result.| **Example** @@ -2777,1033 +2777,255 @@ Notification.getDeviceRemindType().then((data) => { }); ``` - -## Notification.publishAsBundle9+ - -publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number, callback: AsyncCallback\): void - -Publishes an agent-powered notification. This API uses an asynchronous callback to return the result. +## SubscribeCallbackData **System capability**: SystemCapability.Notification.Notification -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER - **System API**: This is a system API and cannot be called by third-party applications. -**Parameters** +| Name | Type | Readable| Writable| Description | +| --------------- | ------------------------------------------------- | ---- | --- | -------- | +| request | [NotificationRequest](#notificationrequest) | Yes | No | Notification content.| +| sortingMap | [NotificationSortingMap](#notificationsortingmap) | Yes | No | Notification sorting information.| +| reason | number | Yes | No | Reason for deletion.| +| sound | string | Yes | No | Sound used for notification.| +| vibrationValues | Array\ | Yes | No | Vibration used for notification.| -| Name | Type | Mandatory| Description | -| -------------------- | ------------------------------------------- | ---- | ---------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| -| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | -| userId | number | Yes | User ID. | -| callback | AsyncCallback | Yes | Callback used to return the result. | -**Example** +## EnabledNotificationCallbackData8+ -```js -// publishAsBundle callback -function callback(err) { - if (err.code) { - console.info("publishAsBundle failed " + JSON.stringify(err)); - } else { - console.info("publishAsBundle success"); - } -} -// Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; -// User ID -let userId = 100; -// NotificationRequest object -let request = { - id: 1, - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "test_title", - text: "test_text", - additionalText: "test_additionalText" - } - } -}; +**System capability**: SystemCapability.Notification.Notification -Notification.publishAsBundle(request, representativeBundle, userId, callback); -``` +**System API**: This is a system API and cannot be called by third-party applications. -## Notification.publishAsBundle9+ +| Name | Type | Readable| Writable| Description | +| ------ | ------- | ---- | --- | ---------------- | +| bundle | string | Yes | No | Bundle name of the application. | +| uid | number | Yes | No | UID of the application. | +| enable | boolean | Yes | No | Notification enabled status of the application.| -publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number): Promise\ -Publishes a notification through the reminder agent. This API uses a promise to return the result. +## DoNotDisturbDate8+ deprecated **System capability**: SystemCapability.Notification.Notification -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [notificationManager.DoNotDisturbDate](js-apis-notificationManager.md#donotdisturbdate) instead. **System API**: This is a system API and cannot be called by third-party applications. -**Parameters** - +| Name | Type | Readable| Writable| Description | +| ----- | -------------------------------------- | ---- | ---- | ---------------------- | +| type | [DoNotDisturbType](#donotdisturbtype8-deprecated) | Yes | Yes | DND time type.| +| begin | Date | Yes | Yes | DND start time.| +| end | Date | Yes | Yes | DND end time.| -| Name | Type | Mandatory| Description | -| -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| -| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | -| userId | number | Yes | User ID. | +## DoNotDisturbType8+ deprecated -**Example** +**System capability**: SystemCapability.Notification.Notification -```js -// Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; -// User ID -let userId = 100; -// NotificationRequest object -let request = { - id: 1, - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "test_title", - text: "test_text", - additionalText: "test_additionalText" - } - } -}; +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [notificationManager.DoNotDisturbType](js-apis-notificationManager.md#donotdisturbtype) instead. -Notification.publishAsBundle(request, representativeBundle, userId).then(() => { - console.info("publishAsBundle success"); -}); -``` +**System API**: This is a system API and cannot be called by third-party applications. -## Notification.cancelAsBundle9+ +| Name | Value | Description | +| ------------ | ---------------- | ------------------------------------------ | +| TYPE_NONE | 0 | Non-DND. | +| TYPE_ONCE | 1 | One-shot DND at the specified time segment (only considering the hour and minute).| +| TYPE_DAILY | 2 | Daily DND at the specified time segment (only considering the hour and minute).| +| TYPE_CLEARLY | 3 | DND at the specified time segment (considering the year, month, day, hour, and minute). | -cancelAsBundle(id: number, representativeBundle: string, userId: number, callback: AsyncCallback\): void -Cancels a notification published by the reminder agent. This API uses an asynchronous callback to return the result. +## ContentType **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| NOTIFICATION_CONTENT_BASIC_TEXT | NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification. | +| NOTIFICATION_CONTENT_LONG_TEXT | NOTIFICATION_CONTENT_LONG_TEXT | Long text notification. | +| NOTIFICATION_CONTENT_PICTURE | NOTIFICATION_CONTENT_PICTURE | Picture-attached notification. | +| NOTIFICATION_CONTENT_CONVERSATION | NOTIFICATION_CONTENT_CONVERSATION | Conversation notification. | +| NOTIFICATION_CONTENT_MULTILINE | NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| -**System API**: This is a system API and cannot be called by third-party applications. +## SlotLevel -**Parameters** +**System capability**: SystemCapability.Notification.Notification -| Name | Type | Mandatory| Description | -| -------------------- | ------------- | ---- | ------------------------ | -| id | number | Yes | Notification ID. | -| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | -| userId | number | Yes | User ID. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| LEVEL_NONE | 0 | The notification function is disabled. | +| LEVEL_MIN | 1 | The notification function is enabled, but the notification icon is not displayed in the status bar, with no banner or alert tone.| +| LEVEL_LOW | 2 | The notification function is enabled, and the notification icon is displayed in the status bar, with no banner or alert tone.| +| LEVEL_DEFAULT | 3 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone but no banner.| +| LEVEL_HIGH | 4 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone and banner.| -**Example** -```js -// cancelAsBundle -function cancelAsBundleCallback(err) { - if (err.code) { - console.info("cancelAsBundle failed " + JSON.stringify(err)); - } else { - console.info("cancelAsBundle success"); - } -} -// Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; -// User ID -let userId = 100; +## BundleOptiondeprecated -Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); -``` +**System capability**: SystemCapability.Notification.Notification -## Notification.cancelAsBundle9+ +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) instead. -cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise\ +| Name | Type | Read-only| Mandatory| Description | +| ------ | ------ |---- | --- | ------ | +| bundle | string | No | Yes | Bundle information of the application.| +| uid | number | No | No | User ID.| -Cancels a notification published by the reminder agent. This API uses a promise to return the result. +## NotificationKeydeprecated **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER - -**System API**: This is a system API and cannot be called by third-party applications. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.NotificationKey](js-apis-notificationSubscribe.md#notificationkey) instead. -**Parameters** +| Name | Type | Readable| Writable| Description | +| ----- | ------ | ---- | --- | -------- | +| id | number | Yes | Yes | Notification ID. | +| label | string | Yes | Yes | Notification label.| -| Name | Type | Mandatory| Description | -| -------------------- | ------ | ---- | ------------------ | -| id | number | Yes | Notification ID. | -| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent.| -| userId | number | Yes | User ID.| -**Example** +## SlotType -```js -// Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; -// User ID -let userId = 100; +**System capability**: SystemCapability.Notification.Notification -Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { - console.info("cancelAsBundle success"); -}); -``` +| Name | Value | Description | +| -------------------- | -------- | ---------- | +| UNKNOWN_TYPE | 0 | Unknown type.| +| SOCIAL_COMMUNICATION | 1 | Notification slot for social communication.| +| SERVICE_INFORMATION | 2 | Notification slot for service information.| +| CONTENT_INFORMATION | 3 | Notification slot for content consultation.| +| OTHER_TYPES | 0xFFFF | Notification slot for other purposes.| -## Notification.enableNotificationSlot 9+ -enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback\): void +## NotificationActionButton -Sets the enabled status of a notification slot type for a specified application. This API uses an asynchronous callback to return the result. +Describes the button displayed in the notification. **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER +| Name | Type | Readable| Writable| Description | +| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | +| title | string | Yes | Yes | Button title. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** of the button.| +| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | +| userInput8+ | [NotificationUserInput](#notificationuserinput8) | Yes | Yes | User input object. | -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| type | [SlotType](#slottype) | Yes | Notification slot type. | -| enable | boolean | Yes | Whether to enable notification. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +## NotificationBasicContent -**Example** +Describes the normal text notification. -```js -// enableNotificationSlot -function enableSlotCallback(err) { - if (err.code) { - console.info("enableNotificationSlot failed " + JSON.stringify(err)); - } else { - console.info("enableNotificationSlot success"); - } -}; +**System capability**: SystemCapability.Notification.Notification -Notification.enableNotificationSlot( - { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, - true, - enableSlotCallback); -``` +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | ---------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| -## Notification.enableNotificationSlot 9+ -enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise\ +## NotificationLongTextContent -Sets the enabled status of a notification slot type for a specified application. This API uses a promise to return the result. +Describes the long text notification. **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| longText | string | Yes | Yes | Long text of the notification. | +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER -**Parameters** +## NotificationMultiLineContent -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| type | [SlotType](#slottype) | Yes | Notification slot type.| -| enable | boolean | Yes | Whether to enable notification. | +Describes the multi-line text notification. -**Example** +**System capability**: SystemCapability.Notification.Notification -```js -// enableNotificationSlot -Notification.enableNotificationSlot({ bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION,true).then(() => { - console.info("enableNotificationSlot success"); -}); -``` +| Name | Type | Readable| Writable| Description | +| -------------- | --------------- | --- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| lines | Array\ | Yes | Yes | Multi-line text of the notification. | -## Notification.isNotificationSlotEnabled 9+ -isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback\): void +## NotificationPictureContent -Checks whether a specified notification slot type is enabled for a specified application. This API uses an asynchronous callback to return the result. +Describes the picture-attached notification. **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Picture attached to the notification. | -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| type | [SlotType](#slottype) | Yes | Notification slot type. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +## NotificationContent -**Example** +Describes the notification content. -```js -// isNotificationSlotEnabled -function getEnableSlotCallback(err, data) { - if (err.code) { - console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); - } else { - console.info("isNotificationSlotEnabled success"); - } -}; +**System capability**: SystemCapability.Notification.Notification -Notification.isNotificationSlotEnabled( - { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, - getEnableSlotCallback); -``` +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | +| contentType | [ContentType](#contenttype) | Yes | Yes | Notification content type. | +| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | +| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | -## Notification.isNotificationSlotEnabled 9+ -isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ +## NotificationFlagStatus8+ -Checks whether a specified notification slot type is enabled for a specified application. This API uses a promise to return the result. +Describes the notification flag status. **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| type | [SlotType](#slottype) | Yes | Notification slot type.| - -**Return value** - -| Type | Description | -| ------------------ | ------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// isNotificationSlotEnabled -Notification.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION).then((data) => { - console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); -}); -``` - +| Name | Value | Description | +| -------------- | --- | --------------------------------- | +| TYPE_NONE | 0 | The default flag is used. | +| TYPE_OPEN | 1 | The notification flag is enabled. | +| TYPE_CLOSE | 2 | The notification flag is disabled. | -## Notification.setSyncNotificationEnabledWithoutApp9+ -setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: AsyncCallback\): void +## NotificationFlags8+ -Sets whether to enable the notification sync feature for devices where the application is not installed. This API uses an asynchronous callback to return the result. +Enumerates notification flags. **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. +| Name | Type | Readable| Writable| Description | +| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | +| soundEnabled | [NotificationFlagStatus](#notificationflagstatus8) | Yes | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus8) | Yes | No | Whether to enable vibration for the notification. | -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER -**Parameters** +## NotificationRequest -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | -------------- | -| userId | number | Yes | User ID. | -| enable | boolean | Yes | Whether the feature is enabled. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +Describes the notification request. -**Example** - -```js -let userId = 100; -let enable = true; - -function callback(err) { - if (err.code) { - console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); - } else { - console.info("setSyncNotificationEnabledWithoutApp success"); - } -} - -Notification.setSyncNotificationEnabledWithoutApp(userId, enable, callback); -``` - - -## Notification.setSyncNotificationEnabledWithoutApp9+ - -setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\ - -Sets whether to enable the notification sync feature for devices where the application is not installed. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | -------------- | -| userId | number | Yes | User ID. | -| enable | boolean | Yes | Whether the feature is enabled. | - -**Return value** - -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -let userId = 100; -let enable = true; - -Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { - console.info('setSyncNotificationEnabledWithoutApp success'); -}).catch((err) => { - console.info('setSyncNotificationEnabledWithoutApp, err:' + JSON.stringify(err)); -}); -``` - - -## Notification.getSyncNotificationEnabledWithoutApp9+ - -getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void - -Obtains whether the notification sync feature is enabled for devices where the application is not installed. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | -------------- | -| userId | number | Yes | User ID. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -let userId = 100; - -function getSyncNotificationEnabledWithoutAppCallback(err, data) { - if (err) { - console.info('getSyncNotificationEnabledWithoutAppCallback, err:' + err); - } else { - console.info('getSyncNotificationEnabledWithoutAppCallback, data:' + data); - } -} - -Notification.getSyncNotificationEnabledWithoutApp(userId, getSyncNotificationEnabledWithoutAppCallback); -``` - - -## Notification.getSyncNotificationEnabledWithoutApp9+ - -getSyncNotificationEnabledWithoutApp(userId: number): Promise\ - -Obtains whether the notification sync feature is enabled for devices where the application is not installed. This API uses a promise to return the result. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | -------------- | -| userId | number | Yes | User ID. | - -**Return value** - -| Type | Description | -| ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -let userId = 100; -Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { - console.info('getSyncNotificationEnabledWithoutApp, data:' + data); -}).catch((err) => { - console.info('getSyncNotificationEnabledWithoutApp, err:' + err); -}); -``` - -## NotificationSubscriber - -Provides callbacks for receiving or removing notifications and serves as the input parameter of [subscribe](#notificationsubscribe). - -**System API**: This is a system API and cannot be called by third-party applications. - -### onConsume - -onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void - -Callback for receiving notifications. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification received.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; - -function onConsumeCallback(data) { - let req = data.request; - console.info('===> onConsume callback req.id:' + req.id); -}; - -let subscriber = { - onConsume: onConsumeCallback -}; - -Notification.subscribe(subscriber, subscribeCallback); -``` - -### onCancel - -onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void - -Callback for canceling notifications. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification to cancel.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; - -function onCancelCallback(data) { - let req = data.request; - console.info('===> onCancel callback req.id:' + req.id); -} - -let subscriber = { - onCancel: onCancelCallback -}; - -Notification.subscribe(subscriber, subscribeCallback); -``` - -### onUpdate - -onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void - -Callback for notification sorting updates. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| data | [NotificationSortingMap](#notificationsortingmap) | Yes| Latest notification sorting list.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; - -function onUpdateCallback(map) { - console.info('===> onUpdateCallback map:' + JSON.stringify(map)); -} - -let subscriber = { - onUpdate: onUpdateCallback -}; - -Notification.subscribe(subscriber, subscribeCallback); -``` - -### onConnect - -onConnect?:() => void - -Callback for subscription. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Example** - -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; - -function onConnectCallback() { - console.info('===> onConnect in test'); -} - -let subscriber = { - onConnect: onConnectCallback -}; - -Notification.subscribe(subscriber, subscribeCallback); -``` - -### onDisconnect - -onDisconnect?:() => void - -Callback for unsubscription. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Example** - -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; -function unsubscribeCallback(err) { - if (err.code) { - console.info("unsubscribe failed " + JSON.stringify(err)); - } else { - console.info("unsubscribeCallback"); - } -}; - -function onConnectCallback() { - console.info('===> onConnect in test'); -} -function onDisconnectCallback() { - console.info('===> onDisconnect in test'); -} - -let subscriber = { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback -}; - -// The onConnect callback is invoked when subscription to the notification is complete. -Notification.subscribe(subscriber, subscribeCallback); -// The onDisconnect callback is invoked when unsubscription to the notification is complete. -Notification.unsubscribe(subscriber, unsubscribeCallback); -``` - -### onDestroy - -onDestroy?:() => void - -Callback for service disconnection. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Example** - -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; - -function onDestroyCallback() { - console.info('===> onDestroy in test'); -} - -let subscriber = { - onDestroy: onDestroyCallback -}; - -Notification.subscribe(subscriber, subscribeCallback); -``` - -### onDoNotDisturbDateChange8+ - -onDoNotDisturbDateChange?:(mode: notification.[DoNotDisturbDate](#donotdisturbdate8)) => void - -Callback for DND time setting updates. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| mode | notification.[DoNotDisturbDate](#donotdisturbdate8) | Yes| DND time setting updates.| - -**Example** -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; - -function onDoNotDisturbDateChangeCallback(mode) { - console.info('===> onDoNotDisturbDateChange:' + mode); -} - -let subscriber = { - onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback -}; -Notification.subscribe(subscriber, subscribeCallback); - -let doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, - begin: new Date(), - end: new Date(2021, 11, 15, 18, 0) -} -// Set the onDoNotDisturbDateChange callback for DND time setting updates. -Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { - console.info("setDoNotDisturbDate sucess"); -}); -``` - - -### onEnabledNotificationChanged8+ - -onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) => void - -Listens for the notification enabled status changes. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| callback | AsyncCallback\<[EnabledNotificationCallbackData](#enablednotificationcallbackdata8)\> | Yes| Callback used to return the result.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribeCallback"); - } -}; - -function onEnabledNotificationChangedCallback(callbackData) { - console.info("bundle: " + callbackData.bundle); - console.info("uid: " + callbackData.uid); - console.info("enable: " + callbackData.enable); -}; - -let subscriber = { - onEnabledNotificationChanged: onEnabledNotificationChangedCallback -}; -Notification.subscribe(subscriber, subscribeCallback); - -let bundle = { - bundle: "bundleName1", -} -// Set the onEnabledNotificationChanged callback that is triggered when the notification enabled status changes. -Notification.enableNotification(bundle, false).then(() => { - console.info("enableNotification sucess"); -}); -``` - -## SubscribeCallbackData - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| --------------- | ------------------------------------------------- | ---- | --- | -------- | -| request | [NotificationRequest](#notificationrequest) | Yes | No | Notification content.| -| sortingMap | [NotificationSortingMap](#notificationsortingmap) | Yes | No | Notification sorting information.| -| reason | number | Yes | No | Reason for deletion.| -| sound | string | Yes | No | Sound used for notification.| -| vibrationValues | Array\ | Yes | No | Vibration used for notification.| - - -## EnabledNotificationCallbackData8+ - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ------ | ------- | ---- | --- | ---------------- | -| bundle | string | Yes | No | Bundle name of the application. | -| uid | number | Yes | No | UID of the application. | -| enable | boolean | Yes | No | Notification enabled status of the application.| - - -## DoNotDisturbDate8+ - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----- | -------------------------------------- | ---- | ---- | ---------------------- | -| type | [DoNotDisturbType](#donotdisturbtype8) | Yes | Yes | DND time type.| -| begin | Date | Yes | Yes | DND start time.| -| end | Date | Yes | Yes | DND end time.| - -## DoNotDisturbType8+ - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| ------------ | ---------------- | ------------------------------------------ | -| TYPE_NONE | 0 | Non-DND. | -| TYPE_ONCE | 1 | One-shot DND at the specified time segment (only considering the hour and minute).| -| TYPE_DAILY | 2 | Daily DND at the specified time segment (only considering the hour and minute).| -| TYPE_CLEARLY | 3 | DND at the specified time segment (considering the year, month, day, hour, and minute). | - - -## ContentType - -**System capability**: SystemCapability.Notification.Notification - -| Name | Value | Description | -| --------------------------------- | ----------- | ------------------ | -| NOTIFICATION_CONTENT_BASIC_TEXT | NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification. | -| NOTIFICATION_CONTENT_LONG_TEXT | NOTIFICATION_CONTENT_LONG_TEXT | Long text notification. | -| NOTIFICATION_CONTENT_PICTURE | NOTIFICATION_CONTENT_PICTURE | Picture-attached notification. | -| NOTIFICATION_CONTENT_CONVERSATION | NOTIFICATION_CONTENT_CONVERSATION | Conversation notification. | -| NOTIFICATION_CONTENT_MULTILINE | NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| - -## SlotLevel - -**System capability**: SystemCapability.Notification.Notification - -| Name | Value | Description | -| --------------------------------- | ----------- | ------------------ | -| LEVEL_NONE | 0 | The notification function is disabled. | -| LEVEL_MIN | 1 | The notification function is enabled, but the notification icon is not displayed in the status bar, with no banner or alert tone.| -| LEVEL_LOW | 2 | The notification function is enabled, and the notification icon is displayed in the status bar, with no banner or alert tone.| -| LEVEL_DEFAULT | 3 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone but no banner.| -| LEVEL_HIGH | 4 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone and banner.| - - -## BundleOption - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ------ | ------ |---- | --- | ------ | -| bundle | string | Yes | Yes | Bundle information of the application.| -| uid | number | Yes | Yes | User ID.| - -## NotificationKey - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ----- | ------ | ---- | --- | -------- | -| id | number | Yes | Yes | Notification ID. | -| label | string | Yes | Yes | Notification label.| - - -## SlotType - -**System capability**: SystemCapability.Notification.Notification - -| Name | Value | Description | -| -------------------- | -------- | ---------- | -| UNKNOWN_TYPE | 0 | Unknown type.| -| SOCIAL_COMMUNICATION | 1 | Notification slot for social communication.| -| SERVICE_INFORMATION | 2 | Notification slot for service information.| -| CONTENT_INFORMATION | 3 | Notification slot for content consultation.| -| OTHER_TYPES | 0xFFFF | Notification slot for other purposes.| - - -## NotificationActionButton - -Describes the button displayed in the notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | -| title | string | Yes | Yes | Button title. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** of the button.| -| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | -| userInput8+ | [NotificationUserInput](#notificationuserinput8) | Yes | Yes | User input object. | - - -## NotificationBasicContent - -Describes the normal text notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | ------ | ---- | ---- | ---------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| - - -## NotificationLongTextContent - -Describes the long text notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | ------ | ---- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| longText | string | Yes | Yes | Long text of the notification. | -| briefText | string | Yes | Yes | Brief text of the notification.| -| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | - - -## NotificationMultiLineContent - -Describes the multi-line text notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | --------------- | --- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| briefText | string | Yes | Yes | Brief text of the notification.| -| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | -| lines | Array\ | Yes | Yes | Multi-line text of the notification. | - - -## NotificationPictureContent - -Describes the picture-attached notification. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | --- | -------------------------------- | -| title | string | Yes | Yes | Notification title. | -| text | string | Yes | Yes | Notification content. | -| additionalText | string | Yes | Yes | Additional information of the notification.| -| briefText | string | Yes | Yes | Brief text of the notification.| -| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | -| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Picture attached to the notification. | - - -## NotificationContent - -Describes the notification content. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | -| contentType | [ContentType](#contenttype) | Yes | Yes | Notification content type. | -| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | -| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| -| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | -| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | - - -## NotificationFlagStatus8+ - -Describes the notification flag status. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------- | --- | --------------------------------- | -| TYPE_NONE | 0 | The default flag is used. | -| TYPE_OPEN | 1 | The notification flag is enabled. | -| TYPE_CLOSE | 2 | The notification flag is disabled. | - - -## NotificationFlags8+ - -Enumerates notification flags. - -**System capability**: SystemCapability.Notification.Notification - -| Name | Type | Readable| Writable| Description | -| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | -| soundEnabled | [NotificationFlagStatus](#notificationflagstatus8) | Yes | No | Whether to enable the sound alert for the notification. | -| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus8) | Yes | No | Whether to enable vibration for the notification. | - - -## NotificationRequest - -Describes the notification request. - -**System capability**: SystemCapability.Notification.Notification +**System capability**: SystemCapability.Notification.Notification | Name | Type | Readable| Writable| Description | | --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | @@ -3947,12 +3169,16 @@ Provides the notification user input. | inputKey | string | Yes | Yes | Key to identify the user input.| -## DeviceRemindType8+ +## DeviceRemindType8+ deprecated **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [notificationManager.DeviceRemindType](js-apis-notificationManager.md#deviceremindtype) instead. + | Name | Value | Description | | -------------------- | --- | --------------------------------- | | IDLE_DONOT_REMIND | 0 | The device is not in use. No notification is required. | @@ -3961,25 +3187,33 @@ Provides the notification user input. | ACTIVE_REMIND | 3 | The device is in use. | -## SourceType8+ +## SourceType8+ deprecated **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [notificationManager.SourceType](js-apis-notificationManager.md#sourcetype) instead. + | Name | Value | Description | | -------------------- | --- | -------------------- | | TYPE_NORMAL | 0 | Normal notification. | | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | -## RemoveReason9+ +## RemoveReason9+ deprecated **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. +> **NOTE** +> +> This API is supported since API version 9 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead. + | Name | Value | Description | | -------------------- | --- | -------------------- | -| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | -| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | +| CLICK_REASON_REMOVE9+ | 1 | The notification is removed after a click on it. | +| CANCEL_REASON_REMOVE9+ | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-notificationManager.md b/en/application-dev/reference/apis/js-apis-notificationManager.md index 3142a3daec90c4ac772e6a6f1e9d36572b9ee828..024b58e38329ce83b1f119d383ff697ad5df1a84 100644 --- a/en/application-dev/reference/apis/js-apis-notificationManager.md +++ b/en/application-dev/reference/apis/js-apis-notificationManager.md @@ -33,7 +33,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -88,8 +87,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------------- | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -145,8 +142,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------------- | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -209,8 +204,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------------- | -| 201 | Permission denied. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -265,7 +258,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -306,7 +298,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -341,7 +332,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -375,7 +365,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -414,7 +403,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -452,9 +440,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -502,9 +487,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -543,7 +525,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -583,7 +564,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -622,9 +602,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -676,9 +653,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -721,7 +695,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -767,7 +740,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -783,7 +755,7 @@ notificationManager.getSlot(slotType).then((data) => { ## notificationManager.getSlots -getSlots(callback: AsyncCallback>): void +getSlots(callback: AsyncCallback\>): void Obtains all notification slots of this application. This API uses an asynchronous callback to return the result. @@ -801,7 +773,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -822,7 +793,7 @@ notificationManager.getSlots(getSlotsCallback); ## notificationManager.getSlots -getSlots(): Promise\> +getSlots(): Promise\> Obtains all notification slots of this application. This API uses a promise to return the result. @@ -840,7 +811,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -874,7 +844,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -914,7 +883,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -948,7 +916,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -980,7 +947,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1019,9 +985,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1068,9 +1031,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1104,7 +1064,7 @@ Checks whether notification is enabled for a specified application. This API use | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | | bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1112,9 +1072,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1166,9 +1123,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1201,7 +1155,7 @@ Checks whether notification is enabled for this application. This API uses an as | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1209,9 +1163,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1242,11 +1193,93 @@ Checks whether notification is enabled for the current application. This API use **System API**: This is a system API and cannot be called by third-party applications. +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```ts +notificationManager.isNotificationEnabled().then((data) => { + console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); +}); +``` + +## notificationManager.isNotificationEnabled + +isNotificationEnabled(userId: number, callback: AsyncCallback\): void + +Checks whether notification is enabled for a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| userId | number | Yes | User ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```ts +function isNotificationEnabledCallback(err, data) { + if (err) { + console.error(`isNotificationEnabled failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("isNotificationEnabled success"); + } +} + +let userId = 1; + +notificationManager.isNotificationEnabled(userId, isNotificationEnabledCallback); +``` + +## notificationManager.isNotificationEnabled + +isNotificationEnabled(userId: number): Promise\ + +Checks whether notification is enabled for a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application.| +| userId | number | Yes | User ID.| **Return value** @@ -1260,18 +1293,17 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | -| 17700001 | The specified bundle name was not found. | +| 1600008 | The user is not exist.. | **Example** ```ts -notificationManager.isNotificationEnabled().then((data) => { +let userId = 1; + +notificationManager.isNotificationEnabled(userId).then((data) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1302,9 +1334,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1351,9 +1380,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1395,9 +1421,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1449,9 +1472,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1486,7 +1506,6 @@ Sets the notification badge number. This API uses a promise to return the result | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1522,7 +1541,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1569,9 +1587,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1621,9 +1636,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1645,7 +1657,7 @@ notificationManager.setSlotByBundle(bundle, notificationSlot).then(() => { ## notificationManager.getSlotsByBundle -getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void +getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback\>): void Obtains the notification slots of a specified application. This API uses an asynchronous callback to return the result. @@ -1660,7 +1672,7 @@ Obtains the notification slots of a specified application. This API uses an asyn | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------- | | bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Error codes** @@ -1668,9 +1680,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1694,7 +1703,7 @@ notificationManager.getSlotsByBundle(bundle, getSlotsByBundleCallback); ## notificationManager.getSlotsByBundle -getSlotsByBundle(bundle: BundleOption): Promise> +getSlotsByBundle(bundle: BundleOption): Promise\> Obtains the notification slots of a specified application. This API uses a promise to return the result. @@ -1714,7 +1723,7 @@ Obtains the notification slots of a specified application. This API uses a promi | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Error codes** @@ -1722,9 +1731,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1766,9 +1772,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1820,9 +1823,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1842,7 +1842,7 @@ notificationManager.getSlotNumByBundle(bundle).then((data) => { ## notificationManager.getAllActiveNotifications -getAllActiveNotifications(callback: AsyncCallback>): void +getAllActiveNotifications(callback: AsyncCallback\>): void Obtains all active notifications. This API uses an asynchronous callback to return the result. @@ -1856,15 +1856,12 @@ Obtains all active notifications. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Error codes** | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1907,9 +1904,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1942,7 +1936,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1981,7 +1974,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1996,7 +1988,7 @@ notificationManager.getActiveNotificationCount().then((data) => { ## notificationManager.getActiveNotifications -getActiveNotifications(callback: AsyncCallback>): void +getActiveNotifications(callback: AsyncCallback\>): void Obtains active notifications of this application. This API uses an asynchronous callback to return the result. @@ -2006,7 +1998,7 @@ Obtains active notifications of this application. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback> | Yes | Callback used to return the result.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Error codes** @@ -2014,7 +2006,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2053,7 +2044,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2087,7 +2077,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2128,7 +2117,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2168,9 +2156,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2218,9 +2203,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2261,9 +2243,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2313,9 +2292,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2361,9 +2337,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2417,9 +2390,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2467,9 +2437,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2513,9 +2480,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2555,9 +2519,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2610,9 +2571,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2652,9 +2610,6 @@ Checks whether DND mode is supported. This API uses an asynchronous callback to | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2697,9 +2652,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2733,11 +2685,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | -| 1600011 | Read template config failed. | **Example** @@ -2780,11 +2730,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | -| 1600011 | Read template config failed. | **Example** @@ -2816,7 +2764,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2849,7 +2796,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2889,9 +2835,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2937,9 +2880,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2976,7 +2916,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3018,7 +2957,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3060,9 +2998,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3116,9 +3051,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3164,9 +3096,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3221,9 +3150,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3267,9 +3193,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3312,9 +3235,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3355,9 +3275,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3425,9 +3342,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3491,9 +3405,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3547,9 +3458,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3596,9 +3504,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3649,9 +3554,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3695,9 +3597,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3752,9 +3651,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3797,9 +3693,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3854,9 +3747,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3901,9 +3791,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3956,9 +3843,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3975,6 +3859,87 @@ notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => }); ``` +## notificationManager.on10+ + +on(type: 'checkNotification', callback: (checkInfo: NotificationCheckInfo) => NotificationCheckResult): void; + +Subscribes to notification events. The notification service sends the notification information in the callback to the verification program. The verification program returns the verification result to determine whether to publish the notification, for example, controlling the publish frequency of marketing notifications. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| type | string | Yes | Event type. The value is fixed to **'checkNotification'**.| +| callback | (checkInfo: [NotificationCheckInfo](#notificationcheckinfo10)) => [NotificationCheckResult](#notificationcheckresult10) | Yes | Pointer to the notification verification function.| + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | + +**Example** + +```ts +try{ + notificationManager.on("checkNotification", OnCheckNotification); +} catch (error){ + console.info(`notificationManager.on error: ${JSON.stringify(error)}`); +} +function OnCheckNotification(info : notificationManager.NotificationCheckInfo) { + console.info(`====>OnCheckNotification info: ${JSON.stringify(info)}`); + if(info.notificationId == 1){ + return { code: 1, message: "testMsg1"} + } else { + return { code: 0, message: "testMsg0"} + } +} +``` + +## notificationManager.off10+ + +off(type: 'checkNotification', callback?: (checkInfo: NotificationCheckInfo) => NotificationCheckResult): void; + +Unsubscribes from notification events. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| type | string | Yes | Event type. The value is fixed to **'checkNotification'**.| +| callback | (checkInfo: [NotificationCheckInfo](#notificationcheckinfo10)) => [NotificationCheckResult](#notificationcheckresult10) | No | Pointer to the notification verification function.| + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | + +**Example** + +```ts +try{ + notificationManager.off("checkNotification"); +} catch (error){ + console.info(`notificationManager.off error: ${JSON.stringify(error)}`); +} +``` ## DoNotDisturbDate @@ -3982,11 +3947,11 @@ notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => **System API**: This is a system API and cannot be called by third-party applications. -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-only| Mandatory| Description | | ----- | ------------------------------------- | ---- | ---- | ---------------------- | -| type | [DoNotDisturbType](#donotdisturbtype) | Yes | Yes | DND time type.| -| begin | Date | Yes | Yes | DND start time.| -| end | Date | Yes | Yes | DND end time.| +| type | [DoNotDisturbType](#donotdisturbtype) | No | Yes | DND time type.| +| begin | Date | No | Yes | DND start time.| +| end | Date | No | Yes | DND end time.| ## DoNotDisturbType @@ -4067,3 +4032,30 @@ notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => | TYPE_NORMAL | 0 | Normal notification. | | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | + +## NotificationCheckInfo10+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +| Name | Type | Read-only| Mandatory| Description | +| ----- | ------------------------------------- | ---- | ---- | ---------------------- | +| bundleName | string | No | Yes | Bundle name.| +| notificationId | number | No | Yes | Notification ID. | +| contentType | [ContentType](#contenttype) | No | Yes | Notification type. | + +## NotificationCheckResult10+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +| Name | Type | Read-only| Mandatory| Description | +| ----- | ------------------------------------- | ---- | ---- | ---------------------- | +| code | number | No | Yes | Result code.
**0**: display.
**1**: no display.| +| message | string | No | Yes | Result. | diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index fa441c00c57cb994824aeb3cf061e623f5256089..0746cb7cb1defd1691cbab96898dbb6ad47996a3 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -12,8 +12,6 @@ The **notificationSubscribe** module provides APIs for notification subscription import notificationSubscribe from '@ohos.notificationSubscribe'; ``` - - ## NotificationSubscribe.subscribe subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void @@ -40,9 +38,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -96,9 +91,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -150,9 +142,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -199,9 +188,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -249,9 +235,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -287,7 +270,7 @@ Removes a notification for a specified application. This API uses an asynchronou | Name | Type | Mandatory| Description | | --------------- | ----------------------------------| ---- | -------------------- | | bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | -| notificationKey | [NotificationKey](js-apis-notification.md#notificationkey) | Yes | Notification key. | +| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | | reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -297,9 +280,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -346,7 +326,7 @@ Removes a notification for a specified application. This API uses a promise to r | Name | Type | Mandatory| Description | | --------------- | --------------- | ---- | ---------- | | bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application.| -| notificationKey | [NotificationKey]((js-apis-notification.md#notificationkey)) | Yes | Notification key. | +| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | | reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | **Error codes** @@ -355,9 +335,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -374,7 +351,7 @@ let notificationKey = { id: 0, label: "label", }; -let reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +let reason = notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; notificationSubscribe.remove(bundle, notificationKey, reason).then(() => { console.info("remove success"); }); @@ -396,7 +373,7 @@ Removes a specified notification. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | Yes | Unique notification ID. It is the value of **hashCode** in the [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) object of [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) in the [onConsume](#onconsume) callback.| +| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) object of [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onConsume) callback.| | reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -406,9 +383,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -426,7 +400,7 @@ function removeCallback(err) { console.info("remove success"); } } -let reason = NotificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; +let reason = notificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; notificationSubscribe.remove(hashCode, reason, removeCallback); ``` @@ -455,9 +429,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -489,7 +460,7 @@ Removes all notifications for a specified application. This API uses an asynchro | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption]((js-apis-inner-notification-notificationCommonDef.md#bundleoption)) | Yes | Bundle information of the application. | +| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -498,9 +469,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -519,7 +487,7 @@ function removeAllCallback(err) { let bundle = { bundle: "bundleName1", }; -NotificationSubscribe.removeAll(bundle, removeAllCallback); +notificationSubscribe.removeAll(bundle, removeAllCallback); ``` ## NotificationSubscribe.removeAll @@ -546,9 +514,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -583,7 +548,7 @@ Removes all notifications for a specified application. This API uses a promise t | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption]((js-apis-inner-notification-notificationCommonDef.md#bundleoption)) | No | Bundle information of the application.| +| bundle | [BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) | No | Bundle information of the application.| **Error codes** @@ -591,9 +556,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -633,9 +595,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -657,7 +616,7 @@ let userId = 1; notificationSubscribe.removeAll(userId, removeAllCallback); ``` -## Notification.removeAll +## NotificationSubscribe.removeAll removeAll(userId: number): Promise\ @@ -681,9 +640,6 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ | ID| Error Message | | -------- | ----------------------------------- | -| 201 | Permission denied. | -| 202 | Not system application to call the interface. | -| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -705,359 +661,14 @@ let userId = 1; notificationSubscribe.removeAll(userId, removeAllCallback); ``` -## NotificationSubscriber - -Provides callbacks for receiving or removing notifications and serves as the input parameter of [subscribe](#notificationsubscribesubscribe). - -**System API**: This is a system API and cannot be called by third-party applications. - -### onConsume - -onConsume?: (data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void - -Called when a notification is received. +## NotificationKey **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | Yes| Information about the notification received.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onConsumeCallback(data) { - console.info('===> onConsume in test'); - let req = data.request; - console.info('===> onConsume callback req.id:' + req.id); -}; - -let subscriber = { - onConsume: onConsumeCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - -### onCancel - -onCancel?:(data: [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata)) => void - -Called when a notification is canceled. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) | Yes| Information about the notification to cancel.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onCancelCallback(data) { - console.info('===> onCancel in test'); - let req = data.request; - console.info('===> onCancel callback req.id:' + req.id); -} - -let subscriber = { - onCancel: onCancelCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - -### onUpdate - -onUpdate?:(data: [NotificationSortingMap](js-apis-notification.md#notificationsortingmap)) => void - -Called when the notification sorting list is updated. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| data | [NotificationSortingMap](js-apis-notification.md#notificationsortingmap)) | Yes| Latest notification sorting list.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onUpdateCallback(map) { - console.info('===> onUpdateCallback map:' + JSON.stringify(map)); -} - -let subscriber = { - onUpdate: onUpdateCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - -### onConnect - -onConnect?:() => void - -Called when subscription is complete. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onConnectCallback() { - console.info('===> onConnect in test'); -} - -let subscriber = { - onConnect: onConnectCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - -### onDisconnect - -onDisconnect?:() => void - -Called when unsubscription is complete. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; -function unsubscribeCallback(err) { - if (err.code) { - console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("unsubscribeCallback"); - } -}; - -function onConnectCallback() { - console.info('===> onConnect in test'); -} -function onDisconnectCallback() { - console.info('===> onDisconnect in test'); -} - -let subscriber = { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback -}; - -// The onConnect callback is invoked when subscription to the notification is complete. -notificationSubscribe.subscribe(subscriber, subscribeCallback); -// The onDisconnect callback is invoked when unsubscription to the notification is complete. -notificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); -``` - -### onDestroy - -onDestroy?:() => void - -Callback for service disconnection. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onDestroyCallback() { - console.info('===> onDestroy in test'); -} - -let subscriber = { - onDestroy: onDestroyCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - -### onDoNotDisturbDateChange - -onDoNotDisturbDateChange?:(mode: notification.[DoNotDisturbDate](js-apis-notificationManager.md#donotdisturbdate)) => void - -Called when the DND time setting is updated. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| mode | notification.[DoNotDisturbDate](js-apis-notificationManager.md#DoNotDisturbDate) | Yes| DND time setting updates.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onDoNotDisturbDateChangeCallback(mode) { - console.info('===> onDoNotDisturbDateChange:' + mode); -} - -let subscriber = { - onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - - -### onEnabledNotificationChanged - -onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata8)) => void - -Listens for the notification enabled status changes. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| ------------ | ------------------------ | ---- | -------------------------- | -| callback | AsyncCallback\<[EnabledNotificationCallbackData](js-apis-notification.md#enablednotificationcallbackdata8)\> | Yes| Callback used to return the result.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onEnabledNotificationChangedCallback(callbackData) { - console.info("bundle: ", callbackData.bundle); - console.info("uid: ", callbackData.uid); - console.info("enable: ", callbackData.enable); -}; - -let subscriber = { - onEnabledNotificationChanged: onEnabledNotificationChangedCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - -### onBadgeChanged10+ - - onBadgeChanged?:(data: [BadgeNumberCallbackData](#badgenumbercallbackdata10)) => void - -Listens for the change of the notification badge number. - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| callback | AsyncCallback\<[BadgeNumberCallbackData](#badgenumbercallbackdata10)\> | Yes | Callback used to return the result.| - -**Example** - -```javascript -function subscribeCallback(err) { - if (err) { - console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("subscribeCallback"); - } -}; - -function onBadgeChangedCallback(data) { - console.info("bundle: ", data.bundle); - console.info("uid: ", data.uid); - console.info("badgeNumber: ", data.badgeNumber); -}; - -let subscriber = { - onBadgeChanged: onBadgeChangedCallback -}; - -notificationSubscribe.subscribe(subscriber, subscribeCallback); -``` - +| Name | Type | Read-only| Mandatory| Description | +| ----- | ------ | ---- | --- | -------- | +| id | number | No | Yes | Notification ID. | +| label | string | No | No | Notification label.| ## RemoveReason @@ -1069,15 +680,3 @@ notificationSubscribe.subscribe(subscriber, subscribeCallback); | -------------------- | --- | -------------------- | | CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | | CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | - -## BadgeNumberCallbackData10+ - -**System capability**: SystemCapability.Notification.Notification - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------- | ------ | ---- | ---- | ------------ | -| bundle | string | Yes | No | Bundle name of the application.| -| uid | number | Yes | No | UID of the application. | -| badgeNumber | number | Yes | No | Notification badge number. | diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index b0e30e22190f5242d16e4be0b815bcf4c4109f30..81a8b7bc6859f69bb6543e18600fd46296bb818c 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -15,7 +15,7 @@ import observer from '@ohos.telephony.observer'; ## observer.on('networkStateChange') -on\(type: \'networkStateChange\', callback: Callback\): void; +on\(type: \'networkStateChange\', callback: Callback\\): void; Registers an observer for network status change events. This API uses an asynchronous callback to return the execution result. @@ -54,7 +54,7 @@ observer.on('networkStateChange', data => { ## observer.on('networkStateChange') -on\(type: \'networkStateChange\', options: { slotId: number }, callback: Callback\): void; +on\(type: \'networkStateChange\', options: { slotId: number }, callback: Callback\\): void; Registers an observer for network status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the execution result. @@ -94,7 +94,7 @@ observer.on('networkStateChange', {slotId: 0}, data => { ## observer.off('networkStateChange') -off\(type: \'networkStateChange\', callback?: Callback\): void; +off\(type: \'networkStateChange\', callback?: Callback\\): void; Unregisters the observer for network status change events. This API uses an asynchronous callback to return the execution result. @@ -111,6 +111,10 @@ Unregisters the observer for network status change events. This API uses an asyn | type | string | Yes | Network status change event. This field has a fixed value of **networkStateChange**. | | callback | Callback\<[NetworkState](js-apis-radio.md#networkstate)\> | No | Callback used to return the result. For details, see [NetworkState](js-apis-radio.md#networkstate).| +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + | ID| Error Message | | -------- | -------------------------------------------- | | 401 | Parameter error. | @@ -133,7 +137,7 @@ observer.off('networkStateChange'); ## observer.on('signalInfoChange') -on\(type: \'signalInfoChange\', callback: Callback\>): void; +on\(type: \'signalInfoChange\', callback: Callback\\>): void; Registers an observer for signal status change events. This API uses an asynchronous callback to return the execution result. @@ -144,15 +148,14 @@ Registers an observer for signal status change events. This API uses an asynchro | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | | type | string | Yes | Signal status change event. This field has a fixed value of **signalInfoChange**. | -| callback | Callback\> | Yes | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| +| callback | Callback\\> | Yes | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| **Error codes** For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). -| ID| Error Message | +| ID| Error Message | | -------- | -------------------------------------------- | -| 201 | Permission denied. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -170,7 +173,7 @@ observer.on('signalInfoChange', data => { ## observer.on('signalInfoChange') -on\(type: \'signalInfoChange\', options: { slotId: number }, callback: Callback\>): void; +on\(type: \'signalInfoChange\', options: { slotId: number }, callback: Callback\\>): void; Registers an observer for signal status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the execution result. @@ -182,7 +185,7 @@ Registers an observer for signal status change events of the SIM card in the spe | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | | type | string | Yes | Signal status change event. This field has a fixed value of **signalInfoChange**. | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | Callback\> | Yes | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| +| callback | Callback\\> | Yes | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| **Error codes** @@ -190,7 +193,6 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | -| 201 | Permission denied. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -208,7 +210,7 @@ observer.on('signalInfoChange', {slotId: 0}, data => { ## observer.off('signalInfoChange') -off\(type: \'signalInfoChange\', callback?: Callback\>): void; +off\(type: \'signalInfoChange\', callback?: Callback\\>): void; Unregisters the observer for signal status change events. This API uses an asynchronous callback to return the execution result. @@ -223,7 +225,7 @@ Unregisters the observer for signal status change events. This API uses an async | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Signal status change event. This field has a fixed value of **signalInfoChange**. | -| callback | Callback\> | No | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| +| callback | Callback\\> | No | Callback used to return the result. For details, see [SignalInformation](js-apis-radio.md#signalinformation).| **Error codes** @@ -251,7 +253,7 @@ observer.off('signalInfoChange'); ## observer.on('cellInfoChange')8+ -on\(type: \'cellInfoChange\', callback: Callback\): void; +on\(type: \'cellInfoChange\', callback: Callback\\>\): void; Registers an observer for cell information change events. This API uses an asynchronous callback to return the result. @@ -263,16 +265,19 @@ Registers an observer for cell information change events. This API uses an async **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------------- | ---- |------------------------------------------------------------| -| type | string | Yes | Cell information change event. This field has a fixed value of **cellInfoChange**. | -| callback | Callback\<[CellInformation](js-apis-radio.md#cellinformation8)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- |------------------------------------------| +| type | string | Yes | Cell information change event. This field has a fixed value of **cellInfoChange**.| +| callback | Callback\\> | Yes | Callback used to return the result. | **Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -290,7 +295,7 @@ observer.on('cellInfoChange', data => { ## observer.on('cellInfoChange')8+ -on\(type: \'cellInfoChange\', options: { slotId: number }, callback: Callback\): void; +on\(type: \'cellInfoChange\', options: { slotId: number }, callback: Callback\\>\): void; Registers an observer for signal status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the execution result. @@ -302,17 +307,20 @@ Registers an observer for signal status change events of the SIM card in the spe **Parameters** -| Name| Type | Mandatory| Description | -| ------ |--------------------------------------------------| ---- |------------------------------------------------------------| -| type | string | Yes | Cell information change event. This field has a fixed value of **cellInfoChange**. | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | Callback\<[CellInformation](js-apis-radio.md#cellinformation8)\> | Yes | Callback used to return the result.| +| Name| Type | Mandatory| Description | +| ------ |--------------------------------------------------| ---- |--------------------------------------------| +| type | string | Yes | Cell information change event. This field has a fixed value of **cellInfoChange**.| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | Callback\\> | Yes | Callback used to return the result. | **Error codes** +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -330,7 +338,7 @@ observer.on('cellInfoChange', {slotId: 0}, data => { ## observer.off('cellInfoChange')8+ -off\(type: \'cellInfoChange\', callback?: Callback\): void; +off\(type: \'cellInfoChange\', callback?: Callback\\>\): void; Unregisters the observer for cell information change events. This API uses an asynchronous callback to return the result. @@ -347,10 +355,15 @@ Unregisters the observer for cell information change events. This API uses an as | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Cell information change event. This field has a fixed value of **cellInfoChange**. | -| callback | Callback\<[CellInformation](js-apis-radio.md#cellinformation8)\> | No | Callback used to return the result.| +| callback | Callback\\> | No | Callback used to return the result.| + +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | diff --git a/en/application-dev/reference/apis/js-apis-overlay.md b/en/application-dev/reference/apis/js-apis-overlay.md index 30c46bad02c997e7915e5595a6308446a2f5d722..f96550cca0b1c21388ec02bc0d2f63d9879b7b21 100644 --- a/en/application-dev/reference/apis/js-apis-overlay.md +++ b/en/application-dev/reference/apis/js-apis-overlay.md @@ -52,11 +52,11 @@ try { overlay.setOverlayEnabled(moduleName, isEnabled) .then(() => { console.info('setOverlayEnabled success'); - }).catch((error) => { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }).catch((err) => { + console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message); }); -} catch (error) { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message); } ``` @@ -92,15 +92,15 @@ var moduleName = "feature"; var isEnabled = false; try { - overlay.setOverlayEnabled(moduleName, isEnabled, (error, data) => { - if (error) { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + overlay.setOverlayEnabled(moduleName, isEnabled, (err, data) => { + if (err) { + console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message); return; } console.info('setOverlayEnabled success'); }); -} catch (error) { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message); } ``` @@ -145,18 +145,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; var isEnabled = false; try { overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled) .then((data) => { console.info('setOverlayEnabledByBundleName successfully'); - }).catch((error) => { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }).catch((err) => { + console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message); }); -} catch (error) { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message); } ``` @@ -196,19 +196,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; var isEnabled = false; try { - overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (error, data) => { - if (error) { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (err, data) => { + if (err) { + console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message); return; } console.info('setOverlayEnabledByBundleName successfully'); }); -} catch (error) { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message); } ``` @@ -245,14 +245,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -var moduleName = "feature" +var moduleName = "feature"; (async() => { try { let overlayModuleInfo = await overlay.getOverlayModuleInfo(moduleName); console.log('overlayModuleInfo is ' + JSON.stringify(overlayModuleInfo)); } catch(err) { - console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } })(); ``` @@ -279,23 +279,23 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | | 17700002 | The specified module name is not found. | -| 17700032 | he specified bundle does not contain any overlay module. | +| 17700032 | The specified bundle does not contain any overlay module. | | 17700033 | The specified module is not an overlay module. | **Example** ```ts -var moduleName = "feature" +var moduleName = "feature"; try { - overlay.getOverlayModuleInfo(moduleName, (error, data) => { - if (error) { - console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getOverlayModuleInfo(moduleName, (err, data) => { + if (err) { + console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` @@ -331,14 +331,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -var targetModuleName = "feature" +var targetModuleName = "feature"; (async() => { try { let overlayModuleInfos = await overlay.getTargetOverlayModuleInfos(targetModuleName); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); } catch(err) { - console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } })(); ``` @@ -370,17 +370,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -var targetModuleName = "feature" +var targetModuleName = "feature"; try { - overlay.getTargetOverlayModuleInfos(targetModuleName, (error, data) => { - if (error) { - console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getTargetOverlayModuleInfos(targetModuleName, (err, data) => { + if (err) { + console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` @@ -401,7 +401,7 @@ Obtains the information about a module with the overlay feature in another appli | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | bundleName | string | Yes | Bundle name of the application. | -| moduleName | string | No | HAP name of the module with the overlay feature. If this parameter is not specified, the API obtains the information of all modules with the overlay feature in that application. | +| moduleName | string | No | HAP name of the module with the overlay feature. By default, no value is passed, and the API obtains the information of all modules with the overlay feature in that application. | **Return value** @@ -424,14 +424,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; (async() => { try { let overlayModuleInfos = await overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); } catch(err) { - console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } })(); ``` @@ -471,18 +471,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; try { - overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (error, data) => { - if (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (err, data) => { + if (err) { + console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` @@ -512,9 +512,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | | 17700001 | The specified bundleName is not found. | -| 17700002 | The specified module name is not found. | | 17700032 | The specified bundle does not contain any overlay module. | -| 17700033 | The specified module is not an overlay module. | **Example** @@ -522,15 +520,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc var bundleName = "com.example.myapplication_xxxxx"; try { - overlay.getOverlayModuleInfoByBundleName(bundleName, (error, data) => { - if (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getOverlayModuleInfoByBundleName(bundleName, (err, data) => { + if (err) { + console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` @@ -551,7 +549,7 @@ Obtains the information about modules with the overlay feature in another applic | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | targetBundleName | string | Yes | Bundle name of the application. | -| moduleName | string | No | HAP name of the target module, which is **targetModuleName** specified by modules with the overlay feature. If this parameter is not specified, the API obtains the information associated with all modules in that application. | +| moduleName | string | No | HAP name of the target module, which is **targetModuleName** specified by modules with the overlay feature. By default, no value is passed, and the API obtains the information associated with all modules in that application. | **Return value** @@ -574,21 +572,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var targetBundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; (async() => { try { let overlayModuleInfos = await overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); } catch(err) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } })(); ``` ## overlay.getTargetOverlayModuleInfosByBundleName -getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback\>): void; +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback<Array<OverlayModuleInfo>>): void; Obtains the information about modules with the overlay feature in another application based on the target module name. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. @@ -621,24 +619,24 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var targetBundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; try { - overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (error, data) => { - if (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (err, data) => { + if (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` ## overlay.getTargetOverlayModuleInfosByBundleName -getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback\>): void; +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback<Array<OverlayModuleInfo>>): void; Obtains the information about all modules with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. @@ -662,8 +660,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | | 17700001 | The specified bundleName is not found. | -| 17700002 | The specified module name is not found. | -| 17700034 | The specified module is an overlay module. | | 17700035 | The specified bundle is an overlay bundle. | **Example** @@ -672,15 +668,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc var targetBundleName = "com.example.myapplication_xxxxx"; try { - overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (error, data) => { - if (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (err, data) => { + if (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 49ed81e115de6345453c93441b68cda2a132021b..61bac1ec1ef7b02115705e7e5e34b600faedca60 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -258,6 +258,386 @@ try { } ``` +## pointer.setHoverScrollState10+ + +setHoverScrollState(state: boolean, callback: AsyncCallback<void>): void + +Sets the status of the mouse hover scroll switch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------------------- | +| state | boolean | Yes | Status of the mouse hover scroll switch. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.setHoverScrollState(true, (error) => { + if (error) { + console.log(`Set the mouse hover scroll failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set the mouse hover scroll success`); + }); +} catch (error) { + console.log(`Set the mouse hover scroll failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setHoverScrollState10+ + +setHoverScrollState(state: boolean): Promise<void> + +Sets the status of the mouse hover scroll switch. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| state | boolean | Yes | Status of the mouse hover scroll switch.| + +**Return value** + +| Name | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.setHoverScrollState(true).then(() => { + console.log(`Set the mouse hover scroll success`); + }); +} catch (error) { + console.log(`Set the mouse hover scroll failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getHoverScrollState10+ + +getHoverScrollState(callback: AsyncCallback<boolean>): void + +Obtains the status of the mouse hover scroll switch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.getHoverScrollState((error, state) => { + console.log(`Get the mouse hover scroll success, state: ${JSON.stringify(state)}`); + }); +} catch (error) { + console.log(`Get the mouse hover scroll failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getHoverScrollState10+ + +getHoverScrollState(): Promise<boolean> + +Obtains the status of the mouse hover scroll switch. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.getHoverScrollState().then((state) => { + console.log(`Get the mouse hover scroll success, state: ${JSON.stringify(state)}`); + }); +} catch (error) { + console.log(`Get the mouse hover scroll failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setMousePrimaryButton10+ + +setMousePrimaryButton(primary: PrimaryButton, callback: AsyncCallback<void>): void + +Sets the primary button of the mouse. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------------------- | +| primary | [PrimaryButton](#primarybutton10) | Yes | ID of the primary mouse button. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.setMousePrimaryButton(pointer.PrimaryButton.RIGHT, (error) => { + if (error) { + console.log(`Set mouse primary button failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set mouse primary button success`); + }); +} catch (error) { + console.log(`Set mouse primary button failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setMousePrimaryButton10+ + +setMousePrimaryButton(primary: PrimaryButton): Promise<void> + +Sets the primary button of the mouse. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| primary | [PrimaryButton](#primarybutton10) | Yes | ID of the primary mouse button.| + +**Return value** + +| Name | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.setMousePrimaryButton(pointer.PrimaryButton.RIGHT).then(() => { + console.log(`Set mouse primary button success`); + }); +} catch (error) { + console.log(`Set mouse primary button failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getMousePrimaryButton10+ + +getMousePrimaryButton(callback: AsyncCallback<PrimaryButton>): void + +Obtains the primary button of the mouse. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------- | +| callback | AsyncCallback<[PrimaryButton](#primarybutton10)> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.getMousePrimaryButton((error, primary) => { + console.log(`Get mouse primary button success, primary: ${JSON.stringify(primary)}`); + }); +} catch (error) { + console.log(`Get mouse primary button failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getMousePrimaryButton10+ + +getMousePrimaryButton(): Promise<PrimaryButton> + +Obtains the primary button of the mouse. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| Promise<[PrimaryButton](#primarybutton10)> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.getMousePrimaryButton().then((primary) => { + console.log(`Get mouse primary button success, primary: ${JSON.stringify(primary)}`); + }); +} catch (error) { + console.log(`Get mouse primary button failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## PrimaryButton10+ + +Type of the primary mouse button. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +| Name | Value | Description | +| -------------------------------- | ---- | ------ | +| LEFT | 0 | Left mouse button. | +| RIGHT | 1 | Right mouse button. | + +## pointer.setMouseScrollRows10+ + +setMouseScrollRows(rows: number, callback: AsyncCallback<void>): void + +Sets the number of mouse scroll rows. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------------------- | +| rows | number | Yes | Number of mouse scroll rows. The value ranges from 1 to 100. The default value is **3**. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.setMouseScrollRows(1, (error) => { + if (error) { + console.log(`setMouseScrollRows failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`setMouseScrollRows success`); + }); +} catch (error) { + console.log(`setMouseScrollRows failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setMouseScrollRows10+ + +setMouseScrollRows(rows: number): Promise<void> + +Sets the number of mouse scroll rows. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| rows | number | Yes | Number of mouse scroll rows. The value ranges from 1 to 100. The default value is **3**.| + +**Return value** + +| Name | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.setMouseScrollRows(20).then(() => { + console.log(`setMouseScrollRows success`); + }); +} catch (error) { + console.log(`setMouseScrollRows failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getMouseScrollRows10+ + +getMouseScrollRows(callback: AsyncCallback<number>): void + +Obtains the number of mouse scroll rows. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.getMouseScrollRows((error, rows) => { + console.log(`getMouseScrollRows success, rows: ${JSON.stringify(rows)}`); + }); +} catch (error) { + console.log(`getMouseScrollRows failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getMouseScrollRows10+ + +getMouseScrollRows(): Promise<number> + +Obtains the mouse movement speed. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| Promise<number> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.getMouseScrollRows().then((rows) => { + console.log(`getMouseScrollRows success, rows: ${JSON.stringify(rows)}`); + }); +} catch (error) { + console.log(`getMouseScrollRows failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + ## pointer.getPointerStyle9+ getPointerStyle(windowId: number, callback: AsyncCallback<PointerStyle>): void diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index f98e56905a7671f4b0a0cb616d6ab64c198116f7..04967480dfd6469eea02de987f0be83a71f6fc9d 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -1,4 +1,4 @@ -# @ohos.power (Power Manager) +# @ohos.power (Power Management) The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status. @@ -36,7 +36,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -72,7 +72,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -98,7 +98,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -133,7 +133,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -161,7 +161,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -193,7 +193,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -231,7 +231,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -275,7 +275,7 @@ For details about the error codes, see [Power Manager Error Codes](../errorcodes | ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 15c1fc484dd8987dd26c9229beeb200ba8a711e9..92ed924f94e29a4ca66f0176622e45817b4420b3 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -103,7 +103,7 @@ promise.then(data => { ## radio.getNetworkState -getNetworkState\(callback: AsyncCallback\): void +getNetworkState\(callback: AsyncCallback\\): void Obtains the network status. This API uses an asynchronous callback to return the result. @@ -141,7 +141,7 @@ radio.getNetworkState((err, data) => { ## radio.getNetworkState -getNetworkState\(slotId: number, callback: AsyncCallback\): void +getNetworkState\(slotId: number, callback: AsyncCallback\\): void Obtains the network status. This API uses an asynchronous callback to return the result. @@ -181,7 +181,7 @@ radio.getNetworkState(slotId, (err, data) => { ## radio.getNetworkState -getNetworkState\(slotId?: number\): Promise +getNetworkState\(slotId?: number\): Promise\ Obtains the network status. This API uses a promise to return the result. @@ -229,7 +229,7 @@ promise.then(data => { ## radio.getNetworkSelectionMode -getNetworkSelectionMode\(slotId: number, callback: AsyncCallback\): void +getNetworkSelectionMode\(slotId: number, callback: AsyncCallback\\): void Obtains the network selection mode of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -266,7 +266,7 @@ radio.getNetworkSelectionMode(slotId, (err, data) => { ## radio.getNetworkSelectionMode -getNetworkSelectionMode\(slotId: number\): Promise +getNetworkSelectionMode\(slotId: number\): Promise\ Obtains the network selection mode of the SIM card in the specified slot. This API uses a promise to return the result. @@ -311,7 +311,7 @@ promise.then(data => { ## radio.getISOCountryCodeForNetwork7+ -getISOCountryCodeForNetwork\(slotId: number, callback: AsyncCallback\): void +getISOCountryCodeForNetwork\(slotId: number, callback: AsyncCallback\\): void Obtains the ISO country code of the network with which the SIM card in the specified slot is registered. This API uses an asynchronous callback to return the result. @@ -348,7 +348,7 @@ radio.getISOCountryCodeForNetwork(slotId, (err, data) => { ## radio.getISOCountryCodeForNetwork7+ -getISOCountryCodeForNetwork\(slotId: number\): Promise +getISOCountryCodeForNetwork\(slotId: number\): Promise\ Obtains the ISO country code of the network with which the SIM card in the specified slot is registered. This API uses a promise to return the result. @@ -403,7 +403,7 @@ Obtains the ID of the slot in which the primary card is located. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -445,7 +445,6 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | -| 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -464,7 +463,7 @@ promise.then(data => { ## radio.getSignalInformation7+ -getSignalInformation\(slotId: number, callback: AsyncCallback\>\): void +getSignalInformation\(slotId: number, callback: AsyncCallback\\>\): void Obtains a list of signal strengths of the network with which the SIM card in the specified slot is registered. This API uses an asynchronous callback to return the result. @@ -501,7 +500,7 @@ radio.getSignalInformation(slotId, (err, data) => { ## radio.getSignalInformation7+ -getSignalInformation\(slotId: number\): Promise\> +getSignalInformation\(slotId: number\): Promise\\> Obtains a list of signal strengths of the network with which the SIM card in the specified slot is registered. This API uses a promise to return the result. @@ -654,7 +653,7 @@ console.log("Result: "+ result); ## radio.isRadioOn7+ -isRadioOn\(callback: AsyncCallback\): void +isRadioOn\(callback: AsyncCallback\\): void Checks whether the radio service is enabled on the primary SIM card. This API uses an asynchronous callback to return the result. @@ -692,7 +691,7 @@ radio.isRadioOn((err, data) => { ## radio.isRadioOn7+ -isRadioOn\(slotId: number, callback: AsyncCallback\): void +isRadioOn\(slotId: number, callback: AsyncCallback\\): void Checks whether the radio service is enabled on the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -732,7 +731,7 @@ radio.isRadioOn(slotId, (err, data) => { ## radio.isRadioOn7+ -isRadioOn\(slotId?: number\): Promise +isRadioOn\(slotId?: number\): Promise\ Checks whether the radio service is enabled on the SIM card in the specified slot. This API uses a promise to return the result. @@ -780,7 +779,7 @@ promise.then(data => { ## radio.getOperatorName7+ -getOperatorName\(slotId: number, callback: AsyncCallback\): void +getOperatorName\(slotId: number, callback: AsyncCallback\\): void Obtains the carrier name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -817,7 +816,7 @@ radio.getOperatorName(slotId, (err, data) => { ## radio.getOperatorName7+ -getOperatorName\(slotId: number\): Promise +getOperatorName\(slotId: number\): Promise\ Obtains the carrier name for the SIM card in the specified slot. This API uses a promise to return the result. @@ -861,7 +860,7 @@ promise.then(data => { ## radio.setPrimarySlotId8+ -setPrimarySlotId(slotId: number, callback: AsyncCallback): void +setPrimarySlotId\(slotId: number, callback: AsyncCallback\\): void Sets the ID of the slot in which the primary card is located. This API uses an asynchronous callback to return the result. @@ -885,6 +884,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -933,6 +933,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -954,7 +955,7 @@ promise.then(() => { ## radio.getIMEI8+ -getIMEI(callback: AsyncCallback): void +getIMEI\(callback: AsyncCallback\\): void Obtains the IMEI of the SIM card in a card slot. This API uses an asynchronous callback to return the result. @@ -977,6 +978,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -994,9 +996,9 @@ radio.getIMEI((err, data) => { ## radio.getIMEI8+ -getIMEI(slotId: number, callback: AsyncCallback): void +getIMEI\(slotId: number, callback: AsyncCallback\\): void -Obtains the IMEI of the SIM card in the specified card slot. This API uses an asynchronous callback to return the result. +Obtains the IMEI of the SIM card in a card slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1018,6 +1020,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1036,7 +1039,7 @@ radio.getIMEI(slotId, (err, data) => { ## radio.getIMEI8+ -getIMEI(slotId?: number): Promise +getIMEI\(slotId?: number\): Promise\ Obtains the IMEI of the SIM card in the specified card slot. This API uses a promise to return the result. @@ -1065,6 +1068,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1085,7 +1089,7 @@ promise.then(data => { ## radio.getMEID8+ -getMEID(callback: AsyncCallback): void +getMEID\(callback: AsyncCallback\\): void Obtains the MEID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. @@ -1108,6 +1112,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1125,9 +1130,9 @@ radio.getMEID((err, data) => { ## radio.getMEID8+ -getMEID(slotId: number, callback: AsyncCallback): void +getMEID\(slotId: number, callback: AsyncCallback\\): void -Obtains the MEID of the SIM card in the specified card slot. This API uses an asynchronous callback to return the result. +Obtains the MEID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1149,6 +1154,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1167,7 +1173,7 @@ radio.getMEID(slotId, (err, data) => { ## radio.getMEID8+ -getMEID(slotId?: number): Promise +getMEID\(slotId?: number\): Promise\ Obtains the MEID of the SIM card in the specified card slot. This API uses a promise to return the result. @@ -1196,6 +1202,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1216,7 +1223,7 @@ promise.then(data => { ## radio.getUniqueDeviceId8+ -getUniqueDeviceId(callback: AsyncCallback): void +getUniqueDeviceId\(callback: AsyncCallback\\): void Obtains the unique device ID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. @@ -1239,6 +1246,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1256,9 +1264,9 @@ radio.getUniqueDeviceId((err, data) => { ## radio.getUniqueDeviceId8+ -getUniqueDeviceId(slotId: number, callback: AsyncCallback): void +getUniqueDeviceId\(slotId: number, callback: AsyncCallback\\): void -Obtains the unique device ID of the SIM card in the specified card slot. This API uses an asynchronous callback to return the result. +Obtains the unique device ID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1280,6 +1288,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1298,7 +1307,7 @@ radio.getUniqueDeviceId(slotId, (err, data) => { ## radio.getUniqueDeviceId8+ -getUniqueDeviceId(slotId?: number): Promise +getUniqueDeviceId\(slotId?: number\): Promise\ Obtains the unique device ID of the SIM card in the specified card slot. This API uses a promise to return the result. @@ -1327,6 +1336,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1347,7 +1357,7 @@ promise.then(data => { ## radio.sendUpdateCellLocationRequest8+ -sendUpdateCellLocationRequest\(callback: AsyncCallback\): void +sendUpdateCellLocationRequest\(callback: AsyncCallback\\): void Sends a cell location update request. This API uses an asynchronous callback to return the result. @@ -1370,6 +1380,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1386,7 +1397,7 @@ radio.sendUpdateCellLocationRequest((err) => { ## radio.sendUpdateCellLocationRequest8+ -sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback\): void +sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback\\): void Sends a cell location update request for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1410,6 +1421,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1427,7 +1439,7 @@ radio.sendUpdateCellLocationRequest(slotId, (err) => { ## radio.sendUpdateCellLocationRequest8+ -sendUpdateCellLocationRequest\(slotId?: number): Promise +sendUpdateCellLocationRequest\(slotId?: number\): Promise\ Sends a cell location update request for the SIM card in the specified slot. This API uses a promise to return the result. @@ -1456,6 +1468,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1475,7 +1488,7 @@ radio.sendUpdateCellLocationRequest(slotId).then(() => { ## radio.getCellInformation8+ -getCellInformation(callback: AsyncCallback>): void +getCellInformation\(callback: AsyncCallback\\>\): void Obtains cell information. This API uses an asynchronous callback to return the result. @@ -1498,6 +1511,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1515,7 +1529,7 @@ radio.getCellInformation((err, data) => { ## radio.getCellInformation8+ -getCellInformation(slotId: number, callback: AsyncCallback\>): void +getCellInformation\(slotId: number, callback: AsyncCallback\\>\): void Obtains cell information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1539,6 +1553,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1557,7 +1572,7 @@ radio.getCellInformation(slotId, (err, data) => { ## radio.getCellInformation8+ -getCellInformation(slotId?: number): Promise\> +getCellInformation\(slotId?: number\): Promise\\> Obtains cell information for the SIM card in the specified slot. This API uses a promise to return the result. @@ -1586,6 +1601,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1606,7 +1622,7 @@ promise.then(data => { ## radio.setNetworkSelectionMode -setNetworkSelectionMode\(options: NetworkSelectionModeOptions, callback: AsyncCallback\): void +setNetworkSelectionMode\(options: NetworkSelectionModeOptions, callback: AsyncCallback\\): void Sets the network selection mode. This API uses an asynchronous callback to return the result. @@ -1630,6 +1646,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1658,7 +1675,7 @@ radio.setNetworkSelectionMode(networkSelectionModeOptions, (err) => { ## radio.setNetworkSelectionMode -setNetworkSelectionMode\(options: NetworkSelectionModeOptions\): Promise +setNetworkSelectionMode\(options: NetworkSelectionModeOptions\): Promise\ Sets the network selection mode. This API uses a promise to return the result. @@ -1687,6 +1704,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1718,7 +1736,7 @@ promise.then(() => { ## radio.getNetworkSearchInformation -getNetworkSearchInformation\(slotId: number, callback: AsyncCallback\): void +getNetworkSearchInformation\(slotId: number, callback: AsyncCallback\\): void Obtains network search information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1742,6 +1760,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1758,7 +1777,7 @@ radio.getNetworkSearchInformation(0, (err, data) => { ## radio.getNetworkSearchInformation -getNetworkSearchInformation\(slotId: number\): Promise +getNetworkSearchInformation\(slotId: number\): Promise\ Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result. @@ -1787,6 +1806,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1806,7 +1826,7 @@ promise.then(data => { ## radio.getNrOptionMode8+ -getNrOptionMode(callback: AsyncCallback): void +getNrOptionMode\(callback: AsyncCallback\\): void Obtains the NR option mode. This API uses an asynchronous callback to return the result. @@ -1826,6 +1846,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1843,7 +1864,7 @@ radio.getNrOptionMode((err, data) => { ## radio.getNrOptionMode8+ -getNrOptionMode(slotId: number, callback: AsyncCallback): void +getNrOptionMode\(slotId: number, callback: AsyncCallback\\): void Obtains the NR option mode for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1864,6 +1885,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1882,7 +1904,7 @@ radio.getNrOptionMode(slotId, (err, data) => { ## radio.getNrOptionMode8+ -getNrOptionMode(slotId?: number): Promise +getNrOptionMode\(slotId?: number\): Promise\ Obtains the NR option mode for the SIM card in the specified slot. This API uses a promise to return the result. @@ -1908,6 +1930,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1928,7 +1951,7 @@ promise.then(data => { ## radio.turnOnRadio7+ -turnOnRadio(callback: AsyncCallback): void +turnOnRadio\(callback: AsyncCallback\\): void Turns on the radio function. This API uses an asynchronous callback to return the result. @@ -1951,6 +1974,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1968,7 +1992,7 @@ radio.turnOnRadio((err) => { ## radio.turnOnRadio7+ -turnOnRadio(slotId: number, callback: AsyncCallback): void +turnOnRadio\(slotId: number, callback: AsyncCallback\\): void Turns on the radio function for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1992,6 +2016,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2010,7 +2035,7 @@ radio.turnOnRadio(slotId, (err) => { ## radio.turnOnRadio7+ -turnOnRadio(slotId?: number): Promise +turnOnRadio(slotId?: number): Promise\ Turns on the radio function for the SIM card in the specified slot. This API uses a promise to return the result. @@ -2039,6 +2064,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2058,7 +2084,7 @@ radio.turnOnRadio(slotId).then(() => { ## radio.turnOffRadio7+ -turnOffRadio(callback: AsyncCallback): void +turnOffRadio\(callback: AsyncCallback\\): void Turns off the radio function. This API uses an asynchronous callback to return the result. @@ -2081,6 +2107,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2098,7 +2125,7 @@ radio.turnOffRadio((err) => { ## radio.turnOffRadio7+ -turnOffRadio(slotId: number, callback: AsyncCallback): void +turnOffRadio\(slotId: number, callback: AsyncCallback\\): void Turns off the radio function for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2122,6 +2149,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2140,7 +2168,7 @@ radio.turnOffRadio(slotId, (err) => { ## radio.turnOffRadio7+ -turnOffRadio(slotId?: number): Promise +turnOffRadio\(slotId?: number\): Promise\ Turns off the radio function for the SIM card in the specified slot. This API uses a promise to return the result. @@ -2169,6 +2197,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2188,7 +2217,7 @@ radio.turnOffRadio(slotId).then(() => { ## radio.setPreferredNetwork8+ -setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback: AsyncCallback\): void +setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback: AsyncCallback\\): void Sets the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2213,6 +2242,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2230,7 +2260,7 @@ radio.setPreferredNetwork(slotId, radio.PreferredNetworkMode.PREFERRED_NETWORK_M ## radio.setPreferredNetwork8+ -setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise +setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode\): Promise\ Sets the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. @@ -2260,6 +2290,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2279,7 +2310,7 @@ radio.setPreferredNetwork(slotId, radio.PreferredNetworkMode.PREFERRED_NETWORK_M ## radio.getPreferredNetwork8+ -getPreferredNetwork\(slotId: number, callback: AsyncCallback\): void +getPreferredNetwork\(slotId: number, callback: AsyncCallback\\): void Obtains the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2303,6 +2334,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2319,7 +2351,7 @@ radio.getPreferredNetwork(0, (err, data) => { ## radio.getPreferredNetwork8+ -getPreferredNetwork(slotId: number): Promise +getPreferredNetwork\(slotId: number\): Promise\ Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. @@ -2348,6 +2380,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2367,7 +2400,7 @@ promise.then(data => { ## radio.getImsRegInfo9+ -getImsRegInfo(slotId: number, imsType: ImsServiceType, callback: AsyncCallback): void +getImsRegInfo\(slotId: number, imsType: ImsServiceType, callback: AsyncCallback\\): void Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2392,6 +2425,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2408,7 +2442,7 @@ radio.getImsRegInfo(0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { ## radio.getImsRegInfo9+ -getImsRegInfo(slotId: number, imsType: ImsServiceType): Promise +getImsRegInfo\(slotId: number, imsType: ImsServiceType\): Promise\ Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses a promise to return the result. @@ -2438,6 +2472,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2457,7 +2492,7 @@ promise.then(data => { ## radio.on('imsRegStateChange')9+ -on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback): void +on\(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback\\): void Enables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result. @@ -2483,6 +2518,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2499,7 +2535,7 @@ radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { ## radio.off('imsRegStateChange')9+ -off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback): void +off\(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback\\): void Disables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result. @@ -2516,7 +2552,7 @@ Disables listening for **imsRegStateChange** events. This API uses an asynchrono | type | string | Yes | IMS registration status changes. | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | imsType | [ImsServiceType](#imsservicetype9) | Yes | IMS service type. | -| callback | Callback<[ImsRegInfo](#imsreginfo9)> | No | Callback used to return the result. | +| callback | Callback<[ImsRegInfo](#imsreginfo9)> | No | Callback used to return the result. If this parameter is not set, the API unsubscribes from all callbacks.| **Error codes** @@ -2525,6 +2561,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2539,6 +2576,101 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { }); ``` + +## radio.getBasebandVersion10+ + +getBasebandVersion\(slotId: number, callback: AsyncCallback\\): void + +Obtains the baseband version of the device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. Baseband version of the device. | + +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +let slotId = 0; +radio.getBasebandVersion(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getBasebandVersion10+ + +getBasebandVersion\(slotId: number\): Promise\ + +Obtains the baseband version of the device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------------- | +| Promise\ | Promise used to return the result. | + +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**Example** + +```js +let slotId = 0; +let promise = radio.getBasebandVersion(slotId); +promise.then(data => { + console.log(`getBasebandVersion success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getBasebandVersion failed, promise: err->${JSON.stringify(err)}`); +}); +``` + + ## RadioTechnology Enumerates radio access technologies. diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 9c1e9746617d53afee221b0ad0f9f98bf4900084..75499d3809a14edf61ea350f5cf8c539e0408a38 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -14,13 +14,6 @@ The **request** module provides applications with basic upload, download, and ba import request from '@ohos.request'; ``` - -## Constraints - -Only HTTP requests are supported. HTTPS requests are not supported. - -The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **Content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')7+](#onfail7). - ## Constants **Required permissions**: ohos.permission.INTERNET @@ -36,7 +29,7 @@ You can set **networkType** in [DownloadConfig](#downloadconfig) to specify the | NETWORK_WIFI | number | 0x00010000 | Whether download is allowed on a WLAN.| ### Download Error Codes -The table below lists the error codes that may be returned by [on('fail')7+](#onfail7)/[off('fail')7+](#offfail7)/[getTaskInfo9+](#gettaskinfo9). +The table below lists the values of **err** in the callback of [on('fail')7+](#onfail7) and the values of **failedReason** returned by [getTaskInfo9+](#gettaskinfo9). | Name| Type| Value| Description| | -------- | -------- | -------- | -------- | @@ -54,7 +47,7 @@ The table below lists the error codes that may be returned by [on('fail')7+ ### Causes of Download Pause -The table below lists the causes of download pause that may be returned by [getTaskInfo9+](#gettaskinfo9). +The table below lists the values of **pausedReason** returned by [getTaskInfo9+](#gettaskinfo9). | Name| Type| Value| Description| | -------- | -------- | -------- | -------- | @@ -65,7 +58,7 @@ The table below lists the causes of download pause that may be returned by [getT | PAUSED_UNKNOWN7+ | number | 4 | Download paused due to unknown reasons.| ### Download Task Status Codes -The table below lists the download task status codes that may be returned by [getTaskInfo9+](#gettaskinfo9). +The table below lists the values of **status** returned by [getTaskInfo9+](#gettaskinfo9). | Name| Type| Value| Description| | -------- | -------- | -------- | -------- | @@ -105,7 +98,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro | ID| Error Message| | -------- | -------- | -| 13400002 | Bad file path. | +| 13400002 | bad file path. | **Example** @@ -153,7 +146,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro | ID| Error Message| | -------- | -------- | -| 13400002 | Bad file path. | +| 13400002 | bad file path. | **Example** @@ -279,7 +272,7 @@ Implements file uploads. Before using any APIs of this class, you must obtain an on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void -Subscribes to an upload event. This API uses an asynchronous callback to return the result. +Subscribes to upload progress events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -302,10 +295,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Example** ```js - uploadTask.on('progress', function callback(uploadedSize, totalSize) { + let upProgressCallback = (uploadedSize, totalSize) => { console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); - } - ); + }; + uploadTask.on('progress', upProgressCallback); ``` @@ -313,7 +306,7 @@ Subscribes to an upload event. This API uses an asynchronous callback to return on(type: 'headerReceive', callback: (header: object) => void): void -Subscribes to an upload event. This API uses an asynchronous callback to return the result. +Subscribes to HTTP header events for an upload task. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -335,10 +328,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Example** ```js - uploadTask.on('headerReceive', function callback(headers){ + let headerCallback = (headers) => { console.info("upOnHeader headers:" + JSON.stringify(headers)); - } - ); + }; + uploadTask.on('headerReceive', headerCallback); ``` @@ -346,7 +339,7 @@ Subscribes to an upload event. This API uses an asynchronous callback to return on(type:'complete' | 'fail', callback: Callback<Array<TaskState>>): void; -Subscribes to an upload event. This API uses an asynchronous callback to return the result. +Subscribes to upload completion or failure events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -368,19 +361,19 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Example** ```js - uploadTask.on('complete', function callback(taskStates) { + let upCompleteCallback = (taskStates) => { for (let i = 0; i < taskStates.length; i++ ) { - console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); + console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); } - } - ); + }; + uploadTask.on('complete', upCompleteCallback); - uploadTask.on('fail', function callback(taskStates) { + let upFailCallback = (taskStates) => { for (let i = 0; i < taskStates.length; i++ ) { console.info("upOnFail taskState:" + JSON.stringify(taskStates[i])); } - } - ); + }; + uploadTask.on('fail', upFailCallback); ``` @@ -388,7 +381,7 @@ Subscribes to an upload event. This API uses an asynchronous callback to return off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void -Unsubscribes from an upload event. This API uses an asynchronous callback to return the result. +Unsubscribes from upload progress events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -399,22 +392,15 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| -| callback | function | No| Callback for the upload progress event.| - - Parameters of the callback function - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| -| totalSize | number | Yes| Total size of the files to upload, in bytes.| +| callback | function | No| Callback used to return the result.
**uploadedSize**: size of the uploaded files, in bytes.
**totalSize**: Total size of the files to upload, in bytes. | **Example** ```js - uploadTask.off('progress', function callback(uploadedSize, totalSize) { - console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize); - } - ); + let upProgressCallback = (uploadedSize, totalSize) => { + console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); + }; + uploadTask.off('progress', upProgressCallback); ``` @@ -422,7 +408,7 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret off(type: 'headerReceive', callback?: (header: object) => void): void -Unsubscribes from an upload event. This API uses an asynchronous callback to return the result. +Unsubscribes from HTTP header events for an upload task. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -433,28 +419,22 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| -| callback | function | No| Callback for the HTTP Response Header event.| - - Parameters of the callback function - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| header | object | Yes| HTTP Response Header.| +| callback | function | No| Callback used to return the result.
**header**: HTTP response header.| **Example** ```js - uploadTask.off('headerReceive', function callback(headers) { - console.info("upOnHeader headers:" + JSON.stringify(headers)); - } - ); + let headerCallback = (header) => { + console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); + }; + uploadTask.off('headerReceive', headerCallback); ``` ### off('complete' | 'fail')9+ off(type:'complete' | 'fail', callback?: Callback<Array<TaskState>>): void; -Unsubscribes from an upload event. This API uses an asynchronous callback to return the result. +Unsubscribes from upload completion or failure events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -465,30 +445,26 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| -| callback | Callback<Array<TaskState>> | No| Callback used to return the result.| - - Parameters of the callback function - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| +| callback | Callback<Array<TaskState>> | No| Callback used to return the result.
**taskstates**: upload task result.| **Example** ```js - uploadTask.off('complete', function callback(taskStates) { + let upCompleteCallback = (taskStates) => { + console.info('Upload delete complete notification.'); for (let i = 0; i < taskStates.length; i++ ) { - console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); + console.info('taskState:' + JSON.stringify(taskStates[i])); } - } - ); + }; + uploadTask.off('complete', upCompleteCallback); - uploadTask.off('fail', function callback(taskStates) { + let upFailCallback = (taskStates) => { + console.info('Upload delete fail notification.'); for (let i = 0; i < taskStates.length; i++ ) { - console.info("upOnFail taskState:" + JSON.stringify(taskStates[i])); + console.info('taskState:' + JSON.stringify(taskStates[i])); } - } - ); + }; + uploadTask.off('fail', upFailCallback); ``` ### delete9+ @@ -709,9 +685,9 @@ For details about the error codes, see [Upload and Download Error Codes](../erro | ID| Error Message| | -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | +| 13400001 | file operation error. | +| 13400002 | bad file path. | +| 13400003 | task manager service error. | **Example** @@ -753,9 +729,9 @@ For details about the error codes, see [Upload and Download Error Codes](../erro | ID| Error Message| | -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | +| 13400001 | file operation error. | +| 13400002 | bad file path. | +| 13400003 | task manager service error. | **Example** @@ -861,7 +837,7 @@ Implements file downloads. Before using any APIs of this class, you must obtain on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void -Subscribes to a download event. This API uses an asynchronous callback to return the result. +Subscribes to download progress events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -872,7 +848,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| -| callback | function | Yes| Callback for the download progress event.| +| callback | function | Yes| Callback used to return the result.| Parameters of the callback function @@ -884,10 +860,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Example** ```js - downloadTask.on('progress', function download_callback(receivedSize, totalSize) { + let progresCallback = (receivedSize, totalSize) => { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); - } - ); + }; + downloadTask.on('progress', progresCallback); ``` @@ -895,7 +871,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void -Unsubscribes from a download event. This API uses an asynchronous callback to return the result. +Unsubscribes from download progress events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -906,22 +882,15 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| -| callback | function | No| Callback for the download progress event.| - - Parameters of the callback function - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| receivedSize | number | Yes| Size of the downloaded files, in bytes.| -| totalSize | number | Yes| Total size of the files to download, in bytes.| +| callback | function | No| Callback used to return the result.
**receivedSize**: size of the downloaded files.
**totalSize**: total size of the files to download.| **Example** ```js - downloadTask .off('progress', function download_callback(receivedSize, totalSize) { - console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); - } - ); + let progresCallback = (receivedSize, totalSize) => { + console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); + }; + downloadTask.off('progress', progresCallback); ``` @@ -929,7 +898,7 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re on(type: 'complete'|'pause'|'remove', callback:() => void): void -Subscribes to a download event. This API uses an asynchronous callback to return the result. +Subscribes to download events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -945,10 +914,20 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Example** ```js - downloadTask.on('complete', function callback() { + let completeCallback = () => { console.info('Download task completed.'); - } - ); + }; + downloadTask.on('complete', completeCallback); + + let pauseCallback = () => { + console.info('Download task pause.'); + }; + downloadTask.on('pause', pauseCallback); + + let removeCallback = () => { + console.info('Download task remove.'); + }; + downloadTask.on('remove', removeCallback); ``` @@ -956,7 +935,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return off(type: 'complete'|'pause'|'remove', callback?:() => void): void -Unsubscribes from a download event. This API uses an asynchronous callback to return the result. +Unsubscribes from download events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -972,10 +951,20 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re **Example** ```js - downloadTask.off('complete', function callback() { - console.info('Download task completed.'); - } - ); + let completeCallback = () => { + console.info('Download delete complete notification.'); + }; + downloadTask.off('complete', completeCallback); + + let pauseCallback = () => { + console.info('Download delete pause notification.'); + }; + downloadTask.off('pause', pauseCallback); + + let removeCallback = () => { + console.info('Download delete remove notification.'); + }; + downloadTask.off('remove', removeCallback); ``` @@ -983,7 +972,7 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re on(type: 'fail', callback: (err: number) => void): void -Subscribes to the download task failure event. This API uses an asynchronous callback to return the result. +Subscribes to download failure events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -1004,11 +993,11 @@ Subscribes to the download task failure event. This API uses an asynchronous cal **Example** - ```js - downloadTask.on('fail', function callBack(err) { + ```js + let failCallback = (err) => { console.info('Download task failed. Cause:' + err); - } - ); + }; + downloadTask.on('fail', failCallback); ``` @@ -1016,7 +1005,7 @@ Subscribes to the download task failure event. This API uses an asynchronous cal off(type: 'fail', callback?: (err: number) => void): void -Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. +Unsubscribes from download failure events. This API uses a callback to return the result synchronously. **Required permissions**: ohos.permission.INTERNET @@ -1027,21 +1016,15 @@ Unsubscribes from the download task failure event. This API uses an asynchronous | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| -| callback | function | No| Callback for the download task failure event.| - - Parameters of the callback function - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| err | number | Yes| Error code of the download failure. For details about the error codes, see [Download Error Codes](#download-error-codes).| +| callback | function | No| Callback used to return the result.
**err**: error code of the download failure. | **Example** ```js - downloadTask.off('fail', function callBack(err) { - console.info('Download task failed. Cause:' + err); - } - ); + let failCallback = (err) => { + console.info(`Download delete fail notification. err: ${err.message}`); + }; + downloadTask.off('fail', failCallback); ``` ### delete9+ @@ -1403,7 +1386,7 @@ Removes this download task. This API uses an asynchronous callback to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result. | **Example** @@ -1706,33 +1689,33 @@ Defines the download task configuration. | -------- | -------- | -------- | -------- | | url | string | Yes| Resource URL.| | header | Object | No| HTTPS flag header to be included in the download request.
The **X-TLS-Version** parameter in **header** specifies the TLS version to be used. If this parameter is not set, the CURL_SSLVERSION_TLSv1_2 version is used. Available options are as follows:
CURL_SSLVERSION_TLSv1_0
CURL_SSLVERSION_TLSv1_1
CURL_SSLVERSION_TLSv1_2
CURL_SSLVERSION_TLSv1_3
The **X-Cipher-List** parameter in **header** specifies the cipher suite list to be used. If this parameter is not specified, the secure cipher suite list is used. Available options are as follows:
- The TLS 1.2 cipher suite list includes the following ciphers:
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,
TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,
TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,
TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
- The TLS 1.3 cipher suite list includes the following ciphers:
TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256
- The TLS 1.3 cipher suite list adds the Chinese national cryptographic algorithm:
TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3 | -| enableMetered | boolean | No| Whether download is allowed on a metered connection.
- **true**: allowed
- **false**: not allowed| -| enableRoaming | boolean | No| Whether download is allowed on a roaming network.
- **true**: allowed
- **false**: not allowed| +| enableMetered | boolean | No| Whether download is allowed on a metered connection. The default value is **false**. In general cases, a mobile data connection is metered, while a Wi-Fi connection is not.
- **true**: allowed
- **false**: not allowed| +| enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.
- **true**: allowed
- **false**: not allowed| | description | string | No| Description of the download session.| -| filePath7+ | string | No| Path where the downloaded file is stored.
- filePath:'/data/storage/el2/base/haps/entry/files/test.txt': Save the file to an absolute path.
- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.
- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.| -| networkType | number | No| Network type allowed for download.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| +| filePath7+ | string | No| Path where the downloaded file is stored.
- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.
- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.| +| networkType | number | No| Network type allowed for download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| | title | string | No| Download task name.| -| background9+ | boolean | No| Whether to enable the background task notification. When this parameter is enabled, the download status is displayed in the notification panel.| +| background9+ | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.| ## DownloadInfo7+ -Defines the download task information, which is the callback parameter of the [query(deprecated)](#querydeprecated-1) API. +Defines the download task information, which is the callback parameter of the [getTaskInfo9+](#gettaskinfo9) API. **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| downloadId | number | Yes| ID of the downloaded file.| -| failedReason | number | No| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| -| fileName | string | Yes| Name of the downloaded file.| -| filePath | string | Yes| URI of the saved file.| -| pausedReason | number | No| Cause of download pause. The value can be any constant in [Causes of Download Pause](#causes-of-download-pause).| -| status | number | Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#download-task-status-codes).| -| targetURI | string | Yes| URI of the downloaded file.| -| downloadTitle | string | Yes| Download task name.| -| downloadTotalBytes | number | Yes| Total size of the files to download, in bytes.| -| description | string | Yes| Description of the file to download.| -| downloadedBytes | number | Yes| Size of the files downloaded, in bytes.| - \ No newline at end of file +| Name| Type|Mandatory| Description| +| -------- | ------ |---------------- | +| downloadId | number |Yes| ID of the download task.| +| failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| +| fileName | string |Yes| Name of the downloaded file.| +| filePath | string |Yes| URI of the saved file.| +| pausedReason | number |Yes| Cause of download pause. The value can be any constant in [Causes of Download Pause](#causes-of-download-pause).| +| status | number |Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#download-task-status-codes).| +| targetURI | string |Yes| URI of the downloaded file.| +| downloadTitle | string |Yes| Name of the download task.| +| downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.| +| description | string |Yes| Description of the download task.| +| downloadedBytes | number |Yes| Size of the files downloaded, in bytes.| + diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 76d9a3456aaa7c24beb2f57aee57e6106f4957fa..a1b98717279f99d9e15c5018fcf41bb28d30c6a5 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,6 +1,6 @@ # @ohos.resourceManager (Resource Manager) -The Resource Manager module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density. +The **resourceManager** module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density. > **NOTE** > @@ -13,7 +13,7 @@ The Resource Manager module provides APIs to obtain information about applicatio import resourceManager from '@ohos.resourceManager'; ``` -## Instruction +## How to Use Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object. For details about how to reference context in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). @@ -171,12 +171,12 @@ Enumerates the device types. | Name | Value | Description | | -------------------- | ---- | ---- | -| DEVICE_TYPE_PHONE | 0x00 | Phone | -| DEVICE_TYPE_TABLET | 0x01 | Tablet | -| DEVICE_TYPE_CAR | 0x02 | Head unit | -| DEVICE_TYPE_PC | 0x03 | PC | -| DEVICE_TYPE_TV | 0x04 | TV | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable | +| DEVICE_TYPE_PHONE | 0x00 | Phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Head unit. | +| DEVICE_TYPE_PC | 0x03 | PC. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -253,7 +253,7 @@ Defines the descriptor of the raw file. | Name | Type | Readable | Writable | Description | | ------ | ------ | ---- | ---- | ------------------ | -| fd | number | Yes | No| Descriptor of the raw file.| +| fd | number | Yes | No| File descriptor of the HAP where the raw file is located.| | offset | number | Yes | No| Start offset of the raw file. | | length | number | Yes | No| Length of the raw file. | @@ -278,7 +278,7 @@ Defines the capability of accessing application resources. > **NOTE** > -> - The APIs involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. +> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. > > - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**. @@ -343,10 +343,10 @@ Obtains the string corresponding to the specified resource ID. This API uses a p | --------------------- | ----------- | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -382,10 +382,10 @@ Obtains the string corresponding to the specified resource object. This API uses | resource | [Resource](#resource9) | Yes | Resource object. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -434,10 +434,10 @@ Obtains the string corresponding to the specified resource object. This API uses | --------------------- | ---------------- | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -478,10 +478,10 @@ Obtains the string array corresponding to the specified resource ID. This API us | resId | number | Yes | Resource ID. | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -524,10 +524,10 @@ Obtains the string array corresponding to the specified resource ID. This API us | ---------------------------------- | ------------- | | Promise<Array<string>> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -562,10 +562,10 @@ Obtains the string array corresponding to the specified resource object. This AP | resource | [Resource](#resource9) | Yes | Resource object. | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -612,10 +612,10 @@ Obtains the string array corresponding to the specified resource object. This AP | ---------------------------------- | ------------------ | | Promise<Array<string>> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -640,7 +640,6 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` - ### getMediaContent9+ getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void @@ -656,10 +655,10 @@ Obtains the content of the media file corresponding to the specified resource ID | resId | number | Yes | Resource ID. | | callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -680,6 +679,45 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaContent10+ + +getMediaContent(resId: number, density: number, callback: AsyncCallback<Uint8Array>): void + +Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | Yes | Resource ID. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaContent($r('app.media.test').id, 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` ### getMediaContent9+ @@ -701,10 +739,10 @@ Obtains the content of the media file corresponding to the specified resource ID | ------------------------- | -------------- | | Promise<Uint8Array> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -723,6 +761,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaContent10+ + +getMediaContent(resId: number, density: number): Promise<Uint8Array> + +Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getMediaContent9+ getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): void @@ -738,10 +819,10 @@ Obtains the content of the media file corresponding to the specified resource ob | resource | [Resource](#resource9) | Yes | Resource object. | | callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -767,6 +848,51 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaContent10+ + +getMediaContent(resource: Resource, density: number, callback: AsyncCallback<Uint8Array>): void + +Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resource | [Resource](#resource9) | Yes | Resource object. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; + try { + this.context.resourceManager.getMediaContent(resource, 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getMediaContent9+ getMediaContent(resource: Resource): Promise<Uint8Array> @@ -787,10 +913,10 @@ Obtains the content of the media file corresponding to the specified resource ob | ------------------------- | ------------------- | | Promise<Uint8Array> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -814,6 +940,53 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaContent10+ + +getMediaContent(resource: Resource, density: number): Promise<Uint8Array> + +Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------- | +| Promise<Uint8Array> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; + try { + this.context.resourceManager.getMediaContent(resource, 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` ### getMediaContentBase649+ @@ -830,10 +1003,10 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. | resId | number | Yes | Resource ID. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -854,6 +1027,45 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaContentBase6410+ + +getMediaContentBase64(resId: number, density: number, callback: AsyncCallback<string>): void + +Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | Yes | Resource ID. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` ### getMediaContentBase649+ @@ -875,10 +1087,10 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. | --------------------- | -------------------- | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -894,7 +1106,50 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco }); } catch (error) { console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) - } + } + ``` + +### getMediaContentBase6410+ + +getMediaContentBase64(resId: number, density: number): Promise<string> + +Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } ``` ### getMediaContentBase649+ @@ -912,10 +1167,10 @@ Obtains the Base64 code of the image corresponding to the specified resource obj | resource | [Resource](#resource9) | Yes | Resource object. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -941,6 +1196,51 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaContentBase6410+ + +getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback<string>): void + +Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resource | [Resource](#resource9) | Yes | Resource object. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; + try { + this.context.resourceManager.getMediaContentBase64(resource, 120, (error, value) => { + if (error != null) { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getMediaContentBase649+ getMediaContentBase64(resource: Resource): Promise<string> @@ -961,10 +1261,10 @@ Obtains the Base64 code of the image corresponding to the specified resource obj | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -988,6 +1288,53 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaContentBase6410+ + +getMediaContentBase64(resource: Resource, density: number): Promise<string> + +Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; + try { + this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` ### getConfiguration @@ -1117,10 +1464,10 @@ Obtains the singular-plural string corresponding to the specified resource ID ba | num | number | Yes | Number. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -1164,10 +1511,10 @@ Obtains the singular-plural string corresponding to the specified resource ID ba | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -1203,10 +1550,10 @@ Obtains the singular-plural string corresponding to the specified resource objec | num | number | Yes | Number. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -1255,10 +1602,10 @@ Obtains the singular-plural string corresponding to the specified resource objec | --------------------- | ------------------------------ | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -1299,10 +1646,10 @@ Obtains the content of the raw file in the **resources/rawfile** directory. This | path | string | Yes | Path of the raw file. | | callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001005 | If the resource not found by path. | @@ -1343,10 +1690,10 @@ Obtains the content of the raw file in the **resources/rawfile** directory. This | ------------------------- | ----------- | | Promise<Uint8Array> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001005 | If the resource not found by path. | @@ -1380,10 +1727,10 @@ Obtains the descriptor of the raw file in the **resources/rawfile** directory. T | path | string | Yes | Path of the raw file. | | callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001005 | If the resource not found by path. | @@ -1425,10 +1772,10 @@ Obtains the descriptor of the raw file in the **resources/rawfile** directory. T | ---------------------------------------- | ------------------- | | Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001005 | If the resource not found by path. | @@ -1448,6 +1795,86 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco }; ``` +### getRawFileList10+ + +getRawFileList(path: string, callback: AsyncCallback<Array\>): void; + +Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the **rawfile** folder. | +| callback | AsyncCallback<Array\> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { // Passing "" means to obtain the list of files in the root directory of the raw file. + this.context.resourceManager.getRawFileList("", (error, value) => { + if (error != null) { + console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`) + } else { + let rawFile = value; + } + }); + } catch (error) { + console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`) + } + + ``` + +### getRawFileList10+ + +getRawFileList(path: string): Promise<Array\> + +Obtains the list of files in the **resources/rawfile** directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the **rawfile** folder.| + +**Return value** + +| Type | Description | +| ------------------------- | ----------- | +| Promise<Array\> | List of files in the **rawfile** folder.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { // Passing "" means to obtain the list of files in the root directory of the raw file. + this.context.resourceManager.getRawFileList("").then(value => { + let rawFile = value; + }).catch(error => { + console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`) + }); + } catch (error) { + console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### closeRawFileDescriptor8+ closeRawFileDescriptor(path: string, callback: AsyncCallback<void>): void @@ -1521,10 +1948,10 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th | path | string | Yes | Path of the raw file.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001005 | The resource not found by path. | @@ -1563,10 +1990,10 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th | ------------------- | ---- | | Promise<void> | Promise that returns no value.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001005 | If the resource not found by path. | @@ -1614,10 +2041,10 @@ Obtains the string corresponding to the specified resource name. This API uses a | resName | string | Yes | Resource name. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -1658,12 +2085,12 @@ Obtains the string corresponding to the specified resource name. This API uses a | Type | Description | | --------------------- | ---------- | -| Promise<string> | String corresponding to the resource name.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| Promise<string> | Promise used to return the result.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -1698,10 +2125,10 @@ Obtains the string array corresponding to the specified resource name. This API | resName | string | Yes | Resource name. | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -1743,10 +2170,10 @@ Obtains the string array corresponding to the specified resource name. This API | ---------------------------------- | ------------ | | Promise<Array<string>> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -1781,15 +2208,14 @@ Obtains the content of the media file corresponding to the specified resource ID | resName | string | Yes | Resource name. | | callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts @@ -1806,6 +2232,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaByName10+ + +getMediaByName(resName: string, density: number, callback: AsyncCallback<Uint8Array>): void + +Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resName | string | Yes | Resource name. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaByName("test", 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getMediaByName9+ getMediaByName(resName: string): Promise<Uint8Array> @@ -1826,15 +2292,14 @@ Obtains the content of the media file corresponding to the specified resource na | ------------------------- | ------------- | | Promise<Uint8Array> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts @@ -1849,6 +2314,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaByName10+ + +getMediaByName(resName: string, density: number): Promise<Uint8Array> + +Obtains the content of the media file with the screen density corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------- | +| Promise<Uint8Array> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaByName("test", 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getMediaBase64ByName9+ getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void @@ -1864,15 +2372,14 @@ Obtains the Base64 code of the image corresponding to the specified resource nam | resName | string | Yes | Resource name. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts @@ -1889,6 +2396,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaBase64ByName10+ + +getMediaBase64ByName(resName: string, density: number, callback: AsyncCallback<string>): void + +Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resName | string | Yes | Resource name. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaBase64ByName("test", 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } + }); + } catch (error) { + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getMediaBase64ByName9+ getMediaBase64ByName(resName: string): Promise<string> @@ -1909,15 +2456,14 @@ Obtains the Base64 code of the image corresponding to the specified resource nam | --------------------- | ------------------- | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts @@ -1932,6 +2478,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getMediaBase64ByName10+ + +getMediaBase64ByName(resName: string, density: number): Promise<string> + +Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------- | +| Promise<string> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | + +**Example** + ```ts + try { + this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getPluralStringByName9+ getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void @@ -1948,10 +2537,10 @@ Obtains the plural string corresponding to the specified resource name based on | num | number | Yes | Number. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -1995,10 +2584,10 @@ Obtains the plural string corresponding to the specified resource name based on | --------------------- | ---------------------- | | Promise<string> | Promise used to return the result.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -2036,12 +2625,12 @@ Obtains the string corresponding to the specified resource ID. This API returns | Type | Description | | ------ | ----------- | -| string | Promise used to return the result.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| string | String corresponding to the specified resource ID.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2078,10 +2667,10 @@ Obtains the string corresponding to the specified resource ID and formats the st | ------ | ---------------------------- | | string | Formatted string.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ----------------------------------------------- | | 9001001 | If the resId invalid. | @@ -2116,12 +2705,12 @@ Obtains the string corresponding to the specified resource object. This API retu | Type | Description | | ------ | ---------------- | -| string | Promise used to return the result.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| string | String corresponding to the specified resource object.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2163,10 +2752,10 @@ Obtains the string corresponding to the specified resource object and formats th | ------ | ---------------------------- | | string | Formatted string.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2208,10 +2797,10 @@ Obtains the string corresponding to the specified resource name. This API return | ------ | ---------- | | string | String corresponding to the specified resource name.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -2248,10 +2837,10 @@ Obtains the string corresponding to the specified resource name and formats the | ------ | ---------------------------- | | string | Formatted string.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -2288,10 +2877,10 @@ Obtains the Boolean result corresponding to the specified resource ID. This API | ------- | ------------ | | boolean | Boolean result corresponding to the specified resource ID.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2326,10 +2915,10 @@ Obtains the Boolean result corresponding to the specified resource object. This | ------- | ----------------- | | boolean | Boolean result corresponding to the specified resource object.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2370,10 +2959,10 @@ Obtains the Boolean result corresponding to the specified resource name. This AP | ------- | ----------- | | boolean | Boolean result corresponding to the specified resource name.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -2407,12 +2996,12 @@ Obtains the integer or float value corresponding to the specified resource ID. T | Type | Description | | ------ | ---------- | -| number | Integer or float value corresponding to the specified resource ID. Wherein, the integer value is the original value, and the float value is the actual pixel value.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| number | Integer or float value corresponding to the specified resource ID. Wherein, the integer value is the original value, and the float value is the actual pixel value. For details, see the sample code.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2452,12 +3041,12 @@ Obtains the integer or float value corresponding to the specified resource objec | Type | Description | | ------ | --------------- | -| number | Integer or float value corresponding to the specified resource object. Wherein, the integer value is the original value, and the float value is the actual pixel value.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| number | Integer or float value corresponding to the specified resource object. Wherein, the integer value is the original value, and the float value is the actual pixel value. For details, see the sample code.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2498,10 +3087,10 @@ Obtains the integer or float value corresponding to the specified resource name. | ------ | --------- | | number | Integer or float value corresponding to the specified resource name.| -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -2542,12 +3131,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | Type | Description | | ------ | ---------- | -| DrawableDescriptor | **DrawableDescriptor** object corresponding to the resource ID.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2571,7 +3160,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; -Obtains the **DrawableDescriptor** object corresponding to the specified resource. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -2586,12 +3175,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | Type | Description | | ------- | ----------------- | -| DrawableDescriptor | **DrawableDescriptor** object corresponding to the resource ID.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | @@ -2635,12 +3224,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | Type | Description | | ------ | --------- | -| DrawableDescriptor | **DrawableDescriptor** object corresponding to the resource ID.| - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | @@ -2666,7 +3255,7 @@ getString(resId: number, callback: AsyncCallback<string>): void Obtains the string corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getStringValue](#getstringvalue9). +This API is deprecated since API version 9. You are advised to use [getStringValue](#getstringvalue9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2697,7 +3286,7 @@ getString(resId: number): Promise<string> Obtains the string corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getStringValue](#getstringvalue9-1). +This API is deprecated since API version 9. You are advised to use [getStringValue](#getstringvalue9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2731,7 +3320,7 @@ getStringArray(resId: number, callback: AsyncCallback<Array<string>> Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getStringArrayValue](#getstringarrayvalue9). +This API is deprecated since API version 9. You are advised to use [getStringArrayValue](#getstringarrayvalue9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2762,7 +3351,7 @@ getStringArray(resId: number): Promise<Array<string>> Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getStringArrayValue](#getstringarrayvalue9-1). +This API is deprecated since API version 9. You are advised to use [getStringArrayValue](#getstringarrayvalue9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2796,7 +3385,7 @@ getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9). +This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2827,7 +3416,7 @@ getMedia(resId: number): Promise<Uint8Array> Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9-1). +This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2861,7 +3450,7 @@ getMediaBase64(resId: number, callback: AsyncCallback<string>): void Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649). +This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2892,7 +3481,7 @@ getMediaBase64(resId: number): Promise<string> Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649-1). +This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2926,7 +3515,7 @@ getPluralString(resId: number, num: number): Promise<string> Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9). +This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2961,7 +3550,7 @@ getPluralString(resId: number, num: number, callback: AsyncCallback<string> Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9-1). +This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2993,7 +3582,7 @@ getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getRawFileContent](#getrawfilecontent9). +This API is deprecated since API version 9. You are advised to use [getRawFileContent](#getrawfilecontent9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -3024,7 +3613,7 @@ getRawFile(path: string): Promise<Uint8Array> Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getRawFileContent](#getrawfilecontent9-1). +This API is deprecated since API version 9. You are advised to use [getRawFileContent](#getrawfilecontent9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -3058,7 +3647,7 @@ getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor& Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getRawFd](#getrawfd9). +This API is deprecated since API version 9. You are advised to use [getRawFd](#getrawfd9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -3090,7 +3679,7 @@ getRawFileDescriptor(path: string): Promise<RawFileDescriptor> Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getRawFd](#getrawfd9-1). +This API is deprecated since API version 9. You are advised to use [getRawFd](#getrawfd9-1) instead. **System capability**: SystemCapability.Global.ResourceManager diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index cf918a571c7121bdb5b9c5f51cb7a93ce782968d..3066cbef6e6a7c36bb6828c82eec5756ba54b532 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -51,10 +51,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -76,7 +76,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ``` -## backgroundTaskManager.getRemainingDelayTime:callback +## backgroundTaskManager.getRemainingDelayTime getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void @@ -99,10 +99,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -125,7 +125,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ``` -## backgroundTaskManager.getRemainingDelayTime:promise +## backgroundTaskManager.getRemainingDelayTime getRemainingDelayTime(requestId: number): Promise<number> @@ -155,10 +155,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -200,10 +200,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -219,7 +219,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ``` -## backgroundTaskManager.startBackgroundRunning:callback +## backgroundTaskManager.startBackgroundRunning startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void @@ -246,9 +246,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -297,7 +297,7 @@ export default class EntryAbility extends UIAbility { }; ``` -## backgroundTaskManager.startBackgroundRunning:promise +## backgroundTaskManager.startBackgroundRunning startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> @@ -329,9 +329,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -376,7 +376,7 @@ export default class EntryAbility extends UIAbility { }; ``` -## backgroundTaskManager.stopBackgroundRunning:callback +## backgroundTaskManager.stopBackgroundRunning stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void @@ -399,9 +399,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -430,7 +430,7 @@ export default class EntryAbility extends UIAbility { }; ``` -## backgroundTaskManager.stopBackgroundRunning:promise +## backgroundTaskManager.stopBackgroundRunning stopBackgroundRunning(context: Context): Promise<void> @@ -460,9 +460,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -513,9 +513,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 18700001 | Caller information verification failed when applying for efficiency resources. | +| 18700001 | Caller information verification failed. | **Example** @@ -556,9 +556,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 18700001 | Caller information verification failed when applying for efficiency resources. | +| 18700001 | Caller information verification failed. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index 01fa04dc18f59bf47d49248681d5f46fba32d187..ae4decd405b23cfc87452846558533448a86563f 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -1549,10 +1549,10 @@ Provides the usage duration information of an application. | Name | Type | Mandatory | Description | | ------------------------ | ------ | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityPrevAccessTime | number | Yes | Last time when the application was used. | -| abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. | -| id | number | No | User ID.| +| bundleName | string | No | Bundle name of the application. | +| abilityPrevAccessTime | number | No | Last time when the application was used. | +| abilityInFgTotalTime | number | No | Total time that the application runs in the foreground. | +| id | number | Yes | User ID.| | abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.| | abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.| | fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.| @@ -1570,9 +1570,9 @@ Provides information about an application event. | Name | Type | Mandatory | Description | | --------------------- | ------ | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| eventId | number | Yes | Application event type. | -| eventOccurredTime | number | Yes | Timestamp when the application event occurs. | +| bundleName | string | No | Bundle name of the application. | +| eventId | number | No | Application event type. | +| eventOccurredTime | number | No | Timestamp when the application event occurs. | | appGroup | number | No | Usage priority group of the application.| | indexOfLink | string | No | Shortcut ID.| | nameOfClass | string | No | Class name.| @@ -1587,7 +1587,7 @@ Provides the usage duration information of an application. | Name | Type | Mandatory | Description | | ------------------------------ | ---------------------------------------- | ---- | -------------- | -| [key: string]: BundleStatsInfo | [key: string]: [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| +| [key: string] | [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| ## DeviceEventStats diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index e25ca6bcb1381a41f8491fcb8c50b2e65e5929e1..4d72733c02f607fd17f29f2c4402f059bfee981f 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,8 +1,9 @@ -# @ohos.runningLock (Runninglock) +# @ohos.runningLock (Running Lock) The **runningLock** module provides APIs for creating, querying, holding, and releasing running locks. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -15,7 +16,7 @@ import runningLock from '@ohos.runningLock'; isSupported(type: RunningLockType): boolean; -Checks whether a specified type of **RunningLock** is supported. +Checks whether the specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -25,7 +26,7 @@ Checks whether a specified type of **RunningLock** is supported. | ------ | ----------------------------------- | ---- | -------------------- | | type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| -**Return value** +**Return Value** | Type | Description | | ------- | --------------------------------------- | @@ -35,9 +36,9 @@ Checks whether a specified type of **RunningLock** is supported. For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). -| Code | Error Message | +| ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -72,9 +73,9 @@ Creates a **RunningLock** object. For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). -| Code | Error Message | +| ID | Error Message | |---------|----------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -105,7 +106,7 @@ Creates a **RunningLock** object. | name | string | Yes | Name of the **RunningLock** object. | | type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| -**Return value** +**Return Value** | Type | Description | | ------------------------------------------ | ------------------------------------ | @@ -115,9 +116,9 @@ Creates a **RunningLock** object. For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). -| Code | Error Message | +| ID | Error Message | |---------|----------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -135,10 +136,9 @@ runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void -> NOTE
-> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9). -Checks whether a specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. +Checks whether the specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. This API uses an asynchronous callback to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -147,7 +147,7 @@ Checks whether a specified type of **RunningLock** is supported. This API uses a | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | | type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that the specified type of **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.| **Example** @@ -165,10 +165,9 @@ runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, ( isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> -> NOTE
-> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9). -Checks whether a specified type of **RunningLock** is supported. This API uses a promise to return the result. +Checks whether the specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. This API uses a promise to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -178,7 +177,7 @@ Checks whether a specified type of **RunningLock** is supported. This API uses a | ------ | ----------------------------------- | ---- | -------------------- | | type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| -**Return value** +**Return Value** | Type | Description | | ---------------------- | ---------------------------------------------------- | @@ -200,8 +199,7 @@ runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND) createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void -> NOTE
-> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9). Creates a **RunningLock** object. @@ -233,8 +231,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B createRunningLock(name: string, type: RunningLockType): Promise<RunningLock> -> NOTE
-> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9). Creates a **RunningLock** object. @@ -249,7 +246,7 @@ Creates a **RunningLock** object. | name | string | Yes | Name of the **RunningLock** object. | | type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| -**Return value** +**Return Value** | Type | Description | | ------------------------------------------ | ------------------------------------ | @@ -269,7 +266,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B ## RunningLock -Represents a **RunningLock** object. +Defines a **RunningLock** object. ### hold9+ @@ -291,9 +288,9 @@ Locks and holds a **RunningLock** object. For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). -| Code | Error Message | +| ID | Error Message | |---------|----------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -327,9 +324,9 @@ Releases a **RunningLock** object. For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). -| Code | Error Message | +| ID | Error Message | |---------|----------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -357,7 +354,7 @@ Checks the hold status of the **Runninglock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core -**Return value** +**Return Value** | Type | Description | | ------- | ------------------------------------------------------------ | @@ -367,9 +364,9 @@ Checks the hold status of the **Runninglock** object. For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). -| Code | Error Message | +| ID | Error Message | |---------|---------| -| 4900101 | Operation failed. Cannot connect to service.| +| 4900101 | If connecting to the service failed. | **Example** @@ -393,8 +390,7 @@ runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) lock(timeout: number): void -> NOTE
-> This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9). Locks and holds a **RunningLock** object. @@ -425,8 +421,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B unlock(): void -> NOTE
-> This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9). Releases a **RunningLock** object. @@ -451,14 +446,13 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B isUsed(): boolean -> NOTE
-> This API is deprecated since API version 9. You are advised to use [RunningLock.isHolding](#isholding9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [RunningLock.isHolding](#isholding9). Checks the hold status of the **Runninglock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core -**Return value** +**Return Value** | Type | Description | | ------- | ------------------------------------------------------------ | | boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.| diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 6736cc90eca295e17310c295409a781f679db7d4..08700a85bd5bab7b6bc8a0e190f5376602eeb462 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -1,6 +1,6 @@ -# @ohos.telephony.sim (SIM) +# @ohos.telephony.sim (SIM Management) -The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. +The **sim** module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. >**NOTE** > @@ -15,7 +15,7 @@ import sim from '@ohos.telephony.sim'; ## sim.isSimActive7+ -isSimActive\(slotId: number, callback: AsyncCallback\): void +isSimActive\(slotId: number, callback: AsyncCallback\\): void Checks whether the SIM card in the specified slot is activated. This API uses an asynchronous callback to return the result. @@ -39,7 +39,7 @@ sim.isSimActive(0, (err, data) => { ## sim.isSimActive7+ -isSimActive\(slotId: number\): Promise +isSimActive\(slotId: number\): Promise\ Checks whether the SIM card in the specified slot is activated. This API uses a promise to return the result. @@ -71,7 +71,7 @@ promise.then(data => { ## sim.getDefaultVoiceSlotId7+ -getDefaultVoiceSlotId\(callback: AsyncCallback\): void +getDefaultVoiceSlotId\(callback: AsyncCallback\\): void Obtains the default slot ID of the SIM card that provides voice services. This API uses an asynchronous callback to return the result. @@ -94,7 +94,7 @@ sim.getDefaultVoiceSlotId((err, data) => { ## sim.getDefaultVoiceSlotId7+ -getDefaultVoiceSlotId\(\): Promise +getDefaultVoiceSlotId\(\): Promise\ Obtains the default slot ID of the SIM card that provides voice services. This API uses a promise to return the result. @@ -119,7 +119,7 @@ promise.then(data => { ## sim.hasOperatorPrivileges7+ -hasOperatorPrivileges(slotId: number, callback: AsyncCallback\): void +hasOperatorPrivileges\(slotId: number, callback: AsyncCallback\\): void Checks whether the application (caller) has been granted the operator permission. This API uses an asynchronous callback to return the result. @@ -154,7 +154,7 @@ sim.hasOperatorPrivileges(0, (err, data) => { ## sim.hasOperatorPrivileges7+ -hasOperatorPrivileges(slotId: number): Promise +hasOperatorPrivileges\(slotId: number\): Promise\ Checks whether the application (caller) has been granted the operator permission. This API uses a promise to return the result. @@ -197,7 +197,7 @@ promise.then(data => { ## sim.getISOCountryCodeForSim -getISOCountryCodeForSim\(slotId: number, callback: AsyncCallback\): void +getISOCountryCodeForSim\(slotId: number, callback: AsyncCallback\\): void Obtains the ISO country code of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -234,7 +234,7 @@ sim.getISOCountryCodeForSim(0, (err, data) => { ## sim.getISOCountryCodeForSim -getISOCountryCodeForSim\(slotId: number\): Promise +getISOCountryCodeForSim\(slotId: number\): Promise\ Obtains the ISO country code of the SIM card in the specified slot. This API uses a promise to return the result. @@ -279,7 +279,7 @@ promise.then(data => { ## sim.getSimOperatorNumeric -getSimOperatorNumeric\(slotId: number, callback: AsyncCallback\): void +getSimOperatorNumeric\(slotId: number, callback: AsyncCallback\\): void Obtains the public land mobile network \(PLMN\) ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -316,7 +316,7 @@ sim.getSimOperatorNumeric(0, (err, data) => { ## sim.getSimOperatorNumeric -getSimOperatorNumeric\(slotId: number\): Promise +getSimOperatorNumeric\(slotId: number\): Promise\ Obtains the PLMN ID of the SIM card in the specified slot. This API uses a promise to return the result. @@ -361,7 +361,7 @@ promise.then(data => { ## sim.getSimSpn -getSimSpn\(slotId: number, callback: AsyncCallback\): void +getSimSpn\(slotId: number, callback: AsyncCallback\\): void Obtains the service provider name (SPN) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -398,7 +398,7 @@ sim.getSimSpn(0, (err, data) => { ## sim.getSimSpn -getSimSpn\(slotId: number\): Promise +getSimSpn\(slotId: number\): Promise\ Obtains the SPN of the SIM card in the specified slot. This API uses a promise to return the result. @@ -443,7 +443,7 @@ promise.then(data => { ## sim.getSimState -getSimState\(slotId: number, callback: AsyncCallback\): void +getSimState\(slotId: number, callback: AsyncCallback\\): void Obtains the state of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -479,7 +479,7 @@ sim.getSimState(0, (err, data) => { ## sim.getSimState -getSimState\(slotId: number\): Promise +getSimState\(slotId: number\): Promise\ Obtains the state of the SIM card in the specified slot. This API uses a promise to return the result. @@ -522,7 +522,7 @@ promise.then(data => { ## sim.getCardType7+ -getCardType\(slotId: number, callback: AsyncCallback\): void +getCardType\(slotId: number, callback: AsyncCallback\\): void Obtains the type of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -559,7 +559,7 @@ sim.getCardType(0, (err, data) => { ## sim.getCardType7+ -getCardType\(slotId: number\): Promise +getCardType\(slotId: number\): Promise\ Obtains the type of the SIM card in the specified slot. This API uses a promise to return the result. @@ -604,7 +604,7 @@ promise.then(data => { ## sim.hasSimCard7+ -hasSimCard\(slotId: number, callback: AsyncCallback\): void +hasSimCard\(slotId: number, callback: AsyncCallback\\): void Checks whether the SIM card in the specified slot is installed. This API uses an asynchronous callback to return the result. @@ -640,7 +640,7 @@ sim.hasSimCard(0, (err, data) => { ## sim.hasSimCard7+ -hasSimCard\(slotId: number\): Promise +hasSimCard\(slotId: number\): Promise\ Checks whether the SIM card in the specified slot is installed. This API uses a promise to return the result. @@ -683,7 +683,7 @@ promise.then(data => { ## sim.getSimAccountInfo7+ -getSimAccountInfo(slotId: number, callback: AsyncCallback): void +getSimAccountInfo\(slotId: number, callback: AsyncCallback\\): void Obtains SIM card account information. This API uses an asynchronous callback to return the result. @@ -707,6 +707,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -726,7 +727,7 @@ sim.getSimAccountInfo(0, (err, data) => { ## sim.getSimAccountInfo7+ -getSimAccountInfo(slotId: number): Promise +getSimAccountInfo\(slotId: number\): Promise\ Obtains SIM card account information. This API uses a promise to return the result. @@ -755,6 +756,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -776,7 +778,7 @@ promise.then(data => { ## sim.getActiveSimAccountInfoList8+ -getActiveSimAccountInfoList(callback: AsyncCallback>): void +getActiveSimAccountInfoList\(callback: AsyncCallback\\>\): void Obtains the account information list of the active SIM card. This API uses an asynchronous callback to return the result. @@ -799,7 +801,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | -| 401 | Parameter error. | +| 202 | Non-system applications use system APIs. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | @@ -817,7 +819,7 @@ sim.getActiveSimAccountInfoList((err, data) => { ## sim.getActiveSimAccountInfoList8+ -getActiveSimAccountInfoList(): Promise>; +getActiveSimAccountInfoList\(\): Promise\\>; Obtains the account information list of the active SIM card. This API uses a promise to return the result. @@ -840,8 +842,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300004 | Do not have sim card. | @@ -860,7 +861,7 @@ promise.then(data => { ## sim.setDefaultVoiceSlotId7+ -setDefaultVoiceSlotId(slotId: number, callback: AsyncCallback): void +setDefaultVoiceSlotId\(slotId: number, callback: AsyncCallback\\): void Sets the default slot ID of the SIM card that provides voice services. This API uses an asynchronous callback to return the result. @@ -884,6 +885,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -903,7 +905,7 @@ sim.setDefaultVoiceSlotId(0, (err) => { ## sim.setDefaultVoiceSlotId7+ -setDefaultVoiceSlotId(slotId: number): Promise\ +setDefaultVoiceSlotId\(slotId: number\): Promise\ Sets the default slot ID of the SIM card that provides voice services. This API uses a promise to return the result. @@ -932,6 +934,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -953,7 +956,7 @@ promise.then(() => { ## sim.setShowName8+ -setShowName\(slotId: number, name: string, callback: AsyncCallback\): void +setShowName\(slotId: number, name: string, callback: AsyncCallback\\): void Sets a display name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -978,6 +981,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1026,6 +1030,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1047,7 +1052,7 @@ promise.then(() => { ## sim.getShowName8+ -getShowName(slotId: number, callback: AsyncCallback): void +getShowName\(slotId: number, callback: AsyncCallback\\): void Obtains the name of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1071,6 +1076,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1089,7 +1095,7 @@ sim.getShowName(0, (err, data) => { ## sim.getShowName8+ -getShowName(slotId: number): Promise +getShowName\(slotId: number\): Promise\ Obtains the name of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1118,6 +1124,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1138,7 +1145,7 @@ promise.then(data => { ## sim.setShowNumber8+ -setShowNumber\(slotId: number, number: string, callback: AsyncCallback\): void +setShowNumber\(slotId: number, number: string, callback: AsyncCallback\\): void Sets a display number for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1163,6 +1170,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1212,6 +1220,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1233,7 +1242,7 @@ promise.then(() => { ## sim.getShowNumber8+ -getShowNumber(slotId: number, callback: AsyncCallback): void +getShowNumber\(slotId: number, callback: AsyncCallback\): void Obtains the display number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1257,6 +1266,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1275,7 +1285,7 @@ sim.getShowNumber(0, (err, data) => { ## sim.getShowNumber8+ -getShowNumber(slotId: number): Promise +getShowNumber\(slotId: number\): Promise\ Obtains the display number of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1304,6 +1314,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1324,7 +1335,7 @@ promise.then(data => { ## sim.activateSim8+ -activateSim(slotId: number, callback: AsyncCallback): void +activateSim\(slotId: number, callback: AsyncCallback\\): void Activates a SIM card in a specified card slot. This API uses an asynchronous callback to return the result. @@ -1348,6 +1359,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1366,7 +1378,7 @@ sim.activateSim(0, (err) => { ## sim.activateSim8+ -activateSim(slotId: number): Promise\ +activateSim\(slotId: number\): Promise\ Activates the SIM card in the specified slot. This API uses a promise to return the result. @@ -1395,6 +1407,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1415,7 +1428,7 @@ promise.then(() => { ## sim.deactivateSim8+ -deactivateSim(slotId: number, callback: AsyncCallback): void +deactivateSim\(slotId: number, callback: AsyncCallback\\): void Disables the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1439,6 +1452,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1457,7 +1471,7 @@ sim.deactivateSim(0, (err) => { ## sim.deactivateSim8+ -deactivateSim(slotId: number): Promise\ +deactivateSim\(slotId: number\): Promise\ Disables the SIM card in the specified slot. This API uses a promise to return the result. @@ -1486,6 +1500,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1506,7 +1521,7 @@ promise.then(() => { ## sim.setLockState7+ -setLockState(slotId: number, options: LockInfo, callback: AsyncCallback): void +setLockState\(slotId: number, options: LockInfo, callback: AsyncCallback\\): void Sets the lock status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1531,6 +1546,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1555,7 +1571,7 @@ sim.setLockState(0, lockInfo, (err, data) => { ## sim.setLockState7+ -setLockState(slotId: number, options: LockInfo): Promise +setLockState\(slotId: number, options: LockInfo\): Promise\ Sets the lock status of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1585,6 +1601,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1611,7 +1628,7 @@ promise.then(data => { ## sim.getLockState8+ -getLockState(slotId: number, lockType: LockType, callback: AsyncCallback): void +getLockState\(slotId: number, lockType: LockType, callback: AsyncCallback\\): void Obtains the lock status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1636,6 +1653,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1655,7 +1673,7 @@ sim.getLockState(0, 1, (err, data) => { ## sim.getLockState8+ -getLockState(slotId: number, lockType: LockType): Promise +getLockState\(slotId: number, lockType: LockType\): Promise\ Obtains the lock status of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1685,6 +1703,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1706,7 +1725,7 @@ promise.then(data => { ## sim.alterPin7+ -alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback): void +alterPin\(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback\\): void Changes the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1732,6 +1751,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1751,7 +1771,7 @@ sim.alterPin(0, "1234", "0000", (err, data) => { ## sim.alterPin7+ -alterPin(slotId: number, newPin: string, oldPin: string): Promise; +alterPin\(slotId: number, newPin: string, oldPin: string\): Promise\; Changes the PIN of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1782,6 +1802,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1803,7 +1824,7 @@ promise.then(data => { ## sim.alterPin28+ -alterPin2(slotId: number, newPin2: string, oldPin2: string, callback: AsyncCallback): void +alterPin2\(slotId: number, newPin2: string, oldPin2: string, callback: AsyncCallback\\): void Changes PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1829,6 +1850,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1848,7 +1870,7 @@ sim.alterPin2(0, "1234", "0000", (err, data) => { ## sim.alterPin28+ -alterPin2(slotId: number, newPin2: string, oldPin2: string): Promise +alterPin2\(slotId: number, newPin2: string, oldPin2: string\): Promise\ Changes PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1879,6 +1901,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1900,7 +1923,7 @@ promise.then(data => { ## sim.unlockPin7+ -unlockPin(slotId: number, pin: string, callback: AsyncCallback): void +unlockPin\(slotId: number, pin: string, callback: AsyncCallback\\): void Unlocks the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1925,6 +1948,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1945,7 +1969,7 @@ sim.unlockPin(0, pin, (err, data) => { ## sim.unlockPin7+ -unlockPin(slotId: number, pin: string): Promise<LockStatusResponse\> +unlockPin\(slotId: number, pin: string\): Promise\ Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1975,6 +1999,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1997,7 +2022,7 @@ promise.then(data => { ## sim.unlockPuk7+ -unlockPuk(slotId: number, newPin: string, puk: string, callback: AsyncCallback): void +unlockPuk\(slotId: number, newPin: string, puk: string, callback: AsyncCallback\\): void Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2023,6 +2048,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2044,7 +2070,7 @@ sim.unlockPuk(0, newPin, puk, (err, data) => { ## sim.unlockPuk7+ -unlockPuk(slotId: number, newPin: string, puk: string): Promise<LockStatusResponse\> +unlockPuk\(slotId: number, newPin: string, puk: string\): Promise\ Unlocks the PUK of the SIM card in the specified slot. This API uses a promise to return the result. @@ -2075,6 +2101,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2098,9 +2125,9 @@ promise.then(data => { ## sim.unlockPin28+ -unlockPin2(slotId: number, pin2: string, callback: AsyncCallback): void +unlockPin2\(slotId: number, pin2: string, callback: AsyncCallback\\): void -Unlocks PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Unlocks the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2123,6 +2150,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2143,9 +2171,9 @@ sim.unlockPin2(0, pin2, (err, data) => { ## sim.unlockPin28+ -unlockPin2(slotId: number, pin2: string): Promise<LockStatusResponse\> +unlockPin2\(slotId: number, pin2: string\): Promise\ -Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. +Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result. **System API**: This is a system API. @@ -2173,6 +2201,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2195,9 +2224,9 @@ promise.then(data => { ## sim.unlockPuk28+ -unlockPuk2(slotId: number, newPin2: string, puk2: string, callback: AsyncCallback): void +unlockPuk2\(slotId: number, newPin2: string, puk2: string, callback: AsyncCallback\\): void -Unlocks PUK 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2242,9 +2271,9 @@ sim.unlockPuk2(0, newPin2, puk2, (err, data) => { ## sim.unlockPuk28+ -unlockPuk2(slotId: number, newPin2: string, puk2: string): Promise<LockStatusResponse\> +unlockPuk2\(slotId: number, newPin2: string, puk2: string\): Promise\ -Unlocks PUK 2 of the SIM card in the specified slot. This API uses a promise to return the result. +Unlocks the PUK of the SIM card in the specified slot. This API uses a promise to return the result. **System API**: This is a system API. @@ -2316,7 +2345,7 @@ console.log("Result: "+ sim.getMaxSimCount()) ## sim.getSimIccId7+ -getSimIccId(slotId: number, callback: AsyncCallback): void +getSimIccId\(slotId: number, callback: AsyncCallback\\): void Obtains the ICCID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2340,6 +2369,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2358,7 +2388,7 @@ sim.getSimIccId(0, (err, data) => { ## sim.getSimIccId7+ -getSimIccId(slotId: number): Promise +getSimIccId\(slotId: number\): Promise\ Obtains the ICCID of the SIM card in the specified slot. This API uses a promise to return the result. @@ -2387,6 +2417,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2407,7 +2438,7 @@ promise.then(data => { ## sim.getVoiceMailIdentifier8+ -getVoiceMailIdentifier(slotId: number, callback: AsyncCallback): void +getVoiceMailIdentifier\(slotId: number, callback: AsyncCallback\\): void Obtains the voice mailbox alpha identifier of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2431,6 +2462,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2449,7 +2481,7 @@ sim.getVoiceMailIdentifier(0, (err, data) => { ## sim.getVoiceMailIdentifier8+ -getVoiceMailIdentifier(slotId: number): Promise +getVoiceMailIdentifier\(slotId: number\): Promise\ Obtains the voice mailbox alpha identifier of the SIM card in the specified slot. This API uses a promise to return the result. @@ -2478,6 +2510,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2498,7 +2531,7 @@ promise.then(data => { ## sim.getVoiceMailNumber8+ -getVoiceMailNumber(slotId: number, callback: AsyncCallback): void +getVoiceMailNumber\(slotId: number, callback: AsyncCallback\): void Obtains the voice mailbox number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2522,6 +2555,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2540,7 +2574,7 @@ sim.getVoiceMailNumber(0, (err, data) => { ## sim.getVoiceMailNumber8+ -getVoiceMailNumber(slotId: number): Promise +getVoiceMailNumber\(slotId: number\): Promise\ Obtains the voice mailbox number of the SIM card in the specified slot. This API uses a promise to return the result. @@ -2569,6 +2603,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2590,7 +2625,7 @@ promise.then(data => { ## sim.setVoiceMailInfo8+ -setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string, callback: AsyncCallback): void +setVoiceMailInfo\(slotId: number, mailName: string, mailNumber: string, callback: AsyncCallback\\): void Sets voice mailbox information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2616,6 +2651,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2635,7 +2671,7 @@ sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com", (err) => { ## sim.setVoiceMailInfo8+ -setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string): Promise +setVoiceMailInfo\(slotId: number, mailName: string, mailNumber: string\): Promise\ Sets voice mailbox information for the SIM card in the specified slot. This API uses a promise to return the result. @@ -2666,6 +2702,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2687,7 +2724,7 @@ promise.then(() => { ## sim.getSimTelephoneNumber8+ -getSimTelephoneNumber(slotId: number, callback: AsyncCallback): void +getSimTelephoneNumber\(slotId: number, callback: AsyncCallback\\): void Obtains the MSISDN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2711,6 +2748,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2729,7 +2767,7 @@ sim.getSimTelephoneNumber(0, (err, data) => { ## sim.getSimTelephoneNumber8+ -getSimTelephoneNumber(slotId: number): Promise +getSimTelephoneNumber\(slotId: number\): Promise\ Obtains the MSISDN of the SIM card in the specified slot. This API uses a promise to return the result. @@ -2758,6 +2796,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2778,7 +2817,7 @@ promise.then(data => { ## sim.getSimGid17+ -getSimGid1(slotId: number, callback: AsyncCallback): void +getSimGid1\(slotId: number, callback: AsyncCallback\\): void Obtains the group identifier level 1 (GID1) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2802,6 +2841,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2820,7 +2860,7 @@ sim.getSimGid1(0, (err, data) => { ## sim.getSimGid17+ -getSimGid1(slotId: number): Promise +getSimGid1\(slotId: number\): Promise\ Obtains the GID1 of the SIM card in the specified slot. This API uses a promise to return the result. @@ -2849,6 +2889,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2869,7 +2910,7 @@ promise.then(data => { ## sim.getIMSI -getIMSI(slotId: number, callback: AsyncCallback): void +getIMSI\(slotId: number, callback: AsyncCallback\\): void Obtains the international mobile subscriber identity (IMSI) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2893,6 +2934,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2911,7 +2953,7 @@ sim.getIMSI(0, (err, data) => { ## sim.getIMSI -getIMSI(slotId: number): Promise +getIMSI\(slotId: number\): Promise\ Obtains the IMSI of the SIM card in the specified slot. This API uses a promise to return the result. @@ -2940,6 +2982,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -2960,7 +3003,7 @@ promise.then(data => { ## sim.getOperatorConfigs8+ -getOperatorConfigs(slotId: number, callback: AsyncCallback>): void +getOperatorConfigs\(slotId: number, callback: AsyncCallback\\>\): void Obtains the carrier configuration of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -2984,6 +3027,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3001,7 +3045,7 @@ sim.getOperatorConfigs(0, (err, data) => { ## sim.getOperatorConfigs8+ -getOperatorConfigs(slotId: number): Promise> +getOperatorConfigs\(slotId: number\): Promise\\> Obtains the carrier configuration of the SIM card in the specified slot. This API uses a promise to return the result. @@ -3030,6 +3074,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3049,7 +3094,7 @@ promise.then(data => { ## sim.queryIccDiallingNumbers8+ -queryIccDiallingNumbers(slotId: number, type: ContactType, callback: AsyncCallback>): void +queryIccDiallingNumbers\(slotId: number, type: ContactType, callback: AsyncCallback\\>\): void Queries contact numbers of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3074,6 +3119,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3093,7 +3139,7 @@ sim.queryIccDiallingNumbers(0, 1, (err, data) => { ## sim.queryIccDiallingNumbers8+ -queryIccDiallingNumbers(slotId: number, type: ContactType): Promise> +queryIccDiallingNumbers\(slotId: number, type: ContactType\): Promise\\> Queries contact numbers of the SIM card in the specified slot. This API uses a promise to return the result. @@ -3123,6 +3169,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3144,7 +3191,7 @@ promise.then(data => { ## sim.addIccDiallingNumbers8+ -addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void +addIccDiallingNumbers\(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback\\): void Adds contact numbers for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3170,6 +3217,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3194,7 +3242,7 @@ sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersIno ## sim.addIccDiallingNumbers8+ -addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise +addIccDiallingNumbers\(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo\): Promise\ Adds contact numbers for the SIM card in the specified slot. This API uses a promise to return the result. @@ -3225,6 +3273,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3250,7 +3299,7 @@ promise.then(() => { ## sim.delIccDiallingNumbers8+ -delIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void +delIccDiallingNumbers\(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback\\): void Deletes contact numbers from the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3276,6 +3325,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3301,7 +3351,7 @@ sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersIno ## sim.delIccDiallingNumbers8+ -delIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise +delIccDiallingNumbers\(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo\): Promise\ Deletes contact numbers from the SIM card in the specified slot. This API uses a promise to return the result. @@ -3332,6 +3382,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3357,7 +3408,7 @@ promise.then(() => { ## sim.updateIccDiallingNumbers8+ -updateIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void +updateIccDiallingNumbers\(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback\\): void Updates contact numbers for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3383,6 +3434,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3408,7 +3460,7 @@ sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbers ## sim.updateIccDiallingNumbers8+ -updateIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise +updateIccDiallingNumbers\(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo\): Promise\ Updates contact numbers for the SIM card in the specified slot. This API uses a promise to return the result. @@ -3439,6 +3491,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3465,7 +3518,7 @@ promise.then(() => { ## sim.sendEnvelopeCmd8+ -sendEnvelopeCmd(slotId: number, cmd: string, callback: AsyncCallback): void +sendEnvelopeCmd\(slotId: number, cmd: string, callback: AsyncCallback\\): void Sends an envelope command to the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3490,6 +3543,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3508,7 +3562,7 @@ sim.sendEnvelopeCmd(0, "ls", (err) => { ## sim.sendEnvelopeCmd8+ -sendEnvelopeCmd(slotId: number, cmd: string): Promise +sendEnvelopeCmd\(slotId: number, cmd: string\): Promise\ Sends an envelope command to the SIM card in the specified slot. This API uses a promise to return the result. @@ -3538,6 +3592,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3558,7 +3613,7 @@ promise.then(() => { ## sim.sendTerminalResponseCmd8+ -sendTerminalResponseCmd(slotId: number, cmd: string, callback: AsyncCallback): void +sendTerminalResponseCmd\(slotId: number, cmd: string, callback: AsyncCallback\\): void Sends a terminal response command to the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3583,6 +3638,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3601,7 +3657,7 @@ sim.sendTerminalResponseCmd(0, "ls", (err) => { ## sim.sendTerminalResponseCmd8+ -sendTerminalResponseCmd(slotId: number, cmd: string): Promise +sendTerminalResponseCmd\(slotId: number, cmd: string\): Promise\ Sends a terminal response command to the SIM card in the specified slot. This API uses a promise to return the result. @@ -3631,6 +3687,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3652,7 +3709,7 @@ promise.then(() => { ## sim.unlockSimLock8+ -unlockSimLock(slotId: number, lockInfo: PersoLockInfo, callback: AsyncCallback): void +unlockSimLock\(slotId: number, lockInfo: PersoLockInfo, callback: AsyncCallback\\): void Unlocks the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3677,6 +3734,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3700,7 +3758,7 @@ sim.unlockSimLock(0, persoLockInfo, (err, data) => { ## sim.unlockSimLock8+ -unlockSimLock(slotId: number, lockInfo: PersoLockInfo): Promise +unlockSimLock\(slotId: number, lockInfo: PersoLockInfo\): Promise\ Unlocks the SIM card in the specified slot. This API uses a promise to return the result. @@ -3730,6 +3788,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -3755,7 +3814,7 @@ promise.then(data => { ## sim.getOpKey9+ -getOpKey(slotId: number, callback: AsyncCallback): void +getOpKey\(slotId: number, callback: AsyncCallback\): void Obtains the opkey of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3800,7 +3859,7 @@ try { ## sim.getOpKey9+ -getOpKey(slotId: number): Promise +getOpKey\(slotId: number\): Promise\ Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. @@ -3844,7 +3903,7 @@ try { ## sim.getOpName9+ -getOpName(slotId: number, callback: AsyncCallback): void +getOpName\(slotId: number, callback: AsyncCallback\\): void Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -3889,7 +3948,7 @@ try { ## sim.getOpName9+ -getOpName(slotId: number): Promise +getOpName\(slotId: number\): Promise\ Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 464f34595cc67c5051524d2f7f6ef0753bede543..b959988ba1c900b0ef4273ec6773a504076c76a6 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -14,7 +14,7 @@ import sms from '@ohos.telephony.sms'; ## sms.createMessage -createMessage\(pdu: Array<number>, specification: string, callback: AsyncCallback\): void +createMessage\(pdu: Array<number>, specification: string, callback: AsyncCallback\\): void Creates an SMS instance based on the protocol data unit (PDU) and specified SMS protocol. This API uses an asynchronous callback to return the result. @@ -28,6 +28,18 @@ Creates an SMS instance based on the protocol data unit (PDU) and specified SMS | specification | string | Yes | SMS protocol type.
- **3gpp**: GSM/UMTS/LTE SMS
- **3gpp2**: CDMA SMS| | callback | AsyncCallback<[ShortMessage](#shortmessage)> | Yes | Callback used to return the result. | +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -42,7 +54,7 @@ sms.createMessage(pdu, specification, (err, data) => { ## sms.createMessage -createMessage\(pdu: Array<number>, specification: string\): Promise +createMessage\(pdu: Array<number>, specification: string\): Promise\ Creates an SMS instance based on the PDU and specified SMS protocol. This API uses a promise to return the result. @@ -61,6 +73,18 @@ Creates an SMS instance based on the PDU and specified SMS protocol. This API us | -------------------------------------------- | --------------------------------- | | Promise<[ShortMessage](#shortmessage)> | Promise used to return the result.| +**Error codes** + +For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + **Example** ```js @@ -77,7 +101,7 @@ promise.then(data => { ## sms.sendMessage -sendMessage(options: SendMessageOptions): void +sendMessage\(options: SendMessageOptions\): void Sends an SMS message. @@ -197,6 +221,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -244,6 +269,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -264,7 +290,7 @@ promise.then(() => { ## sms.setSmscAddr7+ -setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback\): void +setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback\\): void Sets the short message service center (SMSC) address. This API uses an asynchronous callback to return the result. @@ -289,6 +315,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -338,6 +365,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -360,7 +388,7 @@ promise.then(() => { ## sms.getSmscAddr7+ -getSmscAddr\(slotId: number, callback: AsyncCallback\): void +getSmscAddr\(slotId: number, callback: AsyncCallback\\): void Obtains the SMSC address. This API uses an asynchronous callback to return the result. @@ -384,6 +412,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -402,7 +431,7 @@ sms.getSmscAddr(slotId, (err, data) => { ## sms.getSmscAddr7+ -getSmscAddr\(slotId: number\): Promise +getSmscAddr\(slotId: number\): Promise\ Obtains the SMSC address. This API uses a promise to return the result. @@ -431,6 +460,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -451,7 +481,7 @@ promise.then(data => { ## sms.hasSmsCapability7+ -hasSmsCapability(): boolean +hasSmsCapability\(\): boolean Checks whether the current device can send and receive SMS messages. This API works in synchronous mode. @@ -470,7 +500,7 @@ console.log(`hasSmsCapability: ${JSON.stringify(result)}`); ## sms.splitMessage8+ -splitMessage(content: string, callback: AsyncCallback>): void +splitMessage\(content: string, callback: AsyncCallback\\>\): void Splits an SMS message into multiple segments. This API uses an asynchronous callback to return the result. @@ -494,6 +524,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -512,7 +543,7 @@ sms.splitMessage(content, (err, data) => { ## sms.splitMessage8+ -splitMessage(content: string): Promise> +splitMessage\(content: string\): Promise\\> Splits an SMS message into multiple segments. This API uses a promise to return the result. @@ -541,6 +572,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -561,7 +593,7 @@ promise.then(data => { ## sms.addSimMessage7+ -addSimMessage(options: SimMessageOptions, callback: AsyncCallback): void +addSimMessage\(options: SimMessageOptions, callback: AsyncCallback\\): void Adds a SIM message. This API uses an asynchronous callback to return the result. @@ -585,6 +617,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -608,7 +641,7 @@ sms.addSimMessage(simMessageOptions, (err) => { ## sms.addSimMessage7+ -addSimMessage(options: SimMessageOptions): Promise +addSimMessage\(options: SimMessageOptions\): Promise\ Adds a SIM message. This API uses a promise to return the result. @@ -637,6 +670,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -662,7 +696,7 @@ promise.then(() => { ## sms.delSimMessage7+ -delSimMessage(slotId: number, msgIndex: number, callback: AsyncCallback): void +delSimMessage\(slotId: number, msgIndex: number, callback: AsyncCallback\\): void Deletes a SIM message. This API uses an asynchronous callback to return the result. @@ -687,6 +721,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -706,7 +741,7 @@ sms.delSimMessage(slotId, msgIndex, (err) => { ## sms.delSimMessage7+ -delSimMessage(slotId: number, msgIndex: number): Promise +delSimMessage\(slotId: number, msgIndex: number\): Promise\ Deletes a SIM message. This API uses a promise to return the result. @@ -736,6 +771,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -757,7 +793,7 @@ promise.then(() => { ## sms.updateSimMessage7+ -updateSimMessage(options: UpdateSimMessageOptions, callback: AsyncCallback): void +updateSimMessage\(options: UpdateSimMessageOptions, callback: AsyncCallback\\): void Updates a SIM message. This API uses an asynchronous callback to return the result. @@ -781,6 +817,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -805,7 +842,7 @@ sms.updateSimMessage(updateSimMessageOptions, (err) => { ## sms.updateSimMessage7+ -updateSimMessage(options: UpdateSimMessageOptions): Promise +updateSimMessage\(options: UpdateSimMessageOptions\): Promise\ Updates a SIM message. This API uses a promise to return the result. @@ -834,6 +871,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -860,7 +898,7 @@ promise.then(() => { ## sms.getAllSimMessages7+ -getAllSimMessages(slotId: number, callback: AsyncCallback>): void +getAllSimMessages\(slotId: number, callback: AsyncCallback\\>\): void Obtains all SIM card messages. This API uses an asynchronous callback to return the result. @@ -884,6 +922,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -902,7 +941,7 @@ sms.getAllSimMessages(slotId, (err, data) => { ## sms.getAllSimMessages7+ -getAllSimMessages(slotId: number): Promise> +getAllSimMessages\(slotId: number\): Promise\\> Obtains all SIM card messages. This API uses a promise to return the result. @@ -931,6 +970,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -951,7 +991,7 @@ promise.then(data => { ## sms.setCBConfig7+ -setCBConfig(options: CBConfigOptions, callback: AsyncCallback): void +setCBConfig\(options: CBConfigOptions, callback: AsyncCallback\\): void Sets the cell broadcast configuration. This API uses an asynchronous callback to return the result. @@ -975,6 +1015,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -999,7 +1040,7 @@ sms.setCBConfig(cbConfigOptions, (err) => { ## sms.setCBConfig7+ -setCBConfig(options: CBConfigOptions): Promise +setCBConfig\(options: CBConfigOptions\): Promise\ Sets the cell broadcast configuration. This API uses a promise to return the result. @@ -1028,6 +1069,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1054,7 +1096,7 @@ promise.then(() => { ## sms.getSmsSegmentsInfo8+ -getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean, callback: AsyncCallback): void +getSmsSegmentsInfo\(slotId: number, message: string, force7bit: boolean, callback: AsyncCallback\\): void Obtains SMS message segment information. This API uses an asynchronous callback to return the result. @@ -1077,6 +1119,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1095,7 +1138,7 @@ sms.getSmsSegmentsInfo(slotId, "message", false, (err, data) => { ## sms.getSmsSegmentsInfo8+ -getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean): Promise +getSmsSegmentsInfo\(slotId: number, message: string, force7bit: boolean\): Promise\ Obtains SMS message segment information. This API uses a promise to return the result. @@ -1123,6 +1166,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1143,7 +1187,7 @@ promise.then(data => { ## sms.isImsSmsSupported8+ -isImsSmsSupported(slotId: number, callback: AsyncCallback): void +isImsSmsSupported\(slotId: number, callback: AsyncCallback\\): void Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result. @@ -1164,6 +1208,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1182,7 +1227,7 @@ sms.isImsSmsSupported(slotId, (err, data) => { ## sms.isImsSmsSupported8+ -isImsSmsSupported(slotId: number): Promise +isImsSmsSupported\(slotId: number\): Promise\ This API uses an asynchronous callback to return the result. This API uses a promise to return the result. @@ -1208,6 +1253,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1228,7 +1274,7 @@ promise.then(data => { ## sms.getImsShortMessageFormat8+ -getImsShortMessageFormat(callback: AsyncCallback): void +getImsShortMessageFormat\(callback: AsyncCallback\\): void Obtains the SMS format supported by the IMS. This API uses an asynchronous callback to return the result. @@ -1248,6 +1294,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -1265,7 +1312,7 @@ sms.getImsShortMessageFormat((err, data) => { ## sms.getImsShortMessageFormat8+ -getImsShortMessageFormat(): Promise +getImsShortMessageFormat\(\): Promise\ Obtains the SMS format supported by the IMS. This API uses a promise to return the result. @@ -1285,8 +1332,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -1304,7 +1350,7 @@ promise.then(data => { ## sms.decodeMms8+ -decodeMms(mmsFilePathName: string | Array, callback: AsyncCallback): void +decodeMms\(mmsFilePathName: string | Array\, callback: AsyncCallback\\): void Decodes MMS messages. This API uses an asynchronous callback to return the result. @@ -1343,7 +1389,7 @@ sms.decodeMms(mmsFilePathName, (err, data) => { ## sms.decodeMms8+ -decodeMms(mmsFilePathName: string | Array): Promise +decodeMms\(mmsFilePathName: string | Array\\): Promise\ Decodes MMS messages. This API uses a promise to return the result. @@ -1389,7 +1435,7 @@ promise.then(data => { ## sms.encodeMms8+ -encodeMms(mms: MmsInformation, callback: AsyncCallback>): void +encodeMms\(mms: MmsInformation, callback: AsyncCallback\\>\): void MMS message code. This API uses an asynchronous callback to return the result. @@ -1436,7 +1482,7 @@ sms.encodeMms(mmsInformation, (err, data) => { ## sms.encodeMms8+ -encodeMms(mms: MmsInformation): Promise> +encodeMms\(mms: MmsInformation\): Promise\\> MMS message code. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index b03d07b806884ffccbba82cea8eedc88c89fdf3b..9c743577ac99adfdddc58613515b32cbc4dc46e2 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -12,7 +12,7 @@ The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSoc import socket from '@ohos.net.socket'; ``` -## socket.constructUDPSocketInstance +## socket.constructUDPSocketInstance7+ constructUDPSocketInstance(): UDPSocket @@ -32,19 +32,16 @@ Creates a **UDPSocket** object. let udp = socket.constructUDPSocketInstance(); ``` -## UDPSocket +## UDPSocket7+ Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object. -### bind +### bind7+ bind(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. -> **NOTE** -> This API is used for the client to create a socket. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -67,7 +64,7 @@ Binds the IP address and port number. The port number can be specified or random ```js let udp = socket.constructUDPSocketInstance(); -udp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { +udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -76,15 +73,12 @@ udp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { }) ``` -### bind +### bind7+ bind(address: NetAddress): Promise\ Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. -> **NOTE** -> This API is used for the client to create a socket. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -120,7 +114,7 @@ promise.then(() => { }); ``` -### send +### send7+ send(options: UDPSendOptions, callback: AsyncCallback\): void @@ -166,7 +160,7 @@ udp.send({ }) ``` -### send +### send7+ send(options: UDPSendOptions): Promise\ @@ -216,7 +210,7 @@ promise.then(() => { }); ``` -### close +### close7+ close(callback: AsyncCallback\): void @@ -245,7 +239,7 @@ udp.close(err => { }) ``` -### close +### close7+ close(): Promise\ @@ -273,7 +267,7 @@ promise.then(() => { }); ``` -### getState +### getState7+ getState(callback: AsyncCallback\): void @@ -318,7 +312,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { }) ``` -### getState +### getState7+ getState(): Promise\ @@ -357,7 +351,7 @@ promise.then(err => { }); ``` -### setExtraOptions +### setExtraOptions7+ setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\): void @@ -410,7 +404,7 @@ udp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { }) ``` -### setExtraOptions +### setExtraOptions7+ setExtraOptions(options: UDPExtraOptions): Promise\ @@ -466,7 +460,7 @@ promise.then(() => { }); ``` -### on('message') +### on('message')7+ on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void @@ -497,7 +491,7 @@ udp.on('message', value => { }); ``` -### off('message') +### off('message')7+ off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void @@ -535,7 +529,7 @@ udp.off('message', callback); udp.off('message'); ``` -### on('listening' | 'close') +### on('listening' | 'close')7+ on(type: 'listening' | 'close', callback: Callback\): void @@ -562,7 +556,7 @@ udp.on('close', () => { }); ``` -### off('listening' | 'close') +### off('listening' | 'close')7+ off(type: 'listening' | 'close', callback?: Callback\): void @@ -600,7 +594,7 @@ udp.off('close', callback2); udp.off('close'); ``` -### on('error') +### on('error')7+ on(type: 'error', callback: ErrorCallback): void @@ -624,7 +618,7 @@ udp.on('error', err => { }); ``` -### off('error') +### off('error')7+ off(type: 'error', callback?: ErrorCallback): void @@ -655,7 +649,7 @@ udp.off('error', callback); udp.off('error'); ``` -## NetAddress +## NetAddress7+ Defines the destination address. @@ -667,7 +661,7 @@ Defines the destination address. | port | number | No | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port. | | family | number | No | Network protocol type.
- **1**: IPv4
- **2**: IPv6
The default value is **1**.| -## UDPSendOptions +## UDPSendOptions7+ Defines the parameters for sending data over the UDPSocket connection. @@ -678,7 +672,7 @@ Defines the parameters for sending data over the UDPSocket connection. | data | string \| ArrayBuffer7+ | Yes | Data to send. | | address | [NetAddress](#netaddress) | Yes | Destination address.| -## UDPExtraOptions +## UDPExtraOptions7+ Defines other properties of the UDPSocket connection. @@ -692,7 +686,7 @@ Defines other properties of the UDPSocket connection. | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | | socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms.| -## SocketStateBase +## SocketStateBase7+ Defines the status of the socket connection. @@ -704,7 +698,7 @@ Defines the status of the socket connection. | isClose | boolean | Yes | Whether the connection is in the closed state.| | isConnected | boolean | Yes | Whether the connection is in the connected state.| -## SocketRemoteInfo +## SocketRemoteInfo7+ Defines information about the socket connection. @@ -723,7 +717,7 @@ The UDP error code mapping is in the format of 2301000 + Linux kernel error code For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). -## socket.constructTCPSocketInstance +## socket.constructTCPSocketInstance7+ constructTCPSocketInstance(): TCPSocket @@ -743,19 +737,16 @@ Creates a **TCPSocket** object. let tcp = socket.constructTCPSocketInstance(); ``` -## TCPSocket +## TCPSocket7+ Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object. -### bind +### bind7+ bind(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. -> **NOTE** -> This API is used for the client to create a socket. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -778,7 +769,7 @@ Binds the IP address and port number. The port number can be specified or random ```js let tcp = socket.constructTCPSocketInstance(); -tcp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { +tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -787,15 +778,12 @@ tcp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { }) ``` -### bind +### bind7+ bind(address: NetAddress): Promise\ Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. -> **NOTE** -> This API is used for the client to create a socket. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -831,7 +819,7 @@ promise.then(() => { }); ``` -### connect +### connect7+ connect(options: TCPConnectOptions, callback: AsyncCallback\): void @@ -871,7 +859,7 @@ tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, tim }) ``` -### connect +### connect7+ connect(options: TCPConnectOptions): Promise\ @@ -912,7 +900,7 @@ promise.then(() => { }); ``` -### send +### send7+ send(options: TCPSendOptions, callback: AsyncCallback\): void @@ -958,7 +946,7 @@ tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, tim }) ``` -### send +### send7+ send(options: TCPSendOptions): Promise\ @@ -1010,7 +998,7 @@ promise1.then(() => { }); ``` -### close +### close7+ close(callback: AsyncCallback\): void @@ -1045,7 +1033,7 @@ tcp.close(err => { }) ``` -### close +### close7+ close(): Promise\ @@ -1079,7 +1067,7 @@ promise.then(() => { }); ``` -### getRemoteAddress +### getRemoteAddress7+ getRemoteAddress(callback: AsyncCallback\): void @@ -1120,7 +1108,7 @@ tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, tim }); ``` -### getRemoteAddress +### getRemoteAddress7+ getRemoteAddress(): Promise\ @@ -1163,7 +1151,7 @@ promise1.then(() => { }); ``` -### getState +### getState7+ getState(callback: AsyncCallback\): void @@ -1204,7 +1192,7 @@ let promise = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, fa }); ``` -### getState +### getState7+ getState(): Promise\ @@ -1247,7 +1235,7 @@ promise.then(() => { }); ``` -### setExtraOptions +### setExtraOptions7+ setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void @@ -1299,7 +1287,7 @@ let promise = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, fa }); ``` -### setExtraOptions +### setExtraOptions7+ setExtraOptions(options: TCPExtraOptions): Promise\ @@ -1358,7 +1346,7 @@ promise.then(() => { }); ``` -### on('message') +### on('message')7+ on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void @@ -1389,7 +1377,7 @@ tcp.on('message', value => { }); ``` -### off('message') +### off('message')7+ off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void @@ -1427,7 +1415,7 @@ tcp.off('message', callback); tcp.off('message'); ``` -### on('connect' | 'close') +### on('connect' | 'close')7+ on(type: 'connect' | 'close', callback: Callback\): void @@ -1454,7 +1442,7 @@ tcp.on('close', () => { }); ``` -### off('connect' | 'close') +### off('connect' | 'close')7+ off(type: 'connect' | 'close', callback?: Callback\): void @@ -1492,7 +1480,7 @@ tcp.off('close', callback2); tcp.off('close'); ``` -### on('error') +### on('error')7+ on(type: 'error', callback: ErrorCallback): void @@ -1516,7 +1504,7 @@ tcp.on('error', err => { }); ``` -### off('error') +### off('error')7+ off(type: 'error', callback?: ErrorCallback): void @@ -1547,7 +1535,7 @@ tcp.off('error', callback); tcp.off('error'); ``` -## TCPConnectOptions +## TCPConnectOptions7+ Defines TCPSocket connection parameters. @@ -1558,7 +1546,7 @@ Defines TCPSocket connection parameters. | address | [NetAddress](#netaddress) | Yes | Bound IP address and port number. | | timeout | number | No | Timeout duration of the TCPSocket connection, in ms.| -## TCPSendOptions +## TCPSendOptions7+ Defines the parameters for sending data over the TCPSocket connection. @@ -1569,7 +1557,7 @@ Defines the parameters for sending data over the TCPSocket connection. | data | string\| ArrayBuffer7+ | Yes | Data to send. | | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| -## TCPExtraOptions +## TCPExtraOptions7+ Defines other properties of the TCPSocket connection. @@ -1881,7 +1869,7 @@ promise.then(() => { }); ``` -### on('message') +### on('message')9+ on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void; @@ -1912,7 +1900,7 @@ tls.on('message', value => { }); ``` -### off('message') +### off('message')9+ off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void @@ -1948,7 +1936,7 @@ tls.on('message', callback); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. tls.off('message', callback); ``` -### on('connect' | 'close') +### on('connect' | 'close')9+ on(type: 'connect' | 'close', callback: Callback\): void @@ -1975,7 +1963,7 @@ tls.on('close', () => { }); ``` -### off('connect' | 'close') +### off('connect' | 'close')9+ off(type: 'connect' | 'close', callback?: Callback\): void @@ -2012,7 +2000,7 @@ tls.on('close', callback2); tls.off('close', callback2); ``` -### on('error') +### on('error')9+ on(type: 'error', callback: ErrorCallback): void @@ -2036,7 +2024,7 @@ tls.on('error', err => { }); ``` -### off('error') +### off('error')9+ off(type: 'error', callback?: ErrorCallback): void @@ -2675,7 +2663,7 @@ Sends a message to the server after a TLSSocket connection is established. This | ------- | -------------------------------------------- | | 401 | Parameter error. | | 2303501 | SSL is null. | -| 2303503 | Error in tls writing | +| 2303503 | Error in tls writing. | | 2303505 | Error occurred in the tls system call. | | 2303506 | Error clearing tls connection. | | 2300002 | System internal error. | @@ -2712,7 +2700,7 @@ Sends a message to the server after a TLSSocket connection is established. This | ------- | -------------------------------------------- | | 401 | Parameter error. | | 2303501 | SSL is null. | -| 2303503 | Error in tls writing | +| 2303503 | Error in tls writing. | | 2303505 | Error occurred in the tls system call. | | 2303506 | Error clearing tls connection. | | 2300002 | System internal error. | @@ -2846,7 +2834,3 @@ Enumerates TLS protocol versions. Defines the certificate raw data. **System capability**: SystemCapability.Communication.NetStack - -| Type | Description | -| --------------------------------------------------------------------- | --------------------- | -|[cert.EncodingBlob](js-apis-cert.md#datablob) | Data and encoding format of the certificate.| diff --git a/en/application-dev/reference/apis/js-apis-system-fetch.md b/en/application-dev/reference/apis/js-apis-system-fetch.md index 6144d903c19116e693841e5f4a55840aac43e68b..96bc642f5214e48b09df204a314bd694677a77f4 100644 --- a/en/application-dev/reference/apis/js-apis-system-fetch.md +++ b/en/application-dev/reference/apis/js-apis-system-fetch.md @@ -16,7 +16,48 @@ import fetch from '@system.fetch'; ## fetch.fetch3+ -fetch(Object): void +fetch(options:{ + /** + * Resource URL. + * @since 3 + */ + url: string; + /** + * Request parameter, which can be of the string type or a JSON object. + * @since 3 + */ + data?: string | object; + /** + * Request header, which accommodates all attributes of the request. + * @since 3 + */ + header?: Object; + /** + * Request methods available: OPTIONS, GET, HEAD, POST, PUT, DELETE and TRACE. The default value is GET. + * @since 3 + */ + method?: string; + /** + * The return type can be text, or JSON. By default, the return type is determined based on Content-Type in the header returned by the server. + * @since 3 + */ + responseType?: string; + /** + * Called when the network data is obtained successfully. + * @since 3 + */ + success?: (data: FetchResponse) => void; + /** + * Called when the network data fails to be obtained. + * @since 3 + */ + fail?: (data: any, code: number) => void; + /** + * Called when the execution is completed. + * @since 3 + */ + complete?: () => void; + } ): void Obtains data through a network. @@ -43,7 +84,9 @@ Obtains data through a network. | Object | Not set| The default value of **Content-Type** is **application/x-www-form-urlencoded**. The **data** value is encoded based on the URL rule and appended in the request body.| | Object | application/x-www-form-urlencoded | The value of data is encoded based on the URL rule and is used as the request body.| -## FetchResponse +## FetchResponse3+ + +**System capability**: SystemCapability.Communication.NetStack | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-system-network.md b/en/application-dev/reference/apis/js-apis-system-network.md index 5fe6e782edc352c4d49377b4e8d9a4343d8435a6..232c2be8d60b3b893fbebc1119b7d9e807d80ddf 100644 --- a/en/application-dev/reference/apis/js-apis-system-network.md +++ b/en/application-dev/reference/apis/js-apis-system-network.md @@ -21,9 +21,25 @@ ohos.permission.GET_WIFI_INFO ohos.permission.GET_NETWORK_INFO -## network.getType - -getType(Object): void +## network.getType3+ + +getType(options?: { + /** + * Called when the network type is obtained. + * @since 3 + */ + success?: (data: NetworkResponse) => void; + /** + * Called when the network type fails to be obtained. + * @since 3 + */ + fail?: (data: any, code: number) => void; + /** + * Called when the execution is completed. + * @since 3 + */ + complete?: () => void; + }): void Obtains the network type. @@ -61,9 +77,20 @@ export default { ``` -## network.subscribe +## network.subscribe3+ -subscribe(Object): void +subscribe(options?:{ + /** + * Called when the network connection state changes. + * @since 3 + */ + success?: (data: NetworkResponse) => void; + /** + * Called when the listening fails. + * @since 3 + */ + fail?: (data: any, code: number) => void; + }): void Listens to the network connection state. If this method is called multiple times, the last call takes effect. @@ -101,7 +128,7 @@ export default { ``` -## network.unsubscribe +## network.unsubscribe3+ unsubscribe(): void @@ -120,7 +147,7 @@ export default { ``` -## NetworkResponse +## NetworkResponse3+ **System capability**: SystemCapability.Communication.NetManager.Core diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index 0dc490855181cedbe2199810dd45a28384c75c71..fceb893eb40373ad0f4cff2faa34c10018ccb3b8 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -30,7 +30,7 @@ Obtains the value of the system parameter with the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| **Return value** @@ -124,7 +124,7 @@ Obtains the value of the system parameter with the specified key. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md b/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md index 8b4be482d1e6b6b1bae52827c0104387ed16601d..12f2d8448418cac174e471bee660900ceee0b8de 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md +++ b/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md @@ -29,7 +29,7 @@ Obtains the value of the system parameter with the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| **Return value** @@ -123,7 +123,7 @@ Obtains the value of the system parameter with the specified key. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | string | Yes| Key of the system parameter.| -| def | string | No| Default value.| +| def | string | No| Default value of the system parameter.
It works only when the system parameter does not exist.
The value can be **undefined** (in which case an empty string will be returned) or any custom value.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-system-sensor.md b/en/application-dev/reference/apis/js-apis-system-sensor.md index ccf4be2ce7e5a660ef1622e90bce2c204634906e..945be8c89d79e74cb6bc284e90089edad1709b4e 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -89,7 +89,7 @@ Subscribes to data changes of the compass sensor. If this API is called multiple ```js sensor.subscribeCompass({ success: function(ret) { - console.log('get data direction:' + ret.direction); + console.log('Get data direction:' + ret.direction); }, fail: function(data, code) { console.error('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -133,7 +133,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip ```js sensor.subscribeProximity({ success: function(ret) { - console.log('get data distance:' + ret.distance); + console.log('Get data distance:' + ret.distance); }, fail: function(data, code) { console.error('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -177,7 +177,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu ```js sensor.subscribeLight({ success: function(ret) { - console.log('get data intensity:' + ret.intensity); + console.log('Get data intensity:' + ret.intensity); }, fail: function(data, code) { console.error('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -223,7 +223,7 @@ Subscribes to data changes of the step counter sensor. If this API is called mul ```js sensor.subscribeStepCounter({ success: function(ret) { - console.log('get step value:' + ret.steps); + console.log('Get step value:' + ret.steps); }, fail: function(data, code) { console.log('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -270,7 +270,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip ```js sensor.subscribeBarometer({ success: function(ret) { - console.log('get data value:' + ret.pressure); + console.log('Get data value:' + ret.pressure); }, fail: function(data, code) { console.log('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -318,7 +318,7 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi ```js sensor.subscribeHeartRate({ success: function(ret) { - console.log('get heartrate value:' + ret.heartRate); + console.log('Get heartrate value:' + ret.heartRate); }, fail: function(data, code) { console.log('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -365,7 +365,7 @@ Subscribes to changes of the wearing state of a wearable device. If this API is ```js sensor.subscribeOnBodyState({ success: function(ret) { - console.log('get on-body state value:' + ret.value); + console.log('Get on-body state value:' + ret.value); }, fail: function(data, code) { console.log('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -409,7 +409,7 @@ Obtains the wearing state of a wearable device. ```js sensor.getOnBodyState({ success: function(ret) { - console.log('on body state: ' + ret.value); + console.log('On body state: ' + ret.value); }, fail: function(data, code) { console.log('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -710,7 +710,7 @@ Defines the wearing state. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------ | -| success | [OnBodyStateResponse](#onbodystateresponse) | No | Callback upon a successful API call.| +| success | [OnBodyStateResponse](#onbodystateresponse) | Yes | Callback upon a successful API call.| | fail | Function | No | Callback upon an API call failure.| | complete | Function | No | Called when the API call is complete.| diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md index c1741b242f4b98d76df8ad4868dfc75d8089b36a..4eb81b7153748544ead741b01fb8d3cdb334ea93 100644 --- a/en/application-dev/reference/apis/js-apis-taskpool.md +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -19,7 +19,7 @@ import taskpool from '@ohos.taskpool'; ## Priority -Enumerates the priorities available for created tasks. (This enum is not supported yet.) +Enumerates the priorities available for created tasks. **System capability**: SystemCapability.Utils.Lang @@ -29,6 +29,45 @@ Enumerates the priorities available for created tasks. (This enum is not support | MEDIUM | 1 | The task has a medium priority.| | LOW | 2 | The task has a low priority.| +**Example** + +```ts +function func(args) { + "use concurrent"; + console.log("func: " + args); + return args; +} +async function taskpoolTest() { + let task = new taskpool.Task(func, 100); + + let highCount = 0; + let mediumCount = 0; + let lowCount = 0; + let allCount = 100; + for (let i = 0; i < allCount; i++) { + taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { + lowCount++; + console.log("taskpool lowCount is :" + lowCount); + }).catch((e) => { + console.error("low task error: " + e); + }) + taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { + mediumCount++; + console.log("taskpool mediumCount is :" + mediumCount); + }).catch((e) => { + console.error("medium task error: " + e); + }) + taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { + highCount++; + console.log("taskpool highCount is :" + highCount); + }).catch((e) => { + console.error("high task error: " + e); + }) + } +} +taskpoolTest(); +``` + ## Task Implements a task. Before using any of the following APIs, you must create a **Task** instance. @@ -46,7 +85,7 @@ A constructor used to create a **Task** instance. | Name| Type | Mandatory| Description | | ------ | --------- | ---- | -------------------------------------------------------------------- | | func | Function | Yes | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | -| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.| **Error codes** @@ -81,7 +120,7 @@ let task = new taskpool.Task(func, "this is my first Task"); execute(func: Function, ...args: unknown[]): Promise\ -Executes a task in the task pool. You must pass in a function and arguments to execute the task, and the task executed in this mode cannot be canceled. +Places the function to be executed in the internal task queue of the task pool. The function will be distributed to the worker thread for execution. The function to be executed in this mode cannot be canceled. **System capability**: SystemCapability.Utils.Lang @@ -89,8 +128,8 @@ Executes a task in the task pool. You must pass in a function and arguments to e | Name| Type | Mandatory| Description | | ------ | --------- | ---- | ---------------------------------------------------------------------- | -| func | Function | Yes | Function used to execute the task. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | -| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| func | Function | Yes | Function to be executed. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.| **Return value** @@ -129,16 +168,16 @@ taskpoolTest(); execute(task: Task, priority?: Priority): Promise\ -Executes a task in the task pool. You must pass in a created task, and the task executed in this mode can be canceled. +Places a task in the internal task queue of the task pool. The task will be distributed to the worker thread for execution. The task to be executed in this mode can be canceled. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------------------ | -| task | [Task](#task) | Yes | Task to be executed. | -| priority | [Priority](#priority) | No | Priority of the task (not supported yet).| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------- | +| task | [Task](#task) | Yes | Task to be executed. | +| priority | [Priority](#priority) | No | Priority of the task. The default value is **MEDIUM**.| **Return value** @@ -197,18 +236,18 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | 10200015 | If the task is not exist. | | 10200016 | If the task is running. | -**Example** +**Example of successful task cancellation** ```ts -@Concurrent function func(args) { + "use concurrent"; console.log("func: " + args); return args; } async function taskpoolTest() { let task = new taskpool.Task(func, 100); - let value = await taskpool.execute(task); + taskpool.execute(task); try { taskpool.cancel(task); } catch (e) { @@ -219,6 +258,66 @@ async function taskpoolTest() { taskpoolTest(); ``` +**Example of a failure to cancel a task that has been executed** + +```ts +function func(args) { + "use concurrent"; + console.log("func: " + args); + return args; +} + +async function taskpoolTest() { + let task = new taskpool.Task(func, 100); + let value = taskpool.execute(task); + let start = new Date().getTime(); + while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed. + continue; + } + + try { + taskpool.cancel(task); // The task has been executed and fails to be canceled. + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } +} + +taskpoolTest(); +``` + +**Example of a failure to cancel an ongoing task** + +```ts +function func(args) { + "use concurrent"; + console.log("func: " + args); + return args; +} + +async function taskpoolTest() { + let task1 = new taskpool.Task(func, 100); + let task2 = new taskpool.Task(func, 200); + let task3 = new taskpool.Task(func, 300); + let task4 = new taskpool.Task(func, 400); + let task5 = new taskpool.Task(func, 500); + let task6 = new taskpool.Task(func, 600); + + let res1 = taskpool.execute(task1); + let res2 = taskpool.execute(task2); + let res3 = taskpool.execute(task3); + let res4 = taskpool.execute(task4); + let res5 = taskpool.execute(task5); + let res6 = taskpool.execute(task6); + try { + taskpool.cancel(task1); // task1 is being executed and fails to be canceled. + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } +} + +taskpoolTest(); +``` + ## Additional Information ### Sequenceable Data Types diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index a7a1338277a9b05840122488abb6553fd9b86e84..4b234fb7c765a888a037d1034856225d069e5bb3 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -1,6 +1,6 @@ # @ohos.telephony.data (Cellular Data) -The **data** module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. +The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. >**NOTE** > @@ -24,7 +24,7 @@ Obtains the default slot of the SIM card used for mobile data. This API uses an | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
**0**: card slot 1.
**1**: card slot 2.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
**0**: card slot 1
**1**: card slot 2| **Example** @@ -46,7 +46,7 @@ Obtains the default slot of the SIM card used for mobile data. This API uses a p | Type | Description | | ----------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
**0**: card slot 1.
**1**: card slot 2.| +| Promise\ | Promise used to return the result.
**0**: card slot 1
**1**: card slot 2| **Example** @@ -71,7 +71,7 @@ Obtains the default SIM card used for mobile data synchronously. | Type | Description | | ------ | -------------------------------------------------- | -| number | Card slot ID.
**0**: card slot 1.
**1**: card slot 2.| +| number | Card slot ID.
**0**: card slot 1
**1**: card slot 2| **Example** @@ -87,7 +87,7 @@ Sets the default slot of the SIM card used for mobile data. This API uses an asy **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -95,7 +95,7 @@ Sets the default slot of the SIM card used for mobile data. This API uses an asy | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
**0**: card slot 1.
**1**: card slot 2.
**-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
**0**: card slot 1
**1**: card slot 2
**-1**: Clears the default configuration.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** @@ -105,6 +105,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -129,7 +130,7 @@ Sets the default slot of the SIM card used for mobile data. This API uses a prom **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -137,7 +138,7 @@ Sets the default slot of the SIM card used for mobile data. This API uses a prom | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
**0**: card slot 1.
**1**: card slot 2.
**-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
**0**: card slot 1
**1**: card slot 2
**-1**: Clears the default configuration.| **Return value** @@ -152,6 +153,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -325,8 +327,6 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -356,7 +356,7 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1.
**1**: card slot 2. | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2 | | callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: Roaming is enabled for the cellular data service.
**false**: Roaming is disabled for the cellular data service.| **Error codes** @@ -394,7 +394,7 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1.
**1**: card slot 2.| +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| **Return value** @@ -428,13 +428,13 @@ promise.then((data) => { ## data.enableCellularData -enableCellularData(callback: AsyncCallback): void +enableCellularData(callback: AsyncCallback\): void Enables the cellular data service. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -451,6 +451,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -467,13 +468,13 @@ data.enableCellularData((err) => { ## data.enableCellularData -enableCellularData(): Promise +enableCellularData(): Promise\ Enables the cellular data service. This API uses a promise to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -490,8 +491,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -509,13 +509,13 @@ promise.then(() => { ## data.disableCellularData -disableCellularData(callback: AsyncCallback): void +disableCellularData(callback: AsyncCallback\): void Disables the cellular data service. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -532,6 +532,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -548,13 +549,13 @@ data.disableCellularData((err) => { ## data.disableCellularData -disableCellularData(): Promise +disableCellularData(): Promise\ Disables the cellular data service. This API uses a promise to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -571,8 +572,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | -| 401 | Parameter error. | -| 8300001 | Invalid parameter value. | +| 202 | Non-system applications use system APIs. | | 8300002 | Operation failed. Cannot connect to service. | | 8300003 | System internal error. | | 8300999 | Unknown error code. | @@ -590,13 +590,13 @@ promise.then(() => { ## data.enableCellularDataRoaming -enableCellularDataRoaming(slotId: number, callback: AsyncCallback): void +enableCellularDataRoaming(slotId: number, callback: AsyncCallback\): void Enables the cellular data roaming service. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -604,7 +604,7 @@ Enables the cellular data roaming service. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1.
**1**: card slot 2.| +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** @@ -614,6 +614,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -630,13 +631,13 @@ data.enableCellularDataRoaming(0, (err) => { ## data.enableCellularDataRoaming -enableCellularDataRoaming(slotId: number): Promise +enableCellularDataRoaming(slotId: number): Promise\ Enables the cellular data roaming service. This API uses a promise to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -644,7 +645,7 @@ Enables the cellular data roaming service. This API uses a promise to return the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1.
**1**: card slot 2.| +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| **Return value** @@ -659,6 +660,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -678,13 +680,13 @@ promise.then(() => { ## data.disableCellularDataRoaming -disableCellularDataRoaming(slotId: number, callback: AsyncCallback): void +disableCellularDataRoaming(slotId: number, callback: AsyncCallback\): void Disables the cellular data roaming service. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -692,7 +694,7 @@ Disables the cellular data roaming service. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1.
**1**: card slot 2.| +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** @@ -702,6 +704,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | @@ -718,13 +721,13 @@ data.disableCellularDataRoaming(0, (err) => { ## data.disableCellularDataRoaming -disableCellularDataRoaming(slotId: number): Promise +disableCellularDataRoaming(slotId: number): Promise\ Disables the cellular data roaming service. This API uses a promise to return the result. **System API**: This is a system API. -**Required permissions**: ohos.permission.SET_TELEPHONY_STATE +**Required permission**: ohos.permission.SET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CellularData @@ -732,7 +735,7 @@ Disables the cellular data roaming service. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------- | -| slotId | number | Yes | Card slot ID.
**0**: card slot 1.
**1**: card slot 2.| +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| **Return value** @@ -747,6 +750,7 @@ For details about the following error codes, see [Telephony Error Codes](../../r | ID| Error Message | | -------- | -------------------------------------------- | | 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | | 401 | Parameter error. | | 8300001 | Invalid parameter value. | | 8300002 | Operation failed. Cannot connect to service. | diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index 5291826d6fab799eb0684753379399562772f4cf..d9914d9c865911380d57548e94d068956e690ec9 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -2,7 +2,8 @@ The **thermal** module provides thermal level-related callback and query APIs to obtain the information required for thermal control. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -29,9 +30,9 @@ Subscribes to thermal level changes. For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). -| Code | Error Message | +| ID | Error Message | |---------|---------| -| 4800101 | Operation failed. Cannot connect to service.| +| 4800101 | If connecting to the service failed. | **Example** @@ -58,15 +59,15 @@ Unsubscribes from thermal level changes. | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------------------------- | -| callback | Callback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| +| callback | Callback<void> | No | Callback that returns no value. If this parameter is not set, this API unsubscribes from all callbacks.| **Error codes** For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). -| Code | Error Message | +| ID | Error Message | |---------|---------| -| 4800101 | Operation failed. Cannot connect to service.| +| 4800101 | If connecting to the service failed. | **Example** @@ -93,15 +94,15 @@ Obtains the current thermal level. | Type | Description | | ------------ | ------------ | -| ThermalLevel | Thermal level obtained.| +| ThermalLevel | Thermal level.| **Error codes** For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). -| Code | Error Message | +| ID | Error Message | |---------|---------| -| 4800101 | Operation failed. Cannot connect to service.| +| 4800101 | If connecting to the service failed. | **Example** @@ -118,8 +119,7 @@ try { subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void -> NOTE
-> This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9). Subscribes to thermal level changes. @@ -143,8 +143,7 @@ thermal.subscribeThermalLevel((level) => { unsubscribeThermalLevel(callback?: AsyncCallback\): void -> NOTE
-> This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9). Unsubscribes from thermal level changes. @@ -154,7 +153,7 @@ Unsubscribes from thermal level changes. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------- | -| callback | AsyncCallback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| +| callback | AsyncCallback<void> | No | Callback that returns no value. If this parameter is not set, this API unsubscribes from all callbacks.| **Example** @@ -168,8 +167,7 @@ thermal.unsubscribeThermalLevel(() => { getThermalLevel(): ThermalLevel -> NOTE
-> This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9). Obtains the current thermal level. diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 24f66154decc36532fdc49d4bb3273ccf8a81ba1..a6a89a8d4a94d83723d0a03853c1d4567cc7e3f2 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -23,7 +23,7 @@ A constructor used to create a **URLParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object
The default value is **null**.| **Example** @@ -150,7 +150,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this object.| **Table 1** callbackFn parameter description @@ -404,7 +404,7 @@ Creates a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object
The default value is an empty string or an empty object.| **Example** @@ -444,7 +444,7 @@ Parses a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object
The default value is an empty string or an empty object.| **Error codes** @@ -522,7 +522,7 @@ A constructor used to create a **URLSearchParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object
The default value is **null**.| **Example** @@ -665,7 +665,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this object.| **Table 1** callbackFn parameter description diff --git a/en/application-dev/reference/apis/js-apis-userFileManager.md b/en/application-dev/reference/apis/js-apis-userFileManager.md index c783b02f46c014a12ddba60432e1fe182cb93b42..a676fb1f3b86439ee314feceace04810bb5052da 100644 --- a/en/application-dev/reference/apis/js-apis-userFileManager.md +++ b/en/application-dev/reference/apis/js-apis-userFileManager.md @@ -4,8 +4,8 @@ The **userFileManager** module provides user data management capabilities, inclu > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs provided by this module are system APIs. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -49,11 +49,8 @@ let mgr = userFileManager.getUserFileMgr(context); getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; - Obtains image and video assets. This API uses an asynchronous callback to return the result. - - **System capability**: SystemCapability.FileManagement.UserFileManager.Core **Required permissions**: ohos.permission.READ_IMAGEVIDEO @@ -92,7 +89,6 @@ async function example() { } ``` - ### getPhotoAssets getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; @@ -141,6 +137,7 @@ async function example() { } } ``` + ### createPhotoAsset createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback<FileAsset>): void; @@ -261,7 +258,6 @@ async function example() { getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; - Obtains image and video albums. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -352,7 +348,6 @@ async function example() { getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; - Obtains the system album. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -424,7 +419,6 @@ async function example() { getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; - Obtains audio assets. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -469,7 +463,6 @@ async function example() { getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; - Obtains audio assets. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -515,6 +508,7 @@ async function example() { } } ``` + ### delete delete(uri: string, callback: AsyncCallback<void>): void; @@ -564,6 +558,7 @@ async function example() { }); } ``` + ### delete delete(uri: string): Promise<void>; @@ -1093,7 +1088,6 @@ Opens this file asset. This API uses an asynchronous callback to return the resu **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO - **System capability**: SystemCapability.FileManagement.UserFileManager.Core **Parameters** @@ -1923,6 +1917,7 @@ async function example() { }); } ``` + ### getPhotoAssets getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; @@ -2106,6 +2101,7 @@ async function example() { } ``` + ### getPhotoAssets getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; @@ -2147,6 +2143,7 @@ async function example() { console.info('fetchResult.count = ', count); } ``` + ### delete delete(uri: string, callback: AsyncCallback<void>): void; @@ -2190,6 +2187,7 @@ async function example() { }); } ``` + ### delete delete(uri: string): Promise<void>; @@ -2280,6 +2278,7 @@ async function example() { }); } ``` + ### recover recover(uri: string): Promise<void>; @@ -2335,9 +2334,9 @@ Enumerates the member types. | Name | Type| Readable | Writable | Description | | ----- | ---- | ---- | ---- | ---- | -| number | number | Yes| Yes| The member is a number.| -| string | string | Yes| Yes| The member is a string.| -| boolean | boolean | Yes| Yes| The member is a Boolean value.| +| number | number | Yes| Yes| The member is a number.| +| string | string | Yes| Yes| The member is a string.| +| boolean | boolean | Yes| Yes| The member is a Boolean value.| ## ChangeEvent @@ -2366,7 +2365,6 @@ Defines information about a registered device. | networkId | string | Yes | No | Network ID of the registered device.| | isOnline | boolean | Yes | No | Whether the registered device is online. | - ## FileType Enumerates media file types. @@ -2390,8 +2388,6 @@ Enumerates the system album types. | TYPE_FAVORITE | 0 | Favorites.| | TYPE_TRASH | 1 | Recycle bin.| - - ## AudioKey Defines the key information about an audio file. @@ -2445,7 +2441,6 @@ Defines the key album information. | DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | | DATE_MODIFIED | date_modified | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| - ## FetchOptions Defines the options for fetching media files. diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 1a60dc51ae1404aee3947f799c166180ac13dde2..6600939a007d9ac3abd1ad964f3270445cec3a7e 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -547,7 +547,7 @@ A constructor used to create a **TextEncoder** object. | Name| Type| Mandatory| Description| | ----- | ---- | ---- | ---- | -| encoding | string | No| Encoding format.| +| encoding | string | No| Encoding format. The default format is **'utf-8'**.| **Example** @@ -567,7 +567,7 @@ Encodes the input content. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| input | string | No | String to encode.| +| input | string | No | String to encode. The default value is an empty string.| **Return value** @@ -665,7 +665,7 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| input | string | No| String to encode.| +| input | string | No| String to encode. The default value is an empty string.| **Return value** @@ -1646,18 +1646,18 @@ Create a class to implement the **compareTo** method. The **Temperature** class ```js class Temperature{ - constructor(value){ - // If TS is used for development, add the following code: - // private readonly _temp: Temperature; + // If ArkTS is used for development, add the following code: + // private readonly _temp: Temperature; + constructor(value) { this._temp = value; } - compareTo(value){ + compareTo(value) { return this._temp >= value.getTemp(); } - getTemp(){ + getTemp() { return this._temp; } - toString(){ + toString() { return this._temp.toString(); } } diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index 0563c2741b5b71a86cabfb61fee8370bf45e8871..4e869d9d32db75389926d06212fe085f3781955b 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -13,6 +13,21 @@ The **wallpaper** module is a system service module in OpenHarmony that provides ```js import wallpaper from '@ohos.wallpaper'; ``` +## WallpaperResourceType10+ + +Enumerates the types of wallpaper resources. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**System API**: This is a system API. + +| Name| Value|Description| +| -------- | -------- |-------- | +| DEFAULT | 0 |Default type (image resource).| +| PICTURE | 1 |Image resource.| +| VIDEO | 2 |Video resource.| +| PACKAGE | 3 |Package resource.| + ## WallpaperType7+ @@ -44,6 +59,158 @@ Defines the RGBA color space for the wallpaper. | alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| +## wallpaper.setVideo10+ + +setVideo(source: string, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void + +Sets a video resource as the home screen wallpaper or lock screen wallpaper. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | string | Yes| URI of an MP4 file.| +| wallpaperType | [WallpaperType](#wallpapertype7) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/test.mp4"; +try { + wallpaper.setVideo(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setVideo because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setVideo.`); + }); +} catch (error) { + console.error(`failed to setVideo because: ${JSON.stringify(error)}`); +} + +``` + +## wallpaper.setVideo10+ + +setVideo(source: string, wallpaperType: WallpaperType): Promise<void> + +Sets a video resource as the home screen wallpaper or lock screen wallpaper. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | string | Yes| URI of an MP4 file.| +| wallpaperType | [WallpaperType](#wallpapertype7) | Yes| Wallpaper type.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/test.mp4"; +try { + wallpaper.setVideo(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setVideo.`); + }).catch((error) => { + console.error(`failed to setVideo because: ${JSON.stringify(error)}`); + }); +} catch (error) { + console.error(`failed to setVideo because: ${JSON.stringify(error)}`); +} +``` + +## wallpaper.on('wallpaperChange')10+ + +on(type: 'wallpaperChange', callback: (wallpaperType: WallpaperType, resourceType: WallpaperResourceType) => void): void + +Subscribes to wallpaper change events. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is fixed at **'wallpaperChange'**.| +| callback | function | Yes| Callback used to return the wallpaper type and wallpaper resource type.
- wallpaperType
Wallpaper type.
- resourceType
Wallpaper resource type.| + +**Example** + +```js +try { + let listener = (wallpaperType, resourceType) => { + console.log(`wallpaper color changed.`); + }; + wallpaper.on('wallpaperChange', listener); +} catch (error) { + console.error(`failed to on because: ${JSON.stringify(error)}`); +} +``` + +## wallpaper.off('wallpaperChange')10+ + +off(type: 'wallpaperChange', callback?: (wallpaperType: WallpaperType, resourceType: WallpaperResourceType) => void): void + +Unsubscribes from wallpaper change events. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is fixed at **'wallpaperChange'**.| +| callback | function | No| Callback used for unsubscription. If this parameter is not set, this API unsubscribes from all callbacks of the specified event type.
- wallpaperType
Wallpaper type.
- resourceType
Wallpaper resource type.| + +**Example** + +```js +let listener = (wallpaperType, resourceType) => { + console.log(`wallpaper color changed.`); +}; +try { + wallpaper.on('wallpaperChange', listener); +} catch (error) { + console.error(`failed to on because: ${JSON.stringify(error)}`); +} + +try { + // Unsubscribe from the listener. + wallpaper.off('wallpaperChange', listener); +} catch (error) { + console.error(`failed to off because: ${JSON.stringify(error)}`); +} + +try { + // Unsubscribe from all callbacks of the 'wallpaperChange' event type. + wallpaper.off('wallpaperChange'); +} catch (error) { + console.error(`failed to off because: ${JSON.stringify(error)}`); +} +``` + ## wallpaper.getColorsSync9+ getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> @@ -210,7 +377,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a ```js // The source type is string. -let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/js.jpeg"; wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { if (error) { console.error(`failed to setImage because: ${JSON.stringify(error)}`); @@ -270,7 +437,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr ```js // The source type is string. -let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/js.jpeg"; wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { console.log(`success to setImage.`); }).catch((error) => { @@ -898,7 +1065,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a ```js // The source type is string. -let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/js.jpeg"; wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { if (error) { console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); @@ -960,7 +1127,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr ```js // The source type is string. -let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +let wallpaperPath = "/data/storage/el2/base/haps/entry/files/js.jpeg"; wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { console.log(`success to setWallpaper.`); }).catch((error) => { diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index dba171b9da058a60c3dde3b4c96e9476b27dba77..bca3349825d366afd8b3e1c8f15d9b373fce3ff1 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -67,7 +67,7 @@ ws.connect(defaultIpAddress, (err, value) => { }); ``` -## webSocket.createWebSocket +## webSocket.createWebSocket6+ createWebSocket(): WebSocket @@ -87,11 +87,11 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc let ws = webSocket.createWebSocket(); ``` -## WebSocket +## WebSocket6+ Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object. -### connect +### connect6+ connect(url: string, callback: AsyncCallback\): void @@ -132,7 +132,7 @@ ws.connect(url, (err, value) => { }); ``` -### connect +### connect6+ connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void @@ -179,7 +179,7 @@ ws.connect(url, { }); ``` -### connect +### connect6+ connect(url: string, options?: WebSocketRequestOptions): Promise\ @@ -225,7 +225,7 @@ promise.then((value) => { }); ``` -### send +### send6+ send(data: string | ArrayBuffer, callback: AsyncCallback\): void @@ -265,7 +265,7 @@ ws.connect(url, (err, value) => { }); ``` -### send +### send6+ send(data: string | ArrayBuffer): Promise\ @@ -309,7 +309,7 @@ ws.connect(url, (err, value) => { }); ``` -### close +### close6+ close(callback: AsyncCallback\): void @@ -345,7 +345,7 @@ ws.close((err, value) => { }); ``` -### close +### close6+ close(options: WebSocketCloseOptions, callback: AsyncCallback\): void @@ -385,7 +385,7 @@ ws.close({ }); ``` -### close +### close6+ close(options?: WebSocketCloseOptions): Promise\ @@ -429,7 +429,7 @@ promise.then((value) => { }); ``` -### on('open') +### on('open')6+ on(type: 'open', callback: AsyncCallback\): void @@ -453,7 +453,7 @@ ws.on('open', (err, value) => { }); ``` -### off('open') +### off('open')6+ off(type: 'open', callback?: AsyncCallback\): void @@ -483,7 +483,7 @@ ws.on('open', callback1); ws.off('open', callback1); ``` -### on('message') +### on('message')6+ on(type: 'message', callback: AsyncCallback\): void @@ -510,7 +510,7 @@ ws.on('message', (err, value) => { }); ``` -### off('message') +### off('message')6+ off(type: 'message', callback?: AsyncCallback\): void @@ -536,7 +536,7 @@ let ws = webSocket.createWebSocket(); ws.off('message'); ``` -### on('close') +### on('close')6+ on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void @@ -560,7 +560,7 @@ ws.on('close', (err, value) => { }); ``` -### off('close') +### off('close')6+ off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void @@ -585,7 +585,7 @@ let ws = webSocket.createWebSocket(); ws.off('close'); ``` -### on('error') +### on('error')6+ on(type: 'error', callback: ErrorCallback): void @@ -609,7 +609,7 @@ ws.on('error', (err) => { }); ``` -### off('error') +### off('error')6+ off(type: 'error', callback?: ErrorCallback): void diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index d00c77b95c8870f0c97404a0e08d2ba3d449160b..726f05fc58a6ef1f82cb1955d24388fc17f48ebd 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -232,7 +232,7 @@ Describes the window properties. | isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is **false**. The value **true** means that the window is immersive, and **false** means the opposite.| | focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is **true**. The value **true** means that the window can gain focus, and **false** means the opposite.| | touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is **true**. The value **true** means that the window is touchable, and **false** means the opposite.| -| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value **1** indicates the maximum brightness. | +| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value **1** indicates the maximum brightness. If no value is passed, the brightness follows the system. In this case, the obtained brightness value is –1.| | dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value **1** indicates the maximum dimness.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| | isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is **false**. The value **true** means that the screen is always on, and **false** means the opposite.| | isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is **false**. The value **true** means that the window is in privacy mode, and **false** means the opposite.| @@ -332,6 +332,8 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc | ------- | -------------------------------- | | 1300001 | Repeated operation. | | 1300006 | This window context is abnormal. | +| 1300008 | The operation is on invalid display. | +| 1300009 | The parent window is invalid. | **Example** @@ -381,6 +383,8 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc | ------- | -------------------------------- | | 1300001 | Repeated operation. | | 1300006 | This window context is abnormal. | +| 1300008 | The operation is on invalid display. | +| 1300009 | The parent window is invalid. | **Example** @@ -420,6 +424,14 @@ Finds a window based on the name. | ----------------- | ------------------- | | [Window](#window) | Window found.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 1300002 | This window state is abnormal. | + **Example** ```js @@ -2701,7 +2713,7 @@ try { ### off('avoidAreaChange')9+ -off(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void +off(type: 'avoidAreaChange', callback?: Callback<{AvoidAreaType, AvoidArea}>): void Disables listening for changes to the area where the window cannot be displayed. @@ -3471,7 +3483,7 @@ let colorSpace = windowClass.getWindowColorSpace(); setWindowBackgroundColor(color: string): void -Sets the background color for this window. In the stage model, this API must be used after [loadContent](#loadcontent9). +Sets the background color for this window. In the stage model, this API must be used after the call of [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9) takes effect. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3506,6 +3518,8 @@ setWindowBrightness(brightness: number, callback: AsyncCallback<void>): vo Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -3547,6 +3561,8 @@ setWindowBrightness(brightness: number): Promise<void> Sets the screen brightness for this window. This API uses a promise to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -4100,15 +4116,15 @@ Captures this window. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------------ | --------- | ----------------------------------- | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | @@ -4135,15 +4151,15 @@ Captures this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ----------------------------------------------------------- | --------------------------------------------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | @@ -4171,18 +4187,18 @@ Sets the opacity for this window. This API can be used only when you [customize **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | --------- | ------------------------------------------------------------ | -| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0. The value **0.0** means completely transparent, and **1.0** means completely opaque. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------------------------- | +| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0. The value **0.0** means completely transparent, and **1.0** means completely opaque.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4206,18 +4222,18 @@ Sets the scale parameters for this window. This API can be used only when you [c **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | ------------------------------ | --------- | ------------------------ | -| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set. | +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------ | ---- | ---------- | +| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4247,18 +4263,18 @@ Sets the rotation parameters for this window. This API can be used only when you **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | -------------------------------- | --------- | --------------------------- | -| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set. | +| Name | Type | Mandatory| Description | +| ------------- | -------------------------------- | ---- | ---------- | +| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4289,18 +4305,18 @@ Sets the translation parameters for this window. This API can be used only when **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | -------------------------------------- | --------- | ------------------------------------------- | -| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters. The unit is pixels. | +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------- | ---- | -------------------- | +| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters. The unit is pixels.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4329,18 +4345,18 @@ Obtains the transition animation controller. **Return value** -| Type | Description | -| ---------------------------------------------- | -------------------------------- | -| [TransitionController](#transitioncontroller9) | Transition animation controller. | +| Type | Description | +| ---------------------------------------------- | ---------------- | +| [TransitionController](#transitioncontroller9) | Transition animation controller.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4391,18 +4407,18 @@ Blurs this window. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the window. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the window.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4426,18 +4442,18 @@ Blurs the background of this window. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the background of the window. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the background of the window.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4461,18 +4477,18 @@ Sets the blur style for the background of this window. **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------ | --------- | --------------------------------------------------- | -| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window. | +| Name | Type | Mandatory| Description | +| --------- | --------- | ---- | ---------------------- | +| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4496,21 +4512,21 @@ Sets the shadow for the window borders. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | --------- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value **0** means that the shadow is disabled for the window borders. | -| color | string | No | Color of the shadow. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | -| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | -| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value **0** means that the shadow is disabled for the window borders.| +| color | string | No | Color of the shadow. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| +| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | +| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4534,18 +4550,18 @@ Sets the radius of the rounded corners for this window. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value **0** means that the window does not use rounded corners. | +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | -------------------- | +| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value **0** means that the window does not use rounded corners.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| 1300004 | Unauthorized operation. | **Example** @@ -4569,20 +4585,20 @@ Raises the application subwindow to the top layer of the application. This API u **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | --------------------------------------------- | -| 1300002 | This window state is abnormal. | +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | | 1300003 | This window manager service works abnormally. | -| 1300004 | Unauthorized operation. | -| 1300009 | The parent window is invalid. | +| 1300004 | Unauthorized operation. | +| 1300009 | The parent window is invalid. | **Example** @@ -4608,20 +4624,20 @@ Raises the application subwindow to the top layer of the application. This API u **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | --------------------------------------------- | -| 1300002 | This window state is abnormal. | +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | | 1300003 | This window manager service works abnormally. | -| 1300004 | Unauthorized operation. | -| 1300009 | The parent window is invalid. | +| 1300004 | Unauthorized operation. | +| 1300009 | The parent window is invalid. | **Example** @@ -4645,24 +4661,24 @@ This API is available only for the main window of the application. The aspect ra **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------------------------------------------------------ | -| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value must be greater than 0. | +| Name | Type | Mandatory| Description | +| ------------------ | ------- | ---- | ------------------------------------------------------------ | +| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value must be greater than 0.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | ------------------------------ | -| 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | **Example** @@ -4692,19 +4708,19 @@ This API is available only for the main window of the application. The aspect ra **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value must be greater than 0. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------------ | ------- | ---- | ------------------------------------------------------------ | +| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value must be greater than 0.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | ------------------------------ | -| 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | **Example** @@ -4735,18 +4751,18 @@ This API is available only for the main window of the application. After this AP **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | ------------------------------ | -| 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | **Example** @@ -4775,18 +4791,18 @@ This API is available only for the main window of the application. After this AP **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------------ | ------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | ------------------------------ | -| 1300002 | This window state is abnormal. | -| 1300004 | Unauthorized operation. | +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | **Example** @@ -4816,25 +4832,25 @@ Adds or deletes the watermark flag for this window. This API uses a promise to r **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------- | --------- | ------------------------------------------------------------ | -| enable | boolean | Yes | Whether to add or delete the watermark flag to the window. The value **true** means to add the watermark flag and **false** means to delete the watermark flag. | +| Name| Type | Mandatory| Description | +| ------ | ------- | --- | ------------------------------------------------ | +| enable | boolean | Yes | Whether to add or delete the watermark flag to the window. The value **true** means to add the watermark flag and **false** means to delete the watermark flag.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | --------------------------------------------- | -| 1300002 | This window state is abnormal. | -| 1300003 | This window manager service works abnormally. | -| 1300008 | The operation is on invalid display. | +| ID| Error Message| +| ------- | ---------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300008 | The operation is on invalid display. | **Example** @@ -4864,20 +4880,20 @@ Adds or deletes the watermark flag for this window. This API uses an asynchronou **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| enable | boolean | Yes | Whether to add or delete the watermark flag to the window. The value **true** means to add the watermark flag and **false** means to delete the watermark flag. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | --- | ----------------------------------------------- | +| enable | boolean | Yes | Whether to add or delete the watermark flag to the window. The value **true** means to add the watermark flag and **false** means to delete the watermark flag.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | -| ------- | --------------------------------------------- | -| 1300002 | This window state is abnormal. | -| 1300003 | This window manager service works abnormally. | -| 1300008 | The operation is on invalid display. | +| ID| Error Message| +| ------- | ---------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300008 | The operation is on invalid display. | **Example** @@ -4910,9 +4926,9 @@ Shows this window. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -4940,9 +4956,9 @@ Shows this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -4969,9 +4985,9 @@ Destroys this window. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -4999,9 +5015,9 @@ Destroys this window. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5030,11 +5046,11 @@ This operation is not supported in a window in full-screen mode. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right. | -| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------- | +| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| +| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5064,16 +5080,16 @@ This operation is not supported in a window in full-screen mode. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------------------------------------------ | -| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right. | -| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------- | +| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| +| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5108,11 +5124,11 @@ This operation is not supported in a window in full-screen mode. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ----------------------------------- | -| width | number | Yes | New width of the window, in px. | -| height | number | Yes | New height of the window, in px. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------- | +| width | number | Yes | New width of the window, in px.| +| height | number | Yes | New height of the window, in px.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5148,16 +5164,16 @@ This operation is not supported in a window in full-screen mode. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | -------------------------------- | -| width | number | Yes | New width of the window, in px. | -| height | number | Yes | New height of the window, in px. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| width | number | Yes | New width of the window, in px.| +| height | number | Yes | New height of the window, in px.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5186,10 +5202,10 @@ Sets the type of this window. This API uses an asynchronous callback to return t **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------- | --------- | ----------------------------------- | -| type | [WindowType](#windowtype7) | Yes | Window type. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| type | [WindowType](#windowtype7) | Yes | Window type.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -5220,15 +5236,15 @@ Sets the type of this window. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------- | --------- | ------------ | -| type | [WindowType](#windowtype7) | Yes | Window type. | +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ---------- | +| type | [WindowType](#windowtype7) | Yes | Window type.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5256,9 +5272,9 @@ Obtains the properties of this window. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------------------- | --------- | ---------------------------------------------- | -| callback | AsyncCallback<[WindowProperties](#windowproperties)> | Yes | Callback used to return the window properties. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<[WindowProperties](#windowproperties)> | Yes | Callback used to return the window properties.| **Example** @@ -5286,9 +5302,9 @@ Obtains the properties of this window. This API uses a promise to return the res **Return value** -| Type | Description | -| ---------------------------------------------------- | --------------------------------------------- | -| Promise<[WindowProperties](#windowproperties)> | Promise used to return the window properties. | +| Type | Description | +| ---------------------------------------------------- | ------------------------------- | +| Promise<[WindowProperties](#windowproperties)> | Promise used to return the window properties.| **Example** @@ -5315,10 +5331,10 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------------- | --------- | --------------------------------- | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | -| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | +| Name | Type | Mandatory| Description | +| -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area.| +| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** @@ -5347,15 +5363,15 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------------- | --------- | ----------------- | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | +| Name| Type | Mandatory| Description | +| ------ |----------------------------------| ---- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area.| **Return value** -| Type | Description | -| --------------------------------------- | -------------------------------- | -| Promise<[AvoidArea](#avoidarea7)> | Promise used to return the area. | +| Type | Description | +|-----------------------------------------| ----------------------------------- | +| Promise<[AvoidArea](#avoidarea7)> | Promise used to return the area.| **Example** @@ -5383,10 +5399,10 @@ Sets whether to enable the full-screen mode for this window. This API uses an as **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | ------------------------- | --------- | ------------------------------------------------------------ | -| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------ | ------------------------- | ---- | ---------------------------------------------- | +| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5415,15 +5431,15 @@ Sets whether to enable the full-screen mode for this window. This API uses a pro **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | ------- | --------- | ------------------------------------------------------------ | -| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ------------ | ------- | ---- | ---------------------------------------------- | +| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5453,10 +5469,10 @@ A non-immersive layout means that the layout avoids the status bar and navigatio **Parameters** -| Name | Type | Mandatory | Description | -| ------------------ | ------------------------- | --------- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | Yes | Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window is immersive, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------------ | ------------------------- | ---- | ------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes | Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window layout is immersive, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5487,15 +5503,15 @@ A non-immersive layout means that the layout avoids the status bar and navigatio **Parameters** -| Name | Type | Mandatory | Description | -| ------------------ | ------- | --------- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | Yes | Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window is immersive, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ------------------ | ------- | ---- | ------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes | Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window layout is immersive, and **false** means the opposite.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5523,10 +5539,10 @@ Sets whether to display the status bar and navigation bar in this window. This A **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------- | --------- | ------------------------------------------------------------ | -| names | Array<'status'\|'navigation'> | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| names | Array<'status'\|'navigation'> | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5556,15 +5572,15 @@ Sets whether to display the status bar and navigation bar in this window. This A **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ----------------------------- | --------- | ------------------------------------------------------------ | -| names | Array<'status'\|'navigation'> | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed. | +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------------ | +| names | Array<'status'\|'navigation'> | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5593,10 +5609,10 @@ Sets the properties of the status bar and navigation bar in this window. This AP **Parameters** -| Name | Type | Mandatory | Description | -| ------------------- | ------------------------------------------- | --------- | ------------------------------------------------ | -| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------- | ---- | ---------------------- | +| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5631,15 +5647,15 @@ Sets the properties of the status bar and navigation bar in this window. This AP **Parameters** -| Name | Type | Mandatory | Description | -| ------------------- | ------------------------------------------- | --------- | ------------------------------------------------ | -| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar. | +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------- | ---- | ---------------------- | +| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5673,10 +5689,10 @@ Loads content from a page to this window. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------- | -| path | string | Yes | Path of the page from which the content will be loaded. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------- | +| path | string | Yes | Path of the page from which the content will be loaded.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5704,15 +5720,15 @@ Loads content from a page to this window. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------------------------------------- | -| path | string | Yes | Path of the page from which the content will be loaded. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| path | string | Yes | Path of the page from which the content will be loaded.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5739,9 +5755,9 @@ Checks whether this window is displayed. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the window is displayed, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the window is displayed, and **false** means the opposite.| **Example** @@ -5769,9 +5785,9 @@ Checks whether this window is displayed. This API uses a promise to return the r **Return value** -| Type | Description | +| Type | Description | | ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value **true** means that the window is displayed, and **false** means the opposite. | +| Promise<boolean> | Promise used to return the result. The value **true** means that the window is displayed, and **false** means the opposite.| **Example** @@ -5798,10 +5814,10 @@ Enables listening for changes to the area where the window cannot be displayed. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed. | -| callback | Callback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| +| callback | Callback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** @@ -5825,10 +5841,10 @@ Disables listening for changes to the area where the window cannot be displayed. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed. | -| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| +| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | **Example** @@ -5850,9 +5866,9 @@ Checks whether this window supports the wide-gamut color space. This API uses an **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite.| **Example** @@ -5880,9 +5896,9 @@ Checks whether this window supports the wide-gamut color space. This API uses a **Return value** -| Type | Description | +| Type | Description | | ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite. | +| Promise<boolean> | Promise used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite.| **Example** @@ -5909,10 +5925,10 @@ Sets a color space for this window. This API uses an asynchronous callback to re **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | -------------------------- | --------- | ----------------------------------- | -| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------ | +| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5940,15 +5956,15 @@ Sets a color space for this window. This API uses a promise to return the result **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | -------------------------- | --------- | ------------------- | -| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | -------------- | +| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -5975,9 +5991,9 @@ Obtains the color space of this window. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | -| callback | AsyncCallback<[ColorSpace](#colorspace8)> | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ---------------------------------------------------------- | +| callback | AsyncCallback<[ColorSpace](#colorspace8)> | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space.| **Example** @@ -6005,9 +6021,9 @@ Obtains the color space of this window. This API uses a promise to return the re **Return value** -| Type | Description | -| ----------------------------------------- | ----------------------------------------------- | -| Promise<[ColorSpace](#colorspace8)> | Promise used to return the current color space. | +| Type | Description | +| ---------------------------------------- | ------------------------------- | +| Promise<[ColorSpace](#colorspace8)> | Promise used to return the current color space.| **Example** @@ -6024,7 +6040,7 @@ promise.then((data)=> { setBackgroundColor(color: string, callback: AsyncCallback<void>): void -Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). +Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after the call of [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9) takes effect. > **NOTE** > @@ -6034,10 +6050,10 @@ Sets the background color for this window. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| color | string | Yes | Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6056,7 +6072,7 @@ windowClass.setBackgroundColor(color, (err) => { setBackgroundColor(color: string): Promise<void> -Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). +Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after the call of [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9) takes effect. > **NOTE** > @@ -6066,15 +6082,15 @@ Sets the background color for this window. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| color | string | Yes | Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6094,6 +6110,8 @@ setBrightness(brightness: number, callback: AsyncCallback<void>): void Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + > **NOTE** > > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9) instead. @@ -6102,10 +6120,10 @@ Sets the screen brightness for this window. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | --------- | ------------------------------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------------------------------ | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6126,6 +6144,8 @@ setBrightness(brightness: number): Promise<void> Sets the screen brightness for this window. This API uses a promise to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + > **NOTE** > > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9-1) instead. @@ -6134,15 +6154,15 @@ Sets the screen brightness for this window. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------ | --------- | ------------------------------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest. | +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------------------------------ | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6170,10 +6190,10 @@ Sets the dimness of the window that is not on top. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | --------- | ------------------------------------------------------------ | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------- | ---- | -------------------------------------------------- | +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6201,15 +6221,15 @@ Sets the dimness of the window that is not on top. This API uses a promise to re **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | --------- | ------------------------------------------------------------ | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest. | +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | -------------------------------------------------- | +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6236,10 +6256,10 @@ Sets whether this window can gain focus. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------------- | --------- | ------------------------------------------------------------ | -| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | ---------------------------- | +| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6268,15 +6288,15 @@ Sets whether this window can gain focus. This API uses a promise to return the r **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------- | --------- | ------------------------------------------------------------ | -| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | ---------------------------- | +| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6304,10 +6324,10 @@ Sets whether to keep the screen always on. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | --------- | ------------------------------------------------------------ | -| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------- | ---- | ------------------------ | +| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6336,15 +6356,15 @@ Sets whether to keep the screen always on. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------- | --------- | ------------------------------------------------------------ | -| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| -------------- | ------- | ---- | ------------------------ | +| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6372,10 +6392,10 @@ Sets whether the area outside the subwindow is touchable. This API uses an async **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | --------- | ------------------------------------------------------------ | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ---------------- | +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6403,15 +6423,15 @@ Sets whether the area outside the subwindow is touchable. This API uses a promis **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------- | --------- | ------------------------------------------------------------ | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ---------------- | +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6438,10 +6458,10 @@ Sets whether this window is in privacy mode. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------------------- | --------- | ------------------------------------------------------------ | -| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------- | ------------------------- | ---- | -------------------- | +| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6470,15 +6490,15 @@ Sets whether this window is in privacy mode. This API uses a promise to return t **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------- | --------- | ------------------------------------------------------------ | -| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ------------- | ------- | ---- | -------------------- | +| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6506,10 +6526,10 @@ Sets whether this window is touchable. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------------- | --------- | ------------------------------------------------------------ | -| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -6538,15 +6558,15 @@ Sets whether this window is touchable. This API uses a promise to return the res **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------- | --------- | ------------------------------------------------------------ | -| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | -------------------- | +| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -6568,12 +6588,12 @@ Describes the lifecycle of a window stage. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Value | Description | -| -------- | ----- | ---------------------------------------------- | -| SHOWN | 1 | The window stage is running in the foreground. | -| ACTIVE | 2 | The window stage gains focus. | -| INACTIVE | 3 | The window stage loses focus. | -| HIDDEN | 4 | The window stage is running in the background. | +| Name | Value| Description | +| ---------- | ------ | ---------- | +| SHOWN | 1 | The window stage is running in the foreground.| +| ACTIVE | 2 | The window stage gains focus.| +| INACTIVE | 3 | The window stage loses focus.| +| HIDDEN | 4 | The window stage is running in the background.| ## WindowStage9+ @@ -6593,15 +6613,15 @@ Obtains the main window of this window stage. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | --------------------------------------------- | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -6641,15 +6661,15 @@ Obtains the main window of this window stage. This API uses a promise to return **Return value** -| Type | Description | -| -------------------------------- | --------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the main window. | +| Type | Description | +| -------------------------------- | ------------------------------------------------ | +| Promise<[Window](#window)> | Promise used to return the main window.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -6688,15 +6708,15 @@ Obtains the main window of this window stage. **Return value** -| Type | Description | -| ----------------- | ----------------------- | -| [Window](#window) | return the main window. | +| Type| Description| +| ----------------- | --------------------------------- | +| [Window](#window) | return the main window.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -6732,16 +6752,16 @@ Creates a subwindow for this window stage. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | --------- | -------------------------------------- | -| name | string | Yes | Name of the subwindow. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | --------------------------------------------- | +| name | string | Yes | Name of the subwindow. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -6785,21 +6805,21 @@ Creates a subwindow for this window stage. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ---------------------- | -| name | string | Yes | Name of the subwindow. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| name | string | Yes | Name of the subwindow.| **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the subwindow. | +| Type | Description | +| -------------------------------- | ------------------------------------------------ | +| Promise<[Window](#window)> | Promise used to return the subwindow.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -6842,15 +6862,15 @@ Obtains all the subwindows of this window stage. This API uses an asynchronous c **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------------------- | --------- | ------------------------------------------- | -| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------- | +| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300005 | This window stage is abnormal. | @@ -6888,15 +6908,15 @@ Obtains all the subwindows of this window stage. This API uses a promise to retu **Return value** -| Type | Description | -| --------------------------------------------- | ------------------------------------------ | -| Promise<Array<[Window](#window)>> | Promise used to return all the subwindows. | +| Type | Description | +| --------------------------------------------- | ---------------------------------------------------- | +| Promise<Array<[Window](#window)>> | Promise used to return all the subwindows.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300005 | This window stage is abnormal. | @@ -6933,17 +6953,17 @@ Loads content from a page associated with a local storage to the main window in **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | -| path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -6988,22 +7008,22 @@ Loads content from a page associated with a local storage to the main window in **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | -| path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | -| Promise<void> | Promise that returns no value. | +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -7047,16 +7067,16 @@ Loads content from a page to this window stage. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------- | -| path | string | Yes | Path of the page from which the content will be loaded. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------- | +| path | string | Yes | Path of the page from which the content will be loaded.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -7098,16 +7118,16 @@ Enables listening for window stage lifecycle changes. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event. | -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event.| +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -7147,16 +7167,16 @@ Disables listening for window stage lifecycle changes. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event. | -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event.| +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -7197,7 +7217,7 @@ Disables window decorators. For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -7231,15 +7251,15 @@ Sets whether to display the window of the application on the lock screen. **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ------- | --------- | ------------------------------------------------------------ | -| showOnLockScreen | boolean | Yes | Whether to display the window on the lock screen. The value **true** means to display the window on the lock screen, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ---------------- | ------- | ---- | ---------------------------- | +| showOnLockScreen | boolean | Yes | Whether to display the window on the lock screen. The value **true** means to display the window on the lock screen, and **false** means the opposite.| **Error codes** For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| ID | Error Message | +| ID| Error Message| | ------- | ------------------------------ | | 1300002 | This window state is abnormal. | | 1300005 | This window stage is abnormal. | @@ -7272,9 +7292,9 @@ Provides the context for the transition animation. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable | Writable | Description | -| --------------------- | ----------------- | -------- | -------- | --------------------------------------- | -| toWindow9+ | [Window](#window) | Yes | Yes | Target window to display the animation. | +| Name | Type | Readable| Writable| Description | +| --------------------- | ----------------- | ---- | ---- | ---------------- | +| toWindow9+ | [Window](#window) | Yes | Yes | Target window to display the animation.| ### completeTransition9+ @@ -7288,9 +7308,9 @@ Completes the transition. This API can be called only after [animateTo()](../ark **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------- | --------- | ------------------------------------------------------------ | -| isCompleted | boolean | Yes | Whether the transition is complete. The value **true** means that the transition is complete, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | ------------------------------------------------------------ | +| isCompleted | boolean | Yes | Whether the transition is complete. The value **true** means that the transition is complete, and **false** means the opposite.| **Example** @@ -7340,9 +7360,9 @@ Customizes the animation for the scenario when the window is shown. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | --------- | ------------------------------------ | -| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation. | +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| **Example** @@ -7386,9 +7406,9 @@ Customizes the animation for the scenario when the window is hidden. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | --------- | ------------------------------------ | -| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation. | +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| **Example** @@ -7419,5 +7439,3 @@ controller.animationForHidden = (context : window.TransitionContext) => { console.info('complete transition end'); }; ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 88371d4cf32bcbb1686b66f0eaf18e2a4819f3e4..490e283c3689bbcf602bbe0c826ffc579523b426 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -33,11 +33,11 @@ Provides options that can be set for the **Worker** instance to create. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Readable| Writable| Description | +| Name| Type| Readable| Writable| Description| | ---- | -------- | ---- | ---- | -------------- | -| type | "classic" \| "module" | Yes | Yes | Mode in which the **Worker** instance executes the script. The default value is **classic**. The module **type** is not supported yet.| -| name | string | Yes | Yes | Name of the worker thread.| -| shared | boolean | Yes | Yes | Sharing of the **Worker** instance is not supported yet.| +| type | "classic" \| "module" | Yes | Yes| Mode in which the **Worker** instance executes the script. The **module** type is not supported yet. The default value is **classic**.| +| name | string | Yes | Yes| Name of the worker thread. The default value is **undefined**.| +| shared | boolean | Yes | Yes| Whether sharing of the **Worker** instance is enabled. Currently, sharing is not supported.| ## ThreadWorker9+ @@ -188,8 +188,6 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```js const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -workerInstance.postMessage("hello world"); - var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -207,7 +205,7 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Error codes** @@ -859,7 +857,7 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------- | -| message | Object | Yes | Message to be sent to the worker thread. | +| message | Object | Yes | Message to be sent to the host thread. | | transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| **Error codes** @@ -907,8 +905,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| message | Object | Yes | Message to be sent to the host thread. | +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Error codes** @@ -1279,8 +1277,6 @@ Sends a message to the worker thread. The data type of the message must be seque ```js const workerInstance = new worker.Worker("workers/worker.js"); -workerInstance.postMessage("hello world"); - var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -1301,7 +1297,7 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Example** @@ -1309,6 +1305,9 @@ Sends a message to the worker thread. The data type of the message must be seque const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); ``` @@ -1490,7 +1489,7 @@ Defines the event handler to be called when the host thread receives a message s | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------------------- | -| event | [MessageEvent](#messageevent)| Yes | Message received.| +| event | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** @@ -1519,7 +1518,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | -| event | [MessageEvent](#messageevent)| Yes | Error data.| +| event | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -1693,19 +1692,41 @@ Implements communication between the worker thread and the host thread. The **po > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. +### postMessage(deprecated) + +postMessage(messageObject: Object, transfer: Transferable[]): void; + +Sends a message to the host thread from the worker thread. + +> **NOTE**
+> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-2). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| messageObject | Object | Yes | Message to be sent to the host thread. | +| transfer| Transferable[] | Yes | Currently, this parameter is not supported. | + ### postMessage9+ postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; Sends a message to the host thread from the worker thread. +> **NOTE** +> +> The **DedicatedWorkerGlobalScope** class is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-2). + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ----------------------------------------------------- | -| message | Object | Yes | Message to be sent to the worker thread. | +| message | Object | Yes | Message to be sent to the host thread. | | transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| **Example** @@ -1738,7 +1759,7 @@ postMessage(messageObject: Object, options?: PostMessageOptions): void Sends a message to the host thread from the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-3). **System capability**: SystemCapability.Utils.Lang @@ -1746,8 +1767,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| message | Object | Yes | Message to be sent to the host thread. | +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Example** @@ -1778,7 +1799,7 @@ close(): void Terminates the worker thread to stop it from receiving messages. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.close9+](#close9). **System capability**: SystemCapability.Utils.Lang @@ -1806,7 +1827,7 @@ onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.onmessage9+](#onmessage9-1). **System capability**: SystemCapability.Utils.Lang @@ -1815,7 +1836,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | -| ev | [MessageEvent](#messageevent) | Yes | Message received.| +| ev | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** @@ -1842,7 +1863,7 @@ onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.onmessageerror9+](#onmessageerror9-1). **System capability**: SystemCapability.Utils.Lang @@ -1851,7 +1872,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| -| ev | [MessageEvent](#messageevent)| Yes | Error data.| +| ev | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -1878,7 +1899,7 @@ Specifies the object whose ownership needs to be transferred during data transfe | Name | Type | Readable| Writable| Description | | -------- | -------- | ---- | ---- | --------------------------------- | -| transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership.| +| transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership. The array cannot contain **null**.| ## Event @@ -1976,7 +1997,7 @@ onerror?: (ev: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+.onerror9+](#onerror9-1). **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 5259aede120c7b89b0ade477f8fb1bb27490cc1a..f8e8f0fff5917b56be67e1f3ab0b21ac949e7ee3 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -27,13 +27,13 @@ A constructor used to create an **XmlSerializer** instance. | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------ | | buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** for storing the XML information to write.| -| encoding | string | No | Encoding format. | +| encoding | string | No | Encoding format. The default value is **'utf-8'** (the only format currently supported). | **Example** ```js let arrayBuffer = new ArrayBuffer(2048); -let thatSer = new xml.XmlSerializer(arrayBuffer,"utf-8"); +let thatSer = new xml.XmlSerializer(arrayBuffer, "utf-8"); thatSer.setDeclaration(); let result = ''; let view = new Uint8Array(arrayBuffer); @@ -363,11 +363,11 @@ console.log(view1) //'' ## XmlPullParser -### XmlPullParser +### constructor constructor(buffer: ArrayBuffer | DataView, encoding?: string) -Creates and returns an **XmlPullParser** object. The **XmlPullParser** object passes two parameters. The first parameter is the memory of the **ArrayBuffer** or **DataView** type, and the second parameter is the file format (UTF-8 by default). +Creates and returns an **XmlPullParser** object. **System capability**: SystemCapability.Utils.Lang @@ -375,8 +375,8 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------ | -| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** that contains XML text information.| -| encoding | string | No | Encoding format. Only UTF-8 is supported. | +| buffer | ArrayBuffer \| DataView | Yes | XML text information to be parsed.| +| encoding | string | No | Encoding format. The default value is **'utf-8'** (the only format currently supported). | **Example** @@ -401,13 +401,9 @@ let strXml = ' ' + ' ' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let i = 0; i < strLen; ++i) { - bufView[i] = strXml.charCodeAt(i); -} -let that = new xml.XmlPullParser(arrayBuffer, 'UTF-8'); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer, 'UTF-8'); let str1 = ''; function func1(name, value){ str1 += name+':'+value; @@ -443,13 +439,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -481,9 +473,9 @@ Defines the XML parsing options. | ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------------- | | supportDoctype | boolean | No | Whether to ignore **Doctype**. The default value is **false**.| | ignoreNameSpace | boolean | No | Whether to ignore **Namespace**. The default value is **false**. | -| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue**. | -| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. | -| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. | +| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue**. The default value is **null**. | +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. The default value is **null**. | +| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. The default value is **null**. | ## ParseInfo @@ -514,13 +506,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -561,13 +549,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -611,13 +595,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -658,13 +638,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -704,13 +680,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -750,13 +722,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -797,13 +765,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -843,13 +807,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -889,13 +849,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -934,13 +890,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; diff --git a/en/application-dev/reference/arkui-js/figures/tab.gif b/en/application-dev/reference/arkui-js/figures/tab.gif index fea6fcac566df71d32643b81579a59bbe4e1b580..525ea0d263d29509fdcefb7165bc3029d31aacf6 100644 Binary files a/en/application-dev/reference/arkui-js/figures/tab.gif and b/en/application-dev/reference/arkui-js/figures/tab.gif differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md index b2ab19b168a0415f8ddd82cee4a41faa3282848d..2ad1d1ce835fe6c0fcffa7379860711cb49d396d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md @@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type| Description| | ------------- | ------- | -------- | -| select | boolean | Whether the check box is selected.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| select | boolean | Whether the check box is selected.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the check box when it is selected.
Since API version 9, this API is supported in ArkTS widgets.| | unselectedColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Border color of the check box when it is not selected.| | mark10+ | [MarkStyle](#markstyle10) | Internal icon style of the check box.| @@ -39,9 +39,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the In addition to the [universal events](ts-universal-events-click.md), the following attributes are supported. -| Name | Description | +| Name | Description | | -------------------------------------------- | ------------------------------------------------------------ | -| onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes due to a manual operation.
- The value **true** means that the check box is selected.
- The value **false** means that the check box is not selected.
Since API version 9, this API is supported in ArkTS widgets.| +| onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes.
- The value **true** means that the check box is selected.
- The value **false** means that the check box is not selected.
Since API version 9, this API is supported in ArkTS widgets. | ## MarkStyle10+ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index d6beb514c6590f6b4f977b37052d78f180ff8f51..37da4ad0bdf5b41ae99f617a6d06789fb075c922 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| selectAll | boolean | Whether to select all.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If the **select** attribute is set for a [\](ts-basic-components-checkbox.md) component in the same group, the setting of the **\** has a higher priority.| +| selectAll | boolean | Whether to select all.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If the **select** attribute is set for a [\](ts-basic-components-checkbox.md) component in the same group, the setting of the **\** has a higher priority.
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected check box.
Since API version 9, this API is supported in ArkTS widgets.| | unselectedColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Border color of the check box when it is not selected.| | mark10+ | [MarkStyle](#markstyle10) | Internal icon style of the check box.| @@ -41,7 +41,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | -| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult)) => void ) |Triggered when the selected status of the check box group or any check box wherein changes due to a manual operation.
Since API version 9, this API is supported in ArkTS widgets.| +| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult)) => void ) |Triggered when the selected status of the check box group or any check box wherein changes.
Since API version 9, this API is supported in ArkTS widgets.| ## CheckboxGroupResult diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index d54ecbf1d4a50be563e2c712648ae0a56dc19daa..e56281bb9e1915186abcc64e4a9911a99aea18d7 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -139,7 +139,7 @@ Scrolls to the item with the specified index. > **NOTE** > -> Only the **\** and **\** components are supported. +> Only the **\**, **\**, and **\** components are supported. **Parameters** diff --git a/en/application-dev/reference/arkui-ts/ts-gesture-settings.md b/en/application-dev/reference/arkui-ts/ts-gesture-settings.md index 8268db6dca2ea26db846b343060cc001294905f0..6b37f324306957502522eddda9c14be98bee3797 100644 --- a/en/application-dev/reference/arkui-ts/ts-gesture-settings.md +++ b/en/application-dev/reference/arkui-ts/ts-gesture-settings.md @@ -11,29 +11,29 @@ Bind different types of gesture events to components and set response methods fo Use the following attributes to bind gesture recognition to a component. When a gesture is recognized, the event callback is invoked to notify the component. -| Name | Type | Default Value | Description | -| --------------- | ---------------------------------------- | --------------------------------------- | ---------------------------------------- | -| gesture | gesture: [GestureType](#gesturetype),
mask?: [GestureMask](#gesturemask) | gesture: -,
mask: GestureMask.Normal | Gesture to bind.
- **gesture**: type of the gesture to bind.
- **mask**: event response setting. | -| priorityGesture | gesture: [GestureType](#gesturetype),
mask?: [GestureMask](#gesturemask) | gesture: -,
mask: GestureMask.Normal | Gesture to preferentially recognize.
- **gesture**: type of the gesture to bind.
- **mask**: event response setting.
By default, a component recognizes gestures bound through **gesture**. When **priorityGesture** is configured for its parent component, the component preferentially recognizes gestures bound through **priorityGesture**. | -| parallelGesture | gesture: [GestureType](#gesturetype),
mask?: [GestureMask](#gesturemask) | gesture: -,
mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.
- **gesture**: type of the gesture to bind.
- **mask**: event response setting.
The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent and child components can be triggered, thereby implementing a bubbling effect. If both the single-tap gesture event and the double-tap gesture event are bound to the parent and child components, only the single-tap gesture event is responded. | +| Name| Type| Default Value| Description| +| -------- | -------- | -------- | -------- | +| gesture | gesture: [GestureType](#gesturetype),
mask?: [GestureMask](#gesturemask) | gesture: -,
mask: GestureMask.Normal | Gesture to bind.
- **gesture**: type of the gesture to bind.
- **mask**: mask for gesture events.| +| priorityGesture | gesture: [GestureType](#gesturetype),
mask?: [GestureMask](#gesturemask) | gesture: -,
mask: GestureMask.Normal | Gesture to preferentially recognize.
- **gesture**: type of the gesture to bind.
- **mask**: mask for gesture events.
1. By default, the child component preferentially recognizes the gesture specified by **gesture**, and the parent component preferentially recognizes the gesture specified by **priorityGesture** (if set).
2. With regard to long press gestures, the component with the shortest minimum hold-down time responds first, ignoring the **priorityGesture** settings.| +| parallelGesture | gesture: [GestureType](#gesturetype),
mask?: [GestureMask](#gesturemask) | gesture: -,
mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.
- **gesture**: type of the gesture to bind.
- **mask**: mask for gesture events.
The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent and child components can be triggered, thereby implementing a bubbling effect. If both the single-tap gesture event and the double-tap gesture event are bound to the parent and child components, only the single-tap gesture event is responded.| ## GestureType -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| [TapGesture](ts-basic-gestures-tapgesture.md) | Tap gesture, which can be a single-tap or multi-tap gesture. | -| [LongPressGesture](ts-basic-gestures-longpressgesture.md) | Long press gesture. | -| [PanGesture](ts-basic-gestures-pangesture.md) | Pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen. | -| [PinchGesture](ts-basic-gestures-pinchgesture.md) | Pinch gesture. | -| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Rotation gesture. | -| [SwipeGesture](ts-basic-gestures-swipegesture.md) | Swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher. | -| [GestureGroup](ts-combined-gestures.md) | A group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported. | +| Name| Description| +| -------- | -------- | +| [TapGesture](ts-basic-gestures-tapgesture.md) | Tap gesture, which can be a single-tap or multi-tap gesture.| +| [LongPressGesture](ts-basic-gestures-longpressgesture.md) | Long press gesture.| +| [PanGesture](ts-basic-gestures-pangesture.md) | Pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen.| +| [PinchGesture](ts-basic-gestures-pinchgesture.md) | Pinch gesture.| +| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Rotation gesture.| +| [SwipeGesture](ts-basic-gestures-swipegesture.md) | Swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher.| +| [GestureGroup](ts-combined-gestures.md) | A group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported.| ## GestureMask -| Name | Description | -| -------------- | ---------------------------------------- | -| Normal | The gestures of child components are not ignored and are recognized based on the default gesture recognition sequence. | +| Name| Description| +| -------- | -------- | +| Normal | The gestures of child components are not ignored and are recognized based on the default gesture recognition sequence.| | IgnoreInternal | The gestures of child components are ignored, including the built-in gestures. For example, if the child component is **\**, its built-in swipe gesture is also ignored.| ## Gesture Response Event @@ -42,52 +42,52 @@ The component binds gesture objects of different **GestureType**s through gestur **TapGesture** -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onAction((event?:GestureEvent) => void) | Callback invoked when a tap gesture is recognized. | +| Name| Description| +| -------- | -------- | +| onAction((event?:GestureEvent) => void) | Callback invoked when a tap gesture is recognized.| ## GestureEvent -| Name | Type | Description | -| ----------------------- | ---------------------------------------- | ---------------------------------------- | -| repeat | boolean | Whether the event is triggered repeatedly. This attribute is used for the **LongPressGesture** event. | -| offsetX | number | Offset of the gesture event on the x-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means to pan from left to right, and a negative value means the opposite. | -| offsetY | number | Offset of the gesture event on the y-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means to pan from top to bottom, and a negative value means the opposite. | -| angle | number | Rotation angle for the **RotationGesture** event;
angle of the swipe gesture for the **SwipeGesture** event, that is, the change in the included angle between the line segment created by the two fingers and the horizontal direction.
**NOTE**
Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) – arctan2(y2-y1,x2-x1) The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. | -| scale | number | Scale ratio. This attribute is used for the **PinchGesture** event. | -| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px relative to the upper left corner of the current component. This attribute is used for the **PinchGesture** event. | -| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px relative to the upper left corner of the current component. This attribute is used for the **PinchGesture** event. | -| speed8+ | number | Swipe gesture speed, that is, the average swipe speed of all fingers. The unit is vp/s. This attribute is used for the **SwipeGesture** event. | -| fingerList8+ | [FingerInfo](#fingerinfo)[] | Information about all fingers that trigger the event, which is used for the **LongPressGesture** and **TapGesture** events. | -| timestamp8+ | number | Timestamp of the event. | -| target8+ | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event. | -| source8+ | [SourceType](#sourcetype) | Event input device. | -| pressure9+ | number | Press pressure. | -| tiltX9+ | number | Angle between the projection of the stylus on the device plane and the x-axis. | -| tiltY9+ | number | Angle between the projection of the stylus on the device plane and the y-axis. | -| sourceTool9+ | [SourceTool](#sourcetool) | Event input source. | +| Name| Type| Description| +| -------- | -------- | -------- | +| repeat | boolean | Whether the event is triggered repeatedly. This attribute is used for the **LongPressGesture** event.| +| offsetX | number | Offset of the gesture event on the x-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means to pan from left to right, and a negative value means the opposite.| +| offsetY | number | Offset of the gesture event on the y-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means to pan from top to bottom, and a negative value means the opposite.| +| angle | number | Rotation angle for the **RotationGesture** event;
angle of the swipe gesture for the **SwipeGesture** event, that is, the change in the included angle between the line segment created by the two fingers and the horizontal direction.
**NOTE**
Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) – arctan2(y2-y1,x2-x1) The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees.| +| scale | number | Scale ratio. This attribute is used for the **PinchGesture** event.| +| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. This attribute is used for the **PinchGesture** event.| +| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. This attribute is used for the **PinchGesture** event.| +| speed8+ | number | Swipe gesture speed, that is, the average swipe speed of all fingers. The unit is vp/s. This attribute is used for the **SwipeGesture** event.| +| fingerList8+ | [FingerInfo](#fingerinfo)[] | Information about all fingers that trigger the event. This attribute is used for the **LongPressGesture** and **TapGesture** events.| +| timestamp8+ | number | Timestamp of the event.| +| target8+ | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event.| +| source8+ | [SourceType](#sourcetype) | Event input device.| +| pressure9+ | number | Press pressure.| +| tiltX9+ | number | Angle between the projection of the stylus on the device plane and the x-axis.| +| tiltY9+ | number | Angle between the projection of the stylus on the device plane and the y-axis.| +| sourceTool9+ | [SourceTool](#sourcetool) | Event input source.| ## SourceType -| Name | Description | -| ----------- | -------------------- | -| Unknown | Unknown device type. | -| Mouse | Mouse. | -| TouchScreen | Touchscreen. | +| Name| Description| +| -------- | -------- | +| Unknown | Unknown device type.| +| Mouse | Mouse.| +| TouchScreen | Touchscreen.| ## FingerInfo -| Name | Type | Description | -| ------- | ------ | ---------------------------------------- | -| id | number | Index of a finger. | -| globalX | number | X-coordinate relative to the upper left corner of the application window. | -| globalY | number | Y-coordinate relative to the upper left corner of the application window. | -| localX | number | X-coordinate relative to the upper left corner of the current component. | -| localY | number | Y-coordinate relative to the upper left corner of the current component. | +| Name| Type| Description| +| -------- | -------- | -------- | +| id | number | Index of a finger.| +| globalX | number | X-coordinate relative to the upper left corner of the application window.| +| globalY | number | Y-coordinate relative to the upper left corner of the application window.| +| localX | number | X-coordinate relative to the upper left corner of the current component.| +| localY | number | Y-coordinate relative to the upper left corner of the current component.| ## SourceTool -| Name | Description | -| ------- | --------------------- | -| Unknown | Unknown input source. | -| Finger | Finger input. | -| Pen | Stylus input. | +| Name| Description| +| -------- | -------- | +| Unknown | Unknown input source.| +| Finger | Finger input.| +| Pen | Stylus input.| ## Example diff --git a/en/application-dev/reference/errorcodes/errorcode-bundle.md b/en/application-dev/reference/errorcodes/errorcode-bundle.md index f86c810b07e06b53797010d3b95080b5a7ca258d..8f7f78de3cd348f9cd0df3c393c4303bb18666bb 100644 --- a/en/application-dev/reference/errorcodes/errorcode-bundle.md +++ b/en/application-dev/reference/errorcodes/errorcode-bundle.md @@ -586,11 +586,11 @@ The version of shared bundle is dependent on other applications. **Description** -Other applications depend on the shared library, causing the uninstallation to fail. +Other applications depend on the shared library, causing the uninstall to fail. **Possible Causes** -1. The version specified during the uninstallation is the latest version of the shared library, and the shared library is depended on by other applications. -2. No version is not specified during the uninstallation, meaning that all versions of the shared library will be uninstalled, and the shared library is depended on by other applications. +1. The version specified during the uninstall is the latest version of the shared library, and the shared library is depended on by other applications. +2. No version is not specified during the uninstall, meaning that all versions of the shared library will be uninstalled, and the shared library is depended on by other applications. **Solution** 1. Check whether the shared library to uninstall is depended on by other applications. @@ -607,7 +607,7 @@ The specified shared bundle does not exist. The shared library to uninstall does not exist. **Possible Causes** -1. The version specified during the uninstallation is different from the version of the shared library installed. +1. The version specified during the uninstall is different from the version of the shared library installed. 2. The shared library to uninstall is not installed. **Solution** @@ -649,3 +649,118 @@ During application uninstall, the bundle name of an inter-application shared lib **Solution** 1. Use the **-s** parameter to specify the application to be uninstalled as a shared library application. 2. Use the **bundleName** and **versionCode** parameters in **UninstallParam** to specify the bundle name and version of the shared library to be uninstalled. + +## 17700041 Application Installation Is Not Allowed by Enterprise Device Management + +**Error Message** + +Failed to install because enterprise device management disallow install. + +**Description** + +The installation of this application is prohibited by enterprise device management. + +**Possible Causes** + +The enterprise device management does not allow the installation of this application. + +**Solution** + +Check whether the application installation is prohibited by the enterprise device management. + +## 17700042 Incorrect URI in the Data Proxy + +**Error Message** + +Failed to install the HAP because of incorrect URI in the data proxy. + +**Description** + +During application installation, the URI of the data proxy is incorrectly configured. + +**Possible Causes** + +1. The bundle name in the URI is different from that of the current application. +2. The URI is duplicate. + +**Solution** + +1. Change the bundle name in the URI to that of the current application. +2. Change duplicate URIs. Ensure that the URI of each data proxy is unique. + +## 17700043 Incorrect Permission Configuration in the Data Proxy + +**Error Message** + +Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). + +**Description** + +During application installation, the permission level of the data proxy of a non-system application is too low. The permission level should be **system_basic** or **system_core**. + +**Possible Causes** + +1. No permission is configured for the data proxy of a non-system application. +1. The permission level of the data proxy of a non-system application is too low. + +**Solution** + +1. Configure the read and write permissions in the data proxy. +2. Change the read and write permissions in the data proxy and ensure that the permission level is **system_basic** or **system_core**. + +## 17700044 Field isolationMode in the HAP Conflicts with the Device Isolation Mode + +**Error Message** + +Failed to install the HAP because the isolationMode configured is not supported. + +**Description** + +During application installation, the value of **isolationMode** in the HAP conflicts with the isolation mode of the device. + +**Possible Causes** + +1. The device supports the isolation mode (the value of **supportIsolationMode** is **true**), whereas the value of **isolationMode** in the HAP is **nonisolationOnly**. +2. The device does not support the isolation mode (the value of **supportIsolationMode** is **false**), whereas the value of **isolationMode** in the HAP is **isolationOnly**. + +**Solution** + +Set the **isolationMode** field in the HAP based on the isolation mode of the device. + +## 17700045 Application Uninstall Is Not Allowed by Enterprise Device Management + +**Error Message** + +Failed to uninstall because enterprise device management disallow uninstall. + +**Description** + +The uninstall of this application is prohibited by enterprise device management. + +**Possible Causes** + +The enterprise device management does not allow the uninstall of this application. + +**Solution** + +Check whether the application uninstall is prohibited by the enterprise device management. + +## 17700047 Application Version To Be Updated Is Not Later Than the Current Version + +**Error Message** + +Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. + +**Description** + +The version of the application to be updated is not later than the current version. + +**Possible Causes** + +1. The version number of the application to be updated is earlier than or equal to that of the current version number. +2. When **installFlag** is set to **NORMAL**, the version number of the application to be updated must be later than the installed version number. + +**Solution** + +1. Set the version number of the application to be later than the current version number. +2. If you want to update the application without changing the version number, set **installFlag** to **REPLACE_EXISTING**. diff --git a/en/application-dev/reference/errorcodes/errorcode-devicestatus.md b/en/application-dev/reference/errorcodes/errorcode-devicestatus.md new file mode 100644 index 0000000000000000000000000000000000000000..08d37f6fc9bc63b691638a73b84ba24205898e0a --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-devicestatus.md @@ -0,0 +1,27 @@ +# Screen Hopping Error Codes + +> **NOTE** +> +> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md). + +## 20900001 Input Device Operation Failed + +**Error Message** + +Failed to operate the input device. + +**Description** + +This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. + +**Possible Cause** + +1. When screen hopping is initiated, the local device is in the hopped state. +2. When screen hopping is disabled, the local device is in the free state. +3. When screen hopping is disabled, the local device is in the hopping state. + +**Procedure** + +1. When initiating screen hopping, make sure that the local device is not in the hopped state. +2. When disabling screen hopping, make sure that the local device is not in the free state. +3. When disabling screen hopping, make sure that the local device is not in the hopping state. diff --git a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md index 4f45c7d0057984677b67f5a494667462e4a3fedb..219f56460536de918a7bf5b631000e562ce2e507 100644 --- a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md +++ b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md @@ -4,9 +4,14 @@ > > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md). -The error codes of the file management subsystem consist of the following:
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- Spatial statistics error codes +The error codes of the file management subsystem include the following: -## Basic File I/O Error Codes +- [Basic File IO Error Codes](#basic-file-io-error-codes) +- [User Data Management Error Codes](#user-data-management-error-code) +- [User File Access Error Codes](#user-file-access-error-codes) +- [Space Statistics Error Codes](#space-statistics-error-codes) + +## Basic File IO Error Codes ### 13900001 Operation Not Permitted @@ -49,6 +54,7 @@ The process does not exist. **Solution** 1. Check whether the process is killed unexpectedly. + 2. Check whether the service related to the process has started. ### 13900004 System Call Interrupted @@ -64,6 +70,7 @@ The system call is interrupted by another thread. **Solution** 1. Check the multi-thread code logic. + 2. Invoke the system call again. ### 13900005 I/O Error @@ -161,7 +168,9 @@ Out of memory A memory overflow occurs. **Solution** + 1. Check the memory overhead. + 2. Control the memory overhead. ### 13900012 Permission Denied @@ -172,13 +181,14 @@ Permission denied **Possible Causes** - - 1. You do not have the permission to operate the file. + 2. The file sandbox path is incorrect. **Solution** -1. Check that you have the permission to operate the file. + +1. Check that the required permission is available. + 2. Check that the file sandbox path is correct. ### 13900013 Incorrect Address @@ -375,7 +385,7 @@ Seek is used in pipe or FIFO. **Solution** -Check the use of seek. +Check the use of **seek()**. ### 13900027 Read-Only File System @@ -460,6 +470,7 @@ The specified directory is not empty. **Solution** 1. Check the directory. + 2. Ensure that the directory is empty. ### 13900033 Too Many Symbol Links @@ -516,7 +527,7 @@ The device pointed to by the file descriptor is not a character stream device. **Solution** -Check whether the file descriptor points to a stream device. +Check whether the file descriptor points to a stream. ### 13900037 No Data Available @@ -599,7 +610,9 @@ Unknown error The error is unidentified. **Solution** + 1. Call the API again. + 2. Restart the service. ## User Data Management Error Codes @@ -636,7 +649,7 @@ Use the obtained URI. **Error Message** -Invalid file extension +Invalid file name extension **Possible Causes** @@ -660,7 +673,7 @@ The file is moved to the Recycle Bin. Check whether the file is in the Recycle Bin. -## Spatial Statistics Error Codes +## Space Statistics Error Codes ### 13600001 IPC Failed @@ -680,7 +693,7 @@ Check whether the service is started. **Error Message** -Not supported file system +Not supported filesystem **Possible Causes** @@ -767,11 +780,15 @@ Check whether the specified directory or node exists. No such object **Possible Causes** + 1. The specified volume ID is incorrect. + 2. The specified bundle name is incorrect. **Solution** + 1. Check whether the specified volume exists. + 2. Check whether the specified bundle name exists. ### 13600009 Invalid User ID @@ -799,6 +816,7 @@ IPC error **Possible Causes** 1. The server service does not exist. + 2. The extension mechanism is abnormal. **Solution** @@ -854,7 +872,9 @@ Check the data returned by the server. Fail to register notification **Possible Causes** + 1. The server service does not exist. + 2. The extension mechanism is abnormal. **Solution** @@ -868,7 +888,9 @@ Check that the server service exists. Fail to remove notification **Possible Causes** + 1. The server service does not exist. + 2. The extension mechanism is abnormal. **Solution** @@ -896,47 +918,11 @@ Check whether the specified Notify agent is registered. Fail to notify agent **Possible Causes** + 1. The service does not exist. + 2. The extension mechanism is abnormal. **Solution** Check whether the client is normal. - -## Error Code Adaptation -The APIs provided by the file management subsystem support exception handling. -Sample code for exception handling in a synchronous API: -```js -import fs from '@ohos.file.fs' - -try { - let file = fs.openSync(path, fs.OpenMode.READ_ONLY); -} catch (err) { - console.error("openSync errCode:" + err.code + ", errMessage:" + err.message); -} -``` -Sample code for exception handling in an asynchronous API (promise): -```js -import fs from '@ohos.file.fs' - -try { - let file = await fs.open(path, fs.OpenMode.READ_ONLY); -} catch (err) { - console.error("open promise errCode:" + err.code + ", errMessage:" + err.message); -} -``` - -Sample code for exception handling in an asynchronous API (callback): -```js -import fs from '@ohos.file.fs' - -try { - fs.open(path, fs.OpenMode.READ_ONLY, function(e, file){ // Asynchronous thread (such as the system call) errors are obtained via a callback. - if (e) { - console.error("open in async errCode:" + e.code + ", errMessage:" + e.message); - } - }); -} catch (err) {// Main thread errors (such as invalid parameters) are obtained by try catch. - console.error("open callback errCode:" + err.code + ", errMessage:" + err.message); -} -``` diff --git a/en/application-dev/reference/native-apis/image.md b/en/application-dev/reference/native-apis/image.md index 218c78042c84bc5a43edf57b4849d08c0f6808a4..365d04c8dca0a1b718593337237a8e5fb4f0bcb9 100644 --- a/en/application-dev/reference/native-apis/image.md +++ b/en/application-dev/reference/native-apis/image.md @@ -1,13 +1,14 @@ # Image -## Overview - Provides APIs for obtaining pixel map data and information. -\@Syscap SystemCapability.Multimedia.Image +To use the APIs in this file, **libpixelmap_ndk.z.so** is required. + +@Syscap SystemCapability.Multimedia.Image + +**Since** -**Since:** 8 @@ -16,150 +17,180 @@ Provides APIs for obtaining pixel map data and information. ### Files -| Name | Description | +| Name| Description| | -------- | -------- | -| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | Declares the APIs that can lock, access, and unlock pixel map data.
File to Include: | +| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | Declares the APIs that can lock, access, and unlock a pixel map.
File to include:: | ### Structs -| Name | Description | +| Name| Description| | -------- | -------- | -| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | Defines the pixel map information. | -| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | Defines the options used for creating a pixel map. | +| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | Defines the pixel map information.| +| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | Defines the options used for creating a pixel map.| ### Types -| Name | Description | +| Name| Description| | -------- | -------- | -| [NativePixelMap](#nativepixelmap) | Defines the data type name of the native pixel map. | +| [NativePixelMap](#nativepixelmap) | Defines the data type name of the native pixel map.| ### Enums -| Name | Description | +| Name| Description| | -------- | -------- | -| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | Enumerates the error codes returned by a function. | -| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | Enumerates the pixel formats. | -| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | Enumerates the pixel map alpha types. | -| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | Enumerates the pixel map scale modes. | -| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | Enumerates the pixel map editing types. | +| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | Enumerates the error codes returned by the functions.| +| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | Enumerates the pixel formats.| +| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | Enumerates the pixel map alpha types.| +| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | Enumerates the pixel map scale modes.| +| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | Enumerates the pixel map editing types.| ### Functions -| Name | Description | -| -------- | -------- | -| [OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) structure. | -| [OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | Obtains the memory address of the **PixelMap** object data and locks the memory. | -| [OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | Unlocks the memory of the **PixelMap** object data. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs. | -| [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | Creates a **PixelMap** object. | -| [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | Creates a **PixelMap** object that contains only alpha channel information. | -| [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | Initializes a **PixelMap** object. | -| [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | Obtains the number of bytes per row of a **PixelMap** object. | -| [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*[editable](image__pixel__map__napi_8h.md#editable)) | Checks whether a **PixelMap** object is editable. | -| [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | Checks whether a **PixelMap** object supports alpha channels. | -| [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | Sets an alpha channel for a **PixelMap** object. | -| [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | Obtains the pixel density of a **PixelMap** object. | -| [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | Sets the pixel density for a **PixelMap** object. | -| [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | Sets the opacity for a **PixelMap** object. | -| [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Scales a **PixelMap** object. | -| [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Translates a **PixelMap** object. | -| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | Rotates a **PixelMap** object. | -| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | Flips a **PixelMap** object. | -| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](image__pixel__map__napi_8h.md#width), int32_t [height](image__pixel__map__napi_8h.md#height)) | Crops a **PixelMap** object. | +| Name| Description| +| -------- | -------- | +| [OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) struct.| +| [OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | Obtains the memory address of a **PixelMap** object and locks the memory.| +| [OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | Unlocks the memory of a **PixelMap** object. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs.| +| [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | Creates a **PixelMap** object.| +| [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | Creates a **PixelMap** object that contains only alpha channel information.| +| [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | Initializes a **PixelMap** object.| +| [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | Obtains the number of bytes per row of a **PixelMap** object.| +| [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*[editable](image__pixel__map__napi_8h.md#editable)) | Checks whether a **PixelMap** object is editable.| +| [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | Checks whether a **PixelMap** object supports alpha channels.| +| [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | Sets an alpha channel for a **PixelMap** object.| +| [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | Obtains the pixel density of a **PixelMap** object.| +| [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | Sets the pixel density for a **PixelMap** object.| +| [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | Sets the opacity for a **PixelMap** object.| +| [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Scales a **PixelMap** object.| +| [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Translates a **PixelMap** object.| +| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | Rotates a **PixelMap** object.| +| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | Flips a **PixelMap** object.| +| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](image__pixel__map__napi_8h.md#width), int32_t [height](image__pixel__map__napi_8h.md#height)) | Crops a **PixelMap** object.| + ## Type Description ### NativePixelMap - + ``` -typedef struct NativePixelMapNativePixelMap +typedef struct NativePixelMap ``` -**Description:**
+**Description** + Defines the data type name of the native pixel map. +**Since** + +9 + + ## Enum Description ### anonymous enum - + ``` anonymous enum ``` -**Description**
-Enumerates the error codes returned by a function. +**Description** + +Enumerates the error codes returned by the functions. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_IMAGE_RESULT_SUCCESS | Operation success. | -| OHOS_IMAGE_RESULT_BAD_PARAMETER | Invalid value. | +| OHOS_IMAGE_RESULT_SUCCESS| Operation success.| +| OHOS_IMAGE_RESULT_BAD_PARAMETER| Invalid value.| +**Since** + +8 ### anonymous enum - + ``` anonymous enum ``` -**Description**
+**Description** + Enumerates the pixel formats. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_FORMAT_NONE | Unknown format. | -| OHOS_PIXEL_MAP_FORMAT_RGBA_8888 | 32-bit RGBA, with 8 bits each for R (red), G (green), B (blue), and A (alpha). The data is stored from the most significant bit to the least significant bit. | -| OHOS_PIXEL_MAP_FORMAT_RGB_565 | 16-bit RGB, with 5, 6, and 5 bits for R, G, and B, respectively. The storage sequence is from the most significant bit to the least significant bit. | +| OHOS_PIXEL_MAP_FORMAT_NONE| Unknown format.| +| OHOS_PIXEL_MAP_FORMAT_RGBA_8888| 32-bit RGBA, with 8 bits each for R (red), G (green), B (blue), and A (alpha). The data is stored from the most significant bit to the least significant bit.| +| OHOS_PIXEL_MAP_FORMAT_RGB_565| 16-bit RGB, with 5, 6, and 5 bits for R, G, and B, respectively. The storage sequence is from the most significant bit to the least significant bit.| + +**Since** + +8 ### anonymous enum - + ``` anonymous enum ``` -**Description:**
+**Description** + Enumerates the pixel map alpha types. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN | Unknown format. | -| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE | Opaque format. | -| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL | Premultiplied format. | -| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL | Unpremultiplied format. | +| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN| Unknown format.| +| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE| Opaque format.| +| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL| Premultiplied format.| +| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL| Unpremultiplied format.| + +**Since** +9 ### anonymous enum - + ``` anonymous enum ``` -**Description:**
+**Description** + Enumerates the pixel map scale modes. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE | Adaptation to the target image size. | -| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP | Cropping the center portion of an image to the target size. | +| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE| Adaptation to the target image size.| +| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP| Cropping the center portion of an image to the target size.| + +**Since** + +9 ### anonymous enum - + ``` anonymous enum ``` -**Description:**
+**Description** + Enumerates the pixel map editing types. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_READ_ONLY | Read-only. | -| OHOS_PIXEL_MAP_EDITABLE | Editable. | +| OHOS_PIXEL_MAP_READ_ONLY| Read-only.| +| OHOS_PIXEL_MAP_EDITABLE| Editable.| + +**Since** + +9 ## Function Description @@ -167,561 +198,552 @@ Enumerates the pixel map editing types. ### OH_AccessPixels() - + ``` int32_t OH_AccessPixels (napi_env env, napi_value value, void ** addrPtr ) ``` -**Description**
-Obtains the memory address of the **PixelMap** object data and locks the memory. +**Description** + +Obtains the memory address of a **PixelMap** object and locks the memory. -After the function is executed successfully, **\*addrPtr** is the address of the memory to be accessed. After the access operation is complete, you must use [OH_UnAccessPixels](#oh_unaccesspixels) to unlock the memory. Otherwise, the resources in the memory cannot be released. After being unlocked, the memory address cannot be accessed or operated. +After the function is executed successfully, **\*addrPtr** is the address of the memory to be accessed. After the access operation is complete, you must use [OH_UnAccessPixels](#oh_unaccesspixels) to unlock the memory. Otherwise, the resources in the memory cannot be released. After the memory is unlocked, its address cannot be accessed or operated. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | -| addrPtr | Indicates the double pointer to the memory address. | +| env | Indicates the NAPI environment pointer.| +| value | Indicates the **PixelMap** object at the application layer.| +| addrPtr | Indicates the double pointer to the memory address.| - **See** +**See** UnAccessPixels **Returns** -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. +Returns **OHOS_IMAGE_RESULT_SUCCESS** if the operation is successful; returns an error code otherwise. + +**Since** +8 ### OH_GetImageInfo() - + ``` -int32_t OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info ) +struct OhosPixelMapCreateOps OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info ) ``` -**Description**
-Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) structure. +**Description** + +Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) struct. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | -| info | Indicates the pointer to the object that stores the information obtained. For details, see [OhosPixelMapInfo](_ohos_pixel_map_info.md). | +| env | Indicates the NAPI environment pointer.| +| value | Indicates the **PixelMap** object at the application layer.| +| info | Indicates the pointer to the object that stores the information obtained. For details, see [OhosPixelMapInfo](_ohos_pixel_map_info.md).| **Returns** Returns **0** if the information is obtained and stored successfully; returns an error code otherwise. - **See** +**See** [OhosPixelMapInfo](_ohos_pixel_map_info.md) +**Since** -### OH_UnAccessPixels() - - -``` -int32_t OH_UnAccessPixels (napi_env env, napi_value value ) -``` -**Description**
-Unlocks the memory of the **PixelMap** object data. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | - -**Returns** - -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. - - **See** +8 -AccessPixels ### OH_PixelMap_CreateAlphaPixelMap() - + ``` int32_t OH_PixelMap_CreateAlphaPixelMap (napi_env env, napi_value source, napi_value * alpha ) ``` -**Description:**
+**Description** + Creates a **PixelMap** object that contains only alpha channel information. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| source | Indicates the options for setting the **PixelMap** object. | -| alpha | Indicates the pointer to the alpha channel. | +| env | Indicates the NAPI environment pointer.| +| source | Indicates the options for setting the **PixelMap** object.| +| alpha | Indicates the pointer to the alpha channel.| **Returns** Returns a **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** CreateAlphaPixelMap +**Since** + +9 + ### OH_PixelMap_CreatePixelMap() - + ``` int32_t OH_PixelMap_CreatePixelMap (napi_env env, OhosPixelMapCreateOps info, void * buf, size_t len, napi_value * res ) ``` -**Description:**
+**Description** + Creates a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| info | Indicates the options for setting the **PixelMap** object. | -| buf | Indicates the pointer to the buffer of the image. | -| len | Indicates the image size. | -| res | Indicates the pointer to the **PixelMap** object at the application layer. | +| env | Indicates the NAPI environment pointer.| +| info | Indicates the options for setting the **PixelMap** object.| +| buf | Indicates the pointer to the buffer of the image.| +| len | Indicates the image size.| +| res | Indicates the pointer to the **PixelMap** object at the application layer.| **Returns** Returns a **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** CreatePixelMap +**Since** + +9 + ### OH_PixelMap_Crop() - + ``` int32_t OH_PixelMap_Crop (const NativePixelMap * native, int32_t x, int32_t y, int32_t width, int32_t height ) ``` -**Description:**
+**Description** + Crops a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Indicates the x-coordinate of the upper left corner of the target image. | -| y | Indicates the y-coordinate of the upper left corner of the target image. | -| width | Indicates the width of the cropped region. | -| height | Indicates the height of the cropped region. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Indicates the x-coordinate of the upper left corner of the target image.| +| y | Indicates the y-coordinate of the upper left corner of the target image.| +| width | Indicates the width of the cropped region.| +| height | Indicates the height of the cropped region.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Crop +**Since** + +9 + ### OH_PixelMap_Flip() - + ``` int32_t OH_PixelMap_Flip (const NativePixelMap * native, int32_t x, int32_t y ) ``` -**Description:**
+**Description** + Flips a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Specifies whether to flip around the x axis. | -| y | Specifies whether to flip around the y axis. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Specifies whether to flip around the x axis.| +| y | Specifies whether to flip around the y axis.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Flip +**Since** + +9 + ### OH_PixelMap_GetBytesNumberPerRow() - + ``` int32_t OH_PixelMap_GetBytesNumberPerRow (const NativePixelMap * native, int32_t * num ) ``` -**Description:**
+**Description** + Obtains the number of bytes per row of a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| num | Indicates the pointer to the number of bytes per row of the **PixelMap** object. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| num | Indicates the pointer to the number of bytes per row of the **PixelMap** object.| **Returns** Returns the number of bytes per row of the **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** GetBytesNumberPerRow +**Since** + +9 ### OH_PixelMap_GetDensity() - + ``` int32_t OH_PixelMap_GetDensity (const NativePixelMap * native, int32_t * density ) ``` -**Description:**
+**Description** + Obtains the pixel density of a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| density | Indicates the pointer to the pixel density. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| density | Indicates the pointer to the pixel density.| **Returns** Returns the pixel density if the operation is successful; returns an error code otherwise. - **See** +**See** GetDensity +**Since** -### OH_PixelMap_GetImageInfo() - - -``` -int32_t OH_PixelMap_GetImageInfo (const NativePixelMap * native, OhosPixelMapInfo * info ) -``` -**Description:**
-Obtains the image information of a **PixelMap** object. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| info | Indicates the pointer to the image information. | - -**Returns** - -Returns **0** if the operation is successful; returns an error code otherwise. - - **See** - -[OhosPixelMapInfo](_ohos_pixel_map_info.md) +9 ### OH_PixelMap_GetIsEditable() - + ``` int32_t OH_PixelMap_GetIsEditable (const NativePixelMap * native, int32_t * editable ) ``` -**Description:**
+**Description** + Checks whether a **PixelMap** object is editable. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| editable | Indicates the pointer to the editing type of the **PixelMap** object. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| editable | Indicates the pointer to the editing type of the **PixelMap** object.| **Returns** Returns an enumerated value that indicates the editing type of the **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** GetIsEditable +**Since** + +9 + ### OH_PixelMap_InitNativePixelMap() - + ``` NativePixelMap* OH_PixelMap_InitNativePixelMap (napi_env env, napi_value source ) ``` -**Description:**
+**Description** + Initializes a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| source | Indicates the options for setting the **PixelMap** object. | +| env | Indicates the NAPI environment pointer.| +| source | Indicates the options for setting the **PixelMap** object.| **Returns** Returns a pointer to the **NativePixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** InitNativePixelMap +**Since** + +9 + ### OH_PixelMap_IsSupportAlpha() - + ``` int32_t OH_PixelMap_IsSupportAlpha (const NativePixelMap * native, int32_t * alpha ) ``` -**Description:**
+**Description** + Checks whether a **PixelMap** object supports alpha channels. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| alpha | Indicates the pointer to the support for alpha channels. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| alpha | Indicates the pointer to the support for alpha channels.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** IsSupportAlpha +**Since** + +9 + + ### OH_PixelMap_Rotate() - + ``` int32_t OH_PixelMap_Rotate (const NativePixelMap * native, float angle ) ``` -**Description:**
+**Description** + Rotates a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| angle | Indicates the angle to rotate. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| angle | Indicates the angle to rotate.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Rotate +**Since** + +9 + ### OH_PixelMap_Scale() - + ``` int32_t OH_PixelMap_Scale (const NativePixelMap * native, float x, float y ) ``` -**Description:**
+**Description** + Scales a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Indicates the scaling ratio of the width. | -| y | Indicates the scaling ratio of the height. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Indicates the scaling ratio of the width.| +| y | Indicates the scaling ratio of the height.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Scale +**Since** + +9 + ### OH_PixelMap_SetAlphaAble() - + ``` int32_t OH_PixelMap_SetAlphaAble (const NativePixelMap * native, int32_t alpha ) ``` -**Description:**
+**Description** + Sets an alpha channel for a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| alpha | Indicates the alpha channel to set. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| alpha | Indicates the alpha channel to set.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** SetAlphaAble +**Since** + +9 + ### OH_PixelMap_SetDensity() - + ``` int32_t OH_PixelMap_SetDensity (const NativePixelMap * native, int32_t density ) ``` -**Description:**
+**Description** + Sets the pixel density for a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| density | Indicates the pixel density to set. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| density | Indicates the pixel density to set.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** GetDensity +**Since** + +9 + ### OH_PixelMap_SetOpacity() - + ``` int32_t OH_PixelMap_SetOpacity (const NativePixelMap * native, float opacity ) ``` -**Description:**
+**Description** + Sets the opacity for a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| opacity | Indicates the opacity to set. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| opacity | Indicates the opacity to set.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** SetOpacity +**Since** + +9 + ### OH_PixelMap_Translate() - + ``` int32_t OH_PixelMap_Translate (const NativePixelMap * native, float x, float y ) ``` -**Description:**
+**Description** + Translates a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Indicates the horizontal distance to translate. | -| y | Indicates the vertical distance to translate. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Indicates the horizontal distance to translate.| +| y | Indicates the vertical distance to translate.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Translate +**Since** -### OH_PixelMap_UnAccessPixels() - - -``` -int32_t OH_PixelMap_UnAccessPixels (const NativePixelMap * native) -``` -**Description:**
-Unlocks the memory of the **NativePixelMap** object data. This function is used with [OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels) in pairs. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | - -**Returns** - -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. - - **See** - -AccessPixels - - -### OH_PixelMap_AccessPixels() - - -``` -int32_t OH_PixelMap_AccessPixels(const NativePixelMap* native, void** addr) -``` -**Description:**
-Obtains the memory address of a **NativePixelMap** object and locks the memory. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| addr | Indicates the double pointer to the memory address. | - -**Returns** - -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. - - **See** - -UnAccessPixels +9 ### OH_UnAccessPixels() - + ``` int32_t OH_UnAccessPixels (napi_env env, napi_value value ) ``` -**Description:**
+**Description** + Unlocks the memory of a **PixelMap** object. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | +| env | Indicates the NAPI environment pointer.| +| value | Indicates the **PixelMap** object at the application layer.| **Returns** -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. +Returns **OHOS_IMAGE_RESULT_SUCCESS** if the operation is successful; returns an error code otherwise. - **See** +**See** AccessPixels + +**Since** + +8 \ No newline at end of file diff --git a/en/application-dev/reference/native-lib/Readme-EN.md b/en/application-dev/reference/native-lib/Readme-EN.md index e57d19d10689c860c3a0f5f5904986e9d7e40742..d0ac26033d50f5bf9b3a2f94bf90d141d6db86be 100644 --- a/en/application-dev/reference/native-lib/Readme-EN.md +++ b/en/application-dev/reference/native-lib/Readme-EN.md @@ -4,6 +4,7 @@ - [Native Standard Libraries Supported by Openharmony](third_party_libc/musl.md) - Appendix - [Native API Symbols Not Exported](third_party_libc/musl-peculiar-symbol.md) + - [Native API Symbols That May Fail to Be Invoked Due to Permission Control](third_party_libc/musl-permission-control-symbol.md) - [EGL Symbols Exported from Native APIs](third_party_opengl/egl-symbol.md) - [OpenGL ES 3.0 Symbols Exported from Native APIs](third_party_opengl/openglesv3-symbol.md) - [OpenSL ES Interfaces Supported by Native APIs](third_party_opensles/opensles.md) \ No newline at end of file diff --git a/en/application-dev/reference/syscap-list.md b/en/application-dev/reference/syscap-list.md index 13f565e43ee3cbdc19d843a3385ffb84e91b05de..f550259f41ac46bd6841083f87c412ba4e6c9a0f 100644 --- a/en/application-dev/reference/syscap-list.md +++ b/en/application-dev/reference/syscap-list.md @@ -295,6 +295,14 @@ Input device management | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | Yes | No | No | Yes | Yes | Yes | No | No | +## SystemCapability.MultimodalInput.Input.RemoteInputDevice + +Remote input device + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + ## SystemCapability.MultimodalInput.Input.InputMonitor Input event listener @@ -319,6 +327,14 @@ Input event simulator | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | Yes | No | No | Yes | Yes | Yes | No | No | +## SystemCapability.MultimodalInput.Input.InputFilter + +Input filter + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + ## SystemCapability.PowerManager.BatteryManager.Extension Battery manager extension capability @@ -1333,7 +1349,7 @@ Webview component | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | -| Yes | No | Yes | Yes | Yes | Yes | No | No | +| Yes | No | No | Yes | Yes | No | No | No | ## SystemCapability.Cloud.AAID @@ -1623,9 +1639,9 @@ Quick fix | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | Yes | No | Yes | Yes | Yes | Yes | No | No | -## SystemCapability.MultimodalInput.Input.Pointer +## SystemCapability.MultimodalInput.Input.ShortKey -Pointer input enhancement +Shortcut keys | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | @@ -1654,3 +1670,11 @@ General type | Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Msdp.DeviceStatus.Cooperate + +Device status awareness + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | diff --git a/en/application-dev/ui/arkts-graphics-display.md b/en/application-dev/ui/arkts-graphics-display.md index df77d7661115f10ac59cb348933208df50896c40..38cf2605333d884701952b0bebce21e09d2c3d06 100644 --- a/en/application-dev/ui/arkts-graphics-display.md +++ b/en/application-dev/ui/arkts-graphics-display.md @@ -117,7 +117,7 @@ Data sources of the archived type can be classified into local resources, online } } ``` - 2. Check the format of the URL obtained from the media library is as follows: + 2. Check the format of the URL obtained from the media library: ​ ```ts Image('file://media/5') diff --git a/en/application-dev/ui/arkts-layout-update-animation.md b/en/application-dev/ui/arkts-layout-update-animation.md new file mode 100644 index 0000000000000000000000000000000000000000..d5110e2eac29cd3dfe6b235479b75969cf541d54 --- /dev/null +++ b/en/application-dev/ui/arkts-layout-update-animation.md @@ -0,0 +1,270 @@ +# Layout Update Animation + + +[Explicit animation](../reference/arkui-ts/ts-explicit-animation.md) (**animateTo**) and [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) (**animation**) are the most basic and common animation features provided by ArkUI. When the layout attributes (such as the [size](../reference/arkui-ts/ts-universal-attributes-size.md) and [position](../reference/arkui-ts/ts-universal-attributes-location.md)) attributes change, you can use the attribute animation or explicit animation to transit to the new layout parameter status based on the animation parameters. + + +| Animation Type| Description | +| ---- | ---------------------------------------- | +| Explicit animation| Triggered by changes in a closure, including component addition and deletion caused by data changes and component attribute changes.| Complex animation scenarios| +| Attribute animation| Triggered when the attribute changes. The animation setting is simple. | + + +## Using Explicit Animation to Create Layout Update Animation + +The API for explicit animation is as follows: + + +```ts +animateTo(value: AnimateParam, event: () => void): void +``` + +The first parameter specifies the animation parameter, and the second parameter is the closure function of the animation. + +The following is an example of using explicit animation to create a layout update animation. In the example, when the **\** component's **alignItems** attribute is updated, the layout of its child components changes. As long as the attribute is updated in the closure function of **animateTo**, animation is performed as configured through **animateTo** for all changes caused by the attribute toward the end value. + + +```ts +@Entry +@Component +struct LayoutChange { + // Used to control the alignItems attribute of a column. + @State itemAlign: HorizontalAlign = HorizontalAlign.Start; + allAlign: HorizontalAlign[] = [HorizontalAlign.Start, HorizontalAlign.Center, HorizontalAlign.End]; + alignIndex: number = 0; + + build() { + Column() { + Column({ space: 10 }) { + Button("1").width(100).height(50) + Button("2").width(100).height(50) + Button("3").width(100).height(50) + } + .margin(20) + .alignItems(this.itemAlign) + .borderWidth(2) + .width("90%") + .height(200) + + Button("click").onClick(() => { + // The animation duration is 1000 ms, and the curve is EaseInOut. + animateTo({ duration: 1000, curve: Curve.EaseInOut }, () => { + this.alignIndex = (this.alignIndex + 1) % this.allAlign.length; + // Modify the this.itemAlign parameter in the closure function to change the layout of child elements in the container. The animation for transition to the new position is applied. + this.itemAlign = this.allAlign[this.alignIndex]; + }); + }) + } + .width("100%") + .height("100%") + } +} +``` + + +![layoutChange1](figures/layoutChange1.gif) + + +In addition to directly changing the layout, you can also change the width, height, and position of a component. + + + +```ts +@Entry +@Component +struct LayoutChange2 { + @State myWidth: number = 100; + @State myHeight: number = 50; + // Flag. true and false correspond to a group of myWidth and myHeight values, respectively. + @State flag: boolean = false; + + build() { + Column({ space: 10 }) { + Button("text") + .type(ButtonType.Normal) + .width(this.myWidth) + .height(this.myHeight) + .margin(20) + Button("area: click me") + .fontSize(12) + .margin(20) + .onClick(() => { + animateTo({ duration: 1000, curve: Curve.Ease }, () => { + // In the animation closure, the state variables that control the width and height of the first button are changed based on the flag settings so that the width and height of the first button are animated. + if (this.flag) { + this.myWidth = 100; + this.myHeight = 50; + } else { + this.myWidth = 200; + this.myHeight = 100; + } + this.flag = !this.flag; + }); + }) + } + .width("100%") + .height("100%") + } +} +``` + + +In the click event of the second button, the **animateTo** API is used to modify the **this.myWidth** and **this.myHeight** state variables in the closure. As these two state variables set the width and height of the first button, the width and height animation is performed for the first button. The display effect is shown below. + + +![layoutChange2_animateTo](figures/layoutChange2_animateTo.gif) + + +At the same time, the second button also produces a position animation. After the width and height of the first button are changed, the layout of other components in the column is also changed, and the second button is among those other components. + + +If you do not want the second button to have an animation effect, you can use either of the following methods: 1. Add a container outside the first button so that the sizes before and after the animation are within the range of the container. In this way, the position of the second button is not affected by the position of the first button. The key code is as follows: + + + +```ts +Column({ space: 10 }) { + Column() { + // The button is placed in a container that is large enough so that it does not affect the position of the outer component. + Button("text") + .type(ButtonType.Normal) + .width(this.myWidth) + .height(this.myHeight) + } + .margin(20) + .width(200) + .height(100) + + Button("area: click me") + .fontSize(12) + .onClick(() => { + animateTo({ duration: 1000, curve: Curve.Ease }, () => { + // In the animation closure, the state variables that control the width and height of the first button are changed based on the flag settings so that the width and height of the first button are animated. + if (this.flag) { + this.myWidth = 100; + this.myHeight = 50; + } else { + this.myWidth = 200; + this.myHeight = 100; + } + this.flag = !this.flag; + }); + }) +} +.width("100%") +.height("100%") +``` + + +![layoutChange2_animateTo_change](figures/layoutChange2_animateTo_change.gif) + + +2. Add layout constraints to the second button. For example, add position constraints so that the position of the second button is not affected by the width and height of the first button. The sample code is as follows: + + + +```ts +Column({ space: 10 }) { + Button("text") + .type(ButtonType.Normal) + .width(this.myWidth) + .height(this.myHeight) + .margin(20) + + Button("area: click me") + .fontSize(12) + // Set the position attribute to a fixed value so that the position of the second button is not affected by the width and height of the first button. + .position({ x: "30%", y: 200 }) + .onClick(() => { + animateTo({ duration: 1000, curve: Curve.Ease }, () => { + // In the animation closure, the state variables that control the width and height of the first button are changed based on the flag settings so that the width and height of the first button are animated. + if (this.flag) { + this.myWidth = 100; + this.myHeight = 50; + } else { + this.myWidth = 200; + this.myHeight = 100; + } + this.flag = !this.flag; + }); + }) +} +.width("100%") +.height("100%") +``` + + +## Using Attribute Animation to Generate Layout Update Animation + +Unlike explicit animation, which requires the attribute changes for triggering animation to be placed in the closure function, attribute animation does not need to use the closure. You only need to append the **animation** attribute to the target component attribute. + +The API of the attribute animation is as follows: + + +```ts +animation(value: AnimateParam) +``` + +This API accepts an animation parameter as its argument. If you want the component to generate an animation with the value change of an attribute, add this attribute before the **animation** attribute. Otherwise, you can place the attribute after the **animation** attribute. The previous example of explicit animation can be easily implemented with attribute animation. The sample code is as follows: + + + +```ts +@Entry +@Component +struct LayoutChange2 { + @State myWidth: number = 100; + @State myHeight: number = 50; + @State flag: boolean = false; + @State myColor: Color = Color.Blue; + + build() { + Column({ space: 10 }) { + Button("text") + .type(ButtonType.Normal) + .width(this.myWidth) + .height(this.myHeight) + // The animation takes effect only for the type, width, and height attributes. The duration is 1000 ms, and the curve is Ease. + .animation({ duration: 1000, curve: Curve.Ease }) + // The animation does not take effect for the backgroundColor and margin attributes. + .backgroundColor(this.myColor) + .margin(20) + + Button("area: click me") + .fontSize(12) + .onClick(() => { + // Change the attribute value. Animation transition is performed for attributes configured with attribute animation. + if (this.flag) { + this.myWidth = 100; + this.myHeight = 50; + this.myColor = Color.Blue; + } else { + this.myWidth = 200; + this.myHeight = 100; + this.myColor = Color.Pink; + } + this.flag = !this.flag; + }) + } + } +} +``` + + +In the preceding example, the **animation** attribute of the first button takes effect only for the **type**, **width**, and **height** attributes written before the **animation** attribute, but does not take effect for the **backgroundColor** and **margin** attributes written after. In the running result, the **width** and **height** attributes execute the animation based on the **animation** settings, while the **backgroundColor** attribute changes without any animation applied. The display effect is shown below. + + + + + + +![size-change-animation](figures/size-change-animation.gif) + + +>**NOTE** +> +> 1. Attribute animations are executed according to the configured attribute animation settings. Each component can have its own attribute animation settings. +> +> 2. Explicit animations are executed on all GUI differences caused before and after animation closures, and they share the same animation settings. Therefore, explicit animations are applicable to scenarios where animations are executed in a unified manner. Explicit animations can also be used for animations caused by non-attribute variables, such as **if/else** statements and deletion of array elements used by **ForEach**. +> +> 3. If an attribute animation is configured for an attribute and the attribute value is changed in the explicit animation closure, the attribute animation takes precedence, under the configured animation settings. diff --git a/en/application-dev/ui/figures/layoutChange1.gif b/en/application-dev/ui/figures/layoutChange1.gif new file mode 100644 index 0000000000000000000000000000000000000000..3e03ce67601e2c8b1b4702ede58a7b95c9c65414 Binary files /dev/null and b/en/application-dev/ui/figures/layoutChange1.gif differ diff --git a/en/application-dev/ui/figures/layoutChange2_animateTo.gif b/en/application-dev/ui/figures/layoutChange2_animateTo.gif new file mode 100644 index 0000000000000000000000000000000000000000..ad94cb26c2874bc45ca84a2aaf5d58bbcd864685 Binary files /dev/null and b/en/application-dev/ui/figures/layoutChange2_animateTo.gif differ diff --git a/en/application-dev/ui/figures/layoutChange2_animateTo_change.gif b/en/application-dev/ui/figures/layoutChange2_animateTo_change.gif new file mode 100644 index 0000000000000000000000000000000000000000..14d804c7a0f1e843f218b2551af6f8b51dc421bb Binary files /dev/null and b/en/application-dev/ui/figures/layoutChange2_animateTo_change.gif differ diff --git a/en/application-dev/ui/figures/size-change-animation.gif b/en/application-dev/ui/figures/size-change-animation.gif new file mode 100644 index 0000000000000000000000000000000000000000..fe95f4162af64d2f5cbf4c71645a0317a8fff019 Binary files /dev/null and b/en/application-dev/ui/figures/size-change-animation.gif differ diff --git a/en/application-dev/website.md b/en/application-dev/website.md index c405c879240a79a9511ef8bd29ee8cb75a672c47..b0467126d53d2757607b249734ddc940bfd95150 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -1,4 +1,5 @@ # Application Development + - [Application Development Overview](application-dev-guide.md) - Quick Start - Getting Started @@ -19,6 +20,16 @@ - [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md) - [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md) - [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md) + - [Application Package Update Process](quick-start/application-package-update.md) + - Shared Package + - [Shared Package Overview](quick-start/shared-guide.md) + - [HAR](quick-start/har-package.md) + - HSP + - [In-Application HSP Development](quick-start/in-app-hsp.md) + - [Inter-Application HSP Development (for System Applications Only)](quick-start/cross-app-hsp.md) + - Quick Fix + - [Quick Fix Overview](quick-start/quickfix-principles.md) + - [CLI-based Quick Fix Development](quick-start/quickfix-debug.md) - Application Configuration Files in Stage Model - [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md) - [app.json5 Configuration File](quick-start/app-configuration-file.md) @@ -31,15 +42,40 @@ - [Resource Categories and Access](quick-start/resource-categories-and-access.md) - Learning ArkTS - [Getting Started with ArkTS](quick-start/arkts-get-started.md) - - ArkTS Syntax (Declarative UI) - - [Basic UI Description](quick-start/arkts-basic-ui-description.md) - - State Management - - [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md) - - [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md) - - [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md) - - [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md) - - [Rendering Control](quick-start/arkts-rendering-control.md) - - [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md) + - Basic Syntax + - [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md) + - [Declarative UI Description](quick-start/arkts-declarative-ui-description.md) + - Custom Component + - [Creating a Custom Component](quick-start/arkts-create-custom-components.md) + - [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md) + - [\@Builder: Custom Builder Function](quick-start/arkts-builder.md) + - [\@BuilderParam: @Builder Function Reference](quick-start/arkts-builderparam.md) + - [\@Styles: Definition of Resusable Styles](quick-start/arkts-style.md) + - [\@Extend: Extension of Built-in Components](quick-start/arkts-extend.md) + - [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md) + - State Management + - [State Management Overview](quick-start/arkts-state-management-overview.md) + - Component State Management + - [\@State: State Owned by Component](quick-start/arkts-state.md) + - [\@Prop: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md) + - [\@Link: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md) + - [\@Provide and \@Consume: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md) + - [\@Observed and \@ObjectLink: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md) + - Application State Management + - [Application State Management Overview](quick-start/arkts-application-state-management-overview.md) + - [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md) + - [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md) + - [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md) + - [Environment: Device Environment Query](quick-start/arkts-environment.md) + - Other State Management Features + - [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md) + - [\@Watch: Getting Notified of State Variable Changes](quick-start/arkts-watch.md) + - [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md) + - Rendering Control + - [Rendering Control Overview](quick-start/arkts-rendering-control-overview.md) + - [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md) + - [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md) + - [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md) - Development - Application Models - Application Model Overview @@ -59,11 +95,35 @@ - ExtensionAbility Component - [ExtensionAbility Component Overview](application-models/extensionability-overview.md) - [ServiceExtensionAbility](application-models/serviceextensionability.md) - - [DataShareExtensionAbility (for System Applications Only)](application-models/datashareextensionability.md) - - [FormExtensionAbility (Widget)](application-models/widget-development-stage.md) - [AccessibilityExtensionAbility](application-models/accessibilityextensionability.md) + - [EnterpriseAdminExtensionAbility](application-models/enterprise-extensionAbility.md) - [InputMethodExtensionAbility](application-models/inputmethodextentionability.md) - [WindowExtensionAbility](application-models/windowextensionability.md) + - Service Widget Development in Stage Model + - [Service Widget Overview](application-models/service-widget-overview.md) + - Developing an ArkTS Widget + - [ArkTS Widget Working Principles](application-models/arkts-ui-widget-working-principles.md) + - [ArkTS Widget Related Modules](application-models/arkts-ui-widget-modules.md) + - ArkTS Widget Development + - [Creating an ArkTS Widget](application-models/arkts-ui-widget-creation.md) + - [Configuring Widget Configuration Files](application-models/arkts-ui-widget-configuration.md) + - [Widget Lifecycle Management](application-models/arkts-ui-widget-lifecycle.md) + - Widget Page Development + - [Widget Page Capability Overview](application-models/arkts-ui-widget-page-overview.md) + - [Using Animations in the Widget](application-models/arkts-ui-widget-page-animation.md) + - [Applying Custom Drawing in the Widget](application-models/arkts-ui-widget-page-custom-drawing.md) + - Widget Event Development + - [Widget Event Capability Overview](application-models/arkts-ui-widget-event-overview.md) + - [Redirecting to a Specified Page Through the Router Event](application-models/arkts-ui-widget-event-router.md) + - [Updating Widget Content Through FormExtensionAbility](application-models/arkts-ui-widget-event-formextensionability.md) + - [Updating Widget Content Through UIAbility](application-models/arkts-ui-widget-event-uiability.md) + - Widget Data Interaction + - [Widget Data Interaction Overview](application-models/arkts-ui-widget-interaction-overview.md) + - [Configuring a Widget to Update Periodically](application-models/arkts-ui-widget-update-by-time.md) + - [Updating Local and Online Images in the Widget](application-models/arkts-ui-widget-image-update.md) + - [Updating Widget Content by State](application-models/arkts-ui-widget-update-by-status.md) + - [Updating Widget Content by Widget Host (for System Applications Only)](application-models/arkts-ui-widget-content-update.md) + - [Developing a JS Widget](application-models/js-ui-widget-development.md) - [AbilityStage Component Container](application-models/abilitystage.md) - [Context](application-models/application-context-stage.md) - Want @@ -78,22 +138,29 @@ - [Continuation Overview](application-models/inter-device-interaction-hop-overview.md) - [Cross-Device Migration (for System Applications Only)](application-models/hop-cross-device-migration.md) - [Multi-device Collaboration (for System Applications Only)](application-models/hop-multi-device-collaboration.md) - - IPC - - [Process Model](application-models/process-model-stage.md) + - [Subscribing to System Environment Variable Changes](application-models/subscribe-system-environment-variable-changes.md) + - Process Model + - [Process Model Overview](application-models/process-model-stage.md) - Common Events - [Introduction to Common Events](application-models/common-event-overview.md) - - [Subscribing to Common Events](application-models/common-event-subscription.md) + - Common Event Subscription + - [Common Event Subscription Overview](application-models/common-event-subscription-overview.md) + - [Subscribing to Common Events in Dynamic Mode](application-models/common-event-subscription.md) + - [Subscribing to Common Events in Static Mode (for System Applications Only)](application-models/common-event-static-subscription.md) + - [Unsubscribing from Common Events](application-models/common-event-unsubscription.md) - [Publishing Common Events](application-models/common-event-publish.md) - - [Unsubscribing from Common Events](application-models/common-event-unsubscription.md) + - [Removing Sticky Common Events](application-models/common-event-remove-sticky.md) - [Background Services](application-models/background-services.md) - - Inter-Thread Communication - - [Thread Model](application-models/thread-model-stage.md) + - Thread Model + - [Thread Model Overview](application-models/thread-model-stage.md) - [Using Emitter for Inter-Thread Communication](application-models/itc-with-emitter.md) - [Using Worker for Inter-Thread Communication](application-models/itc-with-worker.md) - Mission Management - [Mission Management Scenarios](application-models/mission-management-overview.md) - - [Mission Management and Launch Type](application-models/mission-management-launch-type.md) + - [Mission and Launch Type](application-models/mission-management-launch-type.md) - [Page Stack and MissionList](application-models/page-mission-stack.md) + - [Setting the Icon and Name of a Mission Snapshot](application-models/mission-set-icon-name-for-task-snapshot.md) + - [Application Configuration File (Stage Model)](application-models/config-file-stage.md) - FA Model Development - [FA Model Development Overview](application-models/fa-model-development-overview.md) - FA Mode Application Components @@ -129,14 +196,16 @@ - [Widget Development](application-models/widget-development-fa.md) - [Context](application-models/application-context-fa.md) - [Want](application-models/want-fa.md) - - IPC - - [Process Model](application-models/process-model-fa.md) + - [Component Startup Rules (FA Model)](application-models/component-startup-rules-fa.md) + - Process Model + - [Process Model Overview](application-models/process-model-fa.md) - [Common Events](application-models/common-event-fa.md) - [Background Services](application-models/rpc.md) - - Inter-Thread Communication - - [Thread Model](application-models/thread-model-fa.md) + - Thread Model + - [Thread Model Overview](application-models/thread-model-fa.md) - [Inter-Thread Communication](application-models/itc-fa-overview.md) - [Mission Management](application-models/mission-management-fa.md) + - [Application Configuration File (FA Model)](application-models/config-file-fa.md) - Development of Component Interaction Between the FA Model and Stage Model - [Component Interaction Between the FA Model and Stage Model](application-models/fa-stage-interaction-overview.md) - [Starting a UIAbility from the FA Model](application-models/start-uiability-from-fa.md) @@ -172,32 +241,64 @@ - [Storage Switching](application-models/storage-switch.md) - UI Development - [ArkUI Overview](ui/arkui-overview.md) - - ArkTS-based Declarative Development Paradigm - - [Overview](ui/ui-ts-overview.md) - - [Declarative UI Development Guidelines](ui/ui-ts-developing-intro.md) - - Declarative UI Development Examples - - [Creating a Simple Page](ui/ui-ts-creating-simple-page.md) - - Building a Comprehensive Example - - [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) - - Adding a Splash Screen Animation - - [Using the Drawing Feature](ui/ui-ts-drawing-feature.md) - - [Using the Animation Feature](ui/ui-ts-animation-feature.md) - - [Common Components](ui/ui-ts-components-intro.md) - - Common Layout Development - - Adaptive Layouts - - [Linear Layout](ui/ui-ts-layout-linear.md) - - [Statck Layout](ui/ui-ts-layout-stack.md) - - [Flex Layout](ui/ui-ts-layout-flex.md) - - [Grid Layout](ui/ui-ts-layout-grid.md) - - Responsive Layouts - - [Grid Layout](ui/ui-ts-layout-grid-container-new.md) - - [Media Query](ui/ui-ts-layout-mediaquery.md) - - [Custom Component Lifecycle Callbacks](ui/ui-ts-custom-component-lifecycle-callbacks.md) - - [Web Component Development](ui/ui-ts-components-web.md) - - [Recommendations for Improving Performance](ui/ui-ts-performance-improvement-recommendation.md) + - UI Development (ArkTS-based Declarative Development Paradigm) + - [UI Development (ArkTS-based Declarative Development Paradigm) Overview](ui/arkts-ui-development-overview.md) + - Layout Development + - [Layout Overview](ui/arkts-layout-development-overview.md) + - Building a Layout + - [Linear Layout](ui/arkts-layout-development-linear.md) + - [Stack Layout](ui/arkts-layout-development-stack-layout.md) + - [Flex Layout](ui/arkts-layout-development-flex-layout.md) + - [Relative Layout](ui/arkts-layout-development-relative-layout.md) + - [Responsive Grid Layout](ui/arkts-layout-development-grid-layout.md) + - [Media Query](ui/arkts-layout-development-media-query.md) + - [Creating a List](ui/arkts-layout-development-create-list.md) + - [Creating a Grid](ui/arkts-layout-development-create-grid.md) + - [Creating a Swiper](ui/arkts-layout-development-create-looping.md) + - [Improving Layout Performance](ui/arkts-layout-development-performance-boost.md) + - Adding a Component + - Adding a Common Component + - [Button](ui/arkts-common-components-button.md) + - [Radio Button](ui/arkts-common-components-radio-button.md) + - [Toggle](ui/arkts-common-components-switch.md) + - [Progress Indicator](ui/arkts-common-components-progress-indicator.md) + - [Text Display](ui/arkts-common-components-text-display.md) + - [Text Input](ui/arkts-common-components-text-input.md) + - [Custom Dialog Box](ui/arkts-common-components-custom-dialog.md) + - [Video Playback](ui/arkts-common-components-video-player.md) + - [XComponent](ui/arkts-common-components-xcomponent.md) + - Adding a Bubble and Menu + - [Bubble](ui/arkts-popup-and-menu-components-popup.md) + - [Menu](ui/arkts-popup-and-menu-components-menu.md) + - Setting Page Routing and Component Navigation + - [Page Routing](ui/arkts-routing.md) + - Component Navigation + - [Navigation](ui/arkts-navigation-navigation.md) + - [Tabs](ui/arkts-navigation-tabs.md) + - Using Graphics + - [Displaying Images](ui/arkts-graphics-display.md) + - [Drawing Geometric Shapes](ui/arkts-geometric-shape-drawing.md) + - [Drawing Custom Graphics on the Canvas](ui/arkts-drawing-customization-on-canvas.md) + - Using Animation + - [Animation Overview](ui/arkts-animation-overview.md) + - Animation Within a Page + - [Layout Update Animation](ui/arkts-layout-update-animation.md) + - [Transition Animation Within a Component](ui/arkts-transition-animation-within-component.md) + - [Spring Curve Animation](ui/arkts-spring-animation.md) + - Animation Between Pages + - [Zoom Animation](ui/arkts-zoom-animation.md) + - [Page Transition Animation](ui/arkts-page-transition-animation.md) + - Using Interaction Events + - [Interaction Event Overview](ui/arkts-event-overview.md) + - Universal Events + - [Touchscreen Event](ui/arkts-common-events-touch-screen-event.md) + - [Keyboard and Mouse Event](ui/arkts-common-events-device-input-event.md) + - [Focus Event](ui/arkts-common-events-focus-event.md) + - Gesture Events + - [Gesture Binding](ui/arkts-gesture-events-binding.md) + - [Single Gesture](ui/arkts-gesture-events-single-gesture.md) + - [Combined Gestures](ui/arkts-gesture-events-combined-gestures.md) + - [Recommendations for Improving Performance](ui/arkts-performance-improvement-recommendation.md) - UI Development with JavaScript-compatible Web-like Development Paradigm - [Overview](ui/ui-js-overview.md) - Framework @@ -270,10 +371,27 @@ - [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) + - Web + - [Web Component Overview](web/web-component-overview.md) + - [Loading Pages by Using the Web Component](web/web-page-loading-with-web-components.md) + - Setting Basic Attributes and Events + - [Setting the Dark Mode](web/web-set-dark-mode.md) + - [Uploading Files](web/web-file-upload.md) + - [Opening Pages in a New Window](web/web-open-in-new-window.md) + - [Managing Location Permissions](web/web-geolocation-permission.md) + - Using Frontend Page JavaScript Code on the Application + - [Invoking Frontend Page Functions on the Application](web/web-in-app-frontend-page-function-invoking.md) + - [Invoking Application Functions on the Frontend Page](web/web-in-page-app-function-invoking.md) + - [Establishing a Data Channel Between the Application and the Frontend Page](web/web-app-page-data-channel.md) + - [Managing Page Redirection and Browsing History Navigation](web/web-redirection-and-browsing-history-mgmt.md) + - [Managing Cookies and Data Storage](web/web-cookie-and-data-storage-mgmt.md) + - [Customizing Page Request Responses](web/web-resource-interception-request-mgmt.md) + - [Debugging Frontend Pages by Using DevTools](web/web-debugging-with-devtools.md) - Notification - [Notification Overview](notification/notification-overview.md) - [Notification Subscription (for System Applications Only)](notification/notification-subscription.md) - [Enabling Notification](notification/notification-enable.md) + - [Notification Badge](notification/notification-badge.md) - Publishing a Notification - [Publishing a Basic Notification](notification/text-notification.md) - [Publishing a Progress Notification](notification/progress-bar-notification.md) @@ -287,30 +405,64 @@ - [WebGL Overview](webgl/webgl-overview.md) - [WebGL Development](webgl/webgl-guidelines.md) - Media + - [Media Application Overview](media/media-application-overview.md) - Audio and Video - - [Audio Overview](media/audio-overview.md) - - [Audio Rendering Development](media/audio-renderer.md) - - [Audio Stream Management Development](media/audio-stream-manager.md) - - [Audio Capture Development](media/audio-capturer.md) - - [OpenSL ES Audio Playback Development](media/opensles-playback.md) - - [OpenSL ES Audio Recording Development](media/opensles-capture.md) - - [Audio Interruption Mode Development](media/audio-interruptmode.md) - - [Volume Management Development](media/audio-volume-manager.md) - - [Audio Routing and Device Management Development](media/audio-routing-manager.md) - - [AVPlayer Development (Recommended)](media/avplayer-playback.md) - - [AVRecorder Development (Recommended)](media/avrecorder.md) - - [Audio Playback Development (To Be Deprecated Soon)](media/audio-playback.md) - - [Audio Recording Development (To Be Deprecated Soon)](media/audio-recorder.md) - - [Video Playback Development (To Be Deprecated Soon)](media/video-playback.md) - - [Video Recording Development (To Be Deprecated Soon)](media/video-recorder.md) - - AVSession + - [Audio and Video Overview](media/av-overview.md) + - [AVPlayer and AVRecorder](media/avplayer-avrecorder-overview.md) + - Audio Playback + - [Audio Playback Overview](media/audio-playback-overview.md) + - [Using AVPlayer for Audio Playback](media/using-avplayer-for-playback.md) + - [Using AudioRenderer for Audio Playback](media/using-audiorenderer-for-playback.md) + - [Using OpenSL ES for Audio Playback](media/using-opensl-es-for-playback.md) + - [Using TonePlayer for Audio Playback (for System Applications Only)](media/using-toneplayer-for-playback.md) + - [Audio Playback Concurrency Policy](media/audio-playback-concurrency.md) + - [Volume Management](media/volume-management.md) + - [Audio Playback Stream Management](media/audio-playback-stream-management.md) + - [Audio Output Device Management](media/audio-output-device-management.md) + - [Distributed Audio Playback (for System Applications Only)](media/distributed-audio-playback.md) + - Audio Recording + - [Audio Recording Overview](media/audio-recording-overview.md) + - [Using AVRecorder for Audio Recording](media/using-avrecorder-for-recording.md) + - [Using AudioCapturer for Audio Recording](media/using-audiocapturer-for-recording.md) + - [Using OpenSL ES for Audio Recording](media/using-opensl-es-for-recording.md) + - [Microphone Management](media/mic-management.md) + - [Audio Recording Stream Management](media/audio-recording-stream-management.md) + - [Audio Input Device Management](media/audio-input-device-management.md) + - Audio Call + - [Audio Call Overview](media/audio-call-overview.md) + - [Developing Audio Call](media/audio-call-development.md) + - [Video Playback](media/video-playback.md) + - [Video Recording](media/video-recording.md) + - AVSession (for System Applications Only) - [AVSession Overview](media/avsession-overview.md) - - [AVSession Development](media/avsession-guidelines.md) + - Local AVSession + - [Local AVSession Overview](media/local-avsession-overview.md) + - [AVSession Provider](media/using-avsession-developer.md) + - [AVSession Controller](media/using-avsession-controller.md) + - Distributed AVSession + - [Distributed AVSession Overview](media/distributed-avsession-overview.md) + - [Using Distributed AVSession](media/using-distributed-avsession.md) + - Camera (for System Applications Only) + - [Camera Overview](media/camera-overview.md) + - Camera Development + - [Camera Development Preparations](media/camera-preparation.md) + - [Device Input Management](media/camera-device-input.md) + - [Session Management](media/camera-session-management.md) + - [Camera Preview](media/camera-preview.md) + - [Camera Photographing](media/camera-shooting.md) + - [Camera Recording](media/camera-recording.md) + - [Camera Metadata](media/camera-metadata.md) + - Best Practices + - [Camera Photographing Sample](media/camera-shooting-case.md) + - [Camera Recording Sample](media/camera-recording-case.md) - Image - - [Image Development](media/image.md) - - Camera - - [Camera Development](media/camera.md) - - [Distributed Camera Development](media/remote-camera.md) + - [Image Overview](media/image-overview.md) + - [Image Decoding](media/image-decoding.md) + - Image Processing + - [Image Transformation](media/image-transformation.md) + - [Pixel Map Operation](media/image-pixelmap-operation.md) + - [Image Encoding](media/image-encoding.md) + - [Image Tool](media/image-tool.md) - Security - Access Control - [Access Control Overview](security/accesstoken-overview.md) @@ -323,6 +475,7 @@ - Key Management - [HUKS Overview](security/huks-overview.md) - [HUKS Development](security/huks-guidelines.md) + - [HUKS Cipher Algorithm Specifications](security/huks-appendix.md) - Crypto Framework - [Crypto Framework Overview](security/cryptoFramework-overview.md) - [Crypto Framework Development](security/cryptoFramework-guidelines.md) @@ -339,10 +492,10 @@ - [HTTP Data Request](connectivity/http-request.md) - [WebSocket Connection](connectivity/websocket-connection.md) - [Socket Connection](connectivity/socket-connection.md) - - [Network Policy Management](connectivity/net-policy-management.md) - [Network Sharing](connectivity/net-sharing.md) - [Ethernet Connection](connectivity/net-ethernet.md) - [Network Connection Management](connectivity/net-connection-manager.md) + - [MDNS Management](connectivity/net-mdns.md) - IPC & RPC - [IPC & RPC Overview](connectivity/ipc-rpc-overview.md) - [IPC & RPC Development](connectivity/ipc-rpc-development-guideline.md) @@ -352,30 +505,48 @@ - [Call Service Development](telephony/telephony-call.md) - [SMS Service Development](telephony/telephony-sms.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 - - [RDB Overview](database/database-relational-overview.md) - - [RDB Development](database/database-relational-guidelines.md) - - Preferences - - [Preferences Overview](database/database-preference-overview.md) - - [Preferences Development](database/database-preference-guidelines.md) - - Distributed Data Object - - [Distributed Data Object Overview](database/database-distributedobject-overview.md) - - [Distributed Data Object Development](database/database-distributedobject-guidelines.md) - - Data Share - - [DataShare Overview](database/database-datashare-overview.md) - - [DataShare Development](database/database-datashare-guidelines.md) + - [Data Management Overview](database/data-mgmt-overview.md) + - Application Data Persistence + - [Overview of Application Data Persistence](database/app-data-persistence-overview.md) + - [Persisting Preferences Data](database/data-persistence-by-preferences.md) + - [Persisting KV Store Data](database/data-persistence-by-kv-store.md) + - [Persisting RDB Store Data](database/data-persistence-by-rdb-store.md) + - Distributed Application Data Synchronization + - [Distributed Application Data Synchronization Overview](database/sync-app-data-across-devices-overview.md) + - [Cross-Device Synchronization of KV Stores](database/data-sync-of-kv-store.md) + - [Cross-Device Synchronization of RDB Stores](database/data-sync-of-rdb-store.md) + - [Cross-Device Synchronization of Distributed Data Objects](database/data-sync-of-distributed-data-object.md) + - Data Reliability and Security + - [Data Reliability and Security Overview](database/data-reliability-security-overview.md) + - [Database Backup and Restoration](database/data-backup-and-restore.md) + - [Database Encryption](database/data-encryption.md) + - [Access Control by Device and Data Level](database/access-control-by-device-and-data-level.md) + - Cross-Application Data Sharing (for System Applications Only) + - [Cross-Application Data Sharing Overview](database/share-device-data-across-apps-overview.md) + - [Sharing Data Using DataShareExtensionAbility](database/share-data-by-datashareextensionability.md) + - [Sharing Data in Silent Access](database/share-data-by-silent-access.md) - File Management - - MediaLibrary - - [MediaLibrary Development Overview](file-management/medialibrary-overview.md) - - [Media Asset Management](file-management/medialibrary-resource-guidelines.md) - - [File Path Management](file-management/medialibrary-filepath-guidelines.md) - - [Album Management](file-management/medialibrary-album-guidelines.md) - - File Access Framework - - [File Access Framework Overview](file-management/file-access-framework-overview.md) - - [FilePicker Guide](file-management/filepicker-guidelines.md) + - [File Management Overview](file-management/file-management-overview.md) + - Application File + - [Application File Overview](file-management/app-file-overview.md) + - [Application Sandbox Directory](file-management/app-sandbox-directory.md) + - Application File Access and Management + - [Accessing Application Files](file-management/app-file-access.md) + - [Uploading and Downloading Application Files](file-management/app-file-upload-download.md) + - [Obtaining Application and File System Space Statistics](file-management/app-fs-space-statistics.md) + - [Sending Files to an Application Sandbox](file-management/send-file-to-app-sandbox.md) + - [Sharing an Application File](file-management/share-app-file.md) + - User File + - [User File Overview](file-management/user-file-overview.md) + - Selecting and Saving User Files (FilePicker) + - [Selecting User Files](file-management/select-user-file.md) + - [Saving User Files](file-management/save-user-file.md) + - [Developing a FileManager Application (Available Only for System Applications)](file-management/dev-user-file-manager.md) + - [Managing External Storage Devices (Available Only for System Applications)](file-management/manage-external-storage.md) + - Distributed File System + - [Distributed File System Overview](file-management/distributed-fs-overview.md) + - [Setting the Security Level of a Distributed File](file-management/set-security-label.md) + - [Accessing Files Across Devices](file-management/file-access-across-devices.md) - Background Task Management - Background Task - [Background Task Management Overview](task-management/background-task-overview.md) @@ -414,9 +585,13 @@ - [Development of Application Event Logging](dfx/hiappevent-guidelines.md) - [Development of Performance Tracing](dfx/hitracemeter-guidelines.md) - [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md) + - [HiLog Development (Native)](dfx/hilog-guidelines.md) - Error Management - [Development of Error Manager](dfx/errormanager-guidelines.md) - [Development of Application Recovery](dfx/apprecovery-guidelines.md) + - Log Analysis + - [Application Freeze (appfreeze) Log Analysis](dfx/appfreeze-guidelines.md) + - [cppcrash Log Analysis](dfx/cppcrash-guidelines.md) - Internationalization - [Internationalization Overview](internationalization/international-overview.md) - [Internationalization Development (intl)](internationalization/intl-guidelines.md) @@ -441,8 +616,10 @@ - Packing and Unpacking Tools - [Packing Tools](tools/packing-tool.md) - [Unpacking Tools](tools/unpacking-tool.md) - - [Common Event Manager](tools/anm-tool.md) - [Advanced Notification Manager](tools/cem-tool.md) + - [Common Event Manager](tools/anm-tool.md) + - [restool](tools/restool.md) + - [LLDB Usage Guide](tools/lldb-tool.md) - Hands-On Tutorials - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs) @@ -462,6 +639,7 @@ - [Mouse Event](reference/arkui-ts/ts-universal-mouse-key.md) - [Component Area Change Event](reference/arkui-ts/ts-universal-component-area-change-event.md) - [Visible Area Change Event](reference/arkui-ts/ts-universal-component-visible-area-change-event.md) + - [Custom Keyboard Shortcuts](reference/arkui-ts/ts-universal-events-keyboardshortcut.md) - Universal Attributes - [Size](reference/arkui-ts/ts-universal-attributes-size.md) - [Location](reference/arkui-ts/ts-universal-attributes-location.md) @@ -478,7 +656,6 @@ - [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) @@ -492,6 +669,11 @@ - [Hit Test Control](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md) - [Background Blur](reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md) - [restoreId](reference/arkui-ts/ts-universal-attributes-restoreId.md) + - [Foreground Color](reference/arkui-ts/ts-universal-attributes-foreground-color.md) + - [Spherical Effect](reference/arkui-ts/ts-universal-attributes-sphericalEffect.md) + - [Light Up Effect](reference/arkui-ts/ts-universal-attributes-lightUpEffect.md) + - [Pixel Stretch Effect](reference/arkui-ts/ts-universal-attributes-pixelStretchEffect.md) + - [Text Style](reference/arkui-ts/ts-universal-attributes-text-style.md) - Gesture Processing - [Gesture Binding Methods](reference/arkui-ts/ts-gesture-settings.md) - Basic Gestures @@ -503,6 +685,7 @@ - [SwipeGesture](reference/arkui-ts/ts-basic-gestures-swipegesture.md) - [Combined Gestures](reference/arkui-ts/ts-combined-gestures.md) - Basic Components + - [AlphabetIndexer](reference/arkui-ts/ts-container-alphabet-indexer.md) - [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) @@ -514,6 +697,7 @@ - [Gauge](reference/arkui-ts/ts-basic-components-gauge.md) - [Image](reference/arkui-ts/ts-basic-components-image.md) - [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md) + - [ImageSpan](reference/arkui-ts/ts-basic-components-imagespan.md) - [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md) - [Marquee](reference/arkui-ts/ts-basic-components-marquee.md) - [Menu](reference/arkui-ts/ts-basic-components-menu.md) @@ -549,7 +733,6 @@ - [XComponent](reference/arkui-ts/ts-basic-components-xcomponent.md) - Container Components - [AbilityComponent](reference/arkui-ts/ts-container-ability-component.md) - - [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) @@ -613,6 +796,7 @@ - [Time Picker Dialog Box](reference/arkui-ts/ts-methods-timepicker-dialog.md) - [Text Picker Dialog Box](reference/arkui-ts/ts-methods-textpicker-dialog.md) - [Menu](reference/arkui-ts/ts-methods-menu.md) + - [Custom Component Lifecycle](reference/arkui-ts/ts-custom-component-lifecycle.md) - [State Management with Application-level Variables](reference/arkui-ts/ts-state-management.md) - [Pixel Units](reference/arkui-ts/ts-pixel-units.md) - [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md) @@ -722,39 +906,39 @@ - [Data Type Attributes](reference/arkui-js/js-appendix-types.md) - JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite) - Framework Overview - - [File Organization](js-framework-file.md) - - ["js" Tag](js-framework-js-tag.md) - - [app.js](js-framework-js-file.md) + - [File Organization](reference/arkui-js-lite/js-framework-file.md) + - ["js" Tag](reference/arkui-js-lite/js-framework-js-tag.md) + - [app.js](reference/arkui-js-lite/js-framework-js-file.md) - Syntax - - [HML](js-framework-syntax-hml.md) - - [CSS](js-framework-syntax-css.md) - - [JavaScript](js-framework-syntax-js.md) + - [HML](reference/arkui-js-lite/js-framework-syntax-hml.md) + - [CSS](reference/arkui-js-lite/js-framework-syntax-css.md) + - [JavaScript](reference/arkui-js-lite/js-framework-syntax-js.md) - Universal Component Information - - [Universal Events](js-common-events.md) - - [Universal Attributes](js-common-attributes.md) - - [Universal Styles](js-common-styles.md) - - [Animation Styles](js-components-common-animation.md) + - [Universal Events](reference/arkui-js-lite/js-common-events.md) + - [Universal Attributes](reference/arkui-js-lite/js-common-attributes.md) + - [Universal Styles](reference/arkui-js-lite/js-common-styles.md) + - [Animation Styles](reference/arkui-js-lite/js-components-common-animation.md) - Container Components - - [div](js-components-container-div.md) - - [list](js-components-container-list.md) - - [list-item](js-components-container-list-item.md) - - [stack](js-components-container-stack.md) - - [swiper](js-components-container-swiper.md) + - [div](reference/arkui-js-lite/js-components-container-div.md) + - [list](reference/arkui-js-lite/js-components-container-list.md) + - [list-item](reference/arkui-js-lite/js-components-container-list-item.md) + - [stack](reference/arkui-js-lite/js-components-container-stack.md) + - [swiper](reference/arkui-js-lite/js-components-container-swiper.md) - Basic Components - - [chart](js-components-basic-chart.md) - - [image](js-components-basic-image.md) - - [image-animator](js-components-basic-image-animator.md) - - [input](js-components-basic-input.md) - - [marquee](js-components-basic-marquee.md) - - [picker-view](js-components-basic-picker-view.md) - - [progress](js-components-basic-progress.md) - - [qrcode](js-components-basic-qrcode.md) - - [slider](js-components-basic-slider.md) - - [switch](js-components-basic-switch.md) - - [text](js-components-basic-text.md) + - [chart](reference/arkui-js-lite/js-components-basic-chart.md) + - [image](reference/arkui-js-lite/js-components-basic-image.md) + - [image-animator](reference/arkui-js-lite/js-components-basic-image-animator.md) + - [input](reference/arkui-js-lite/js-components-basic-input.md) + - [marquee](reference/arkui-js-lite/js-components-basic-marquee.md) + - [picker-view](reference/arkui-js-lite/js-components-basic-picker-view.md) + - [progress](reference/arkui-js-lite/js-components-basic-progress.md) + - [qrcode](reference/arkui-js-lite/js-components-basic-qrcode.md) + - [slider](reference/arkui-js-lite/js-components-basic-slider.md) + - [switch](reference/arkui-js-lite/js-components-basic-switch.md) + - [text](reference/arkui-js-lite/js-components-basic-text.md) - Canvas Components - - [canvas](js-components-canvas-canvas.md) - - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) + - [canvas](reference/arkui-js-lite/js-components-canvas-canvas.md) + - [CanvasRenderingContext2D](reference/arkui-js-lite/js-components-canvas-canvasrenderingcontext2d.md) - JS Service Widget UI Components - JS Service Widget UI Framework - [File Organization](reference/js-service-widget-ui/js-service-widget-file.md) @@ -812,8 +996,6 @@ - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](reference/apis/js-apis-app-form-formExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](reference/apis/js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](reference/apis/js-apis-application-staticSubscriberExtensionAbility.md) - - Stage Model (To Be Deprecated Soon) - - [@ohos.application.EnvironmentCallback (EnvironmentCallback)](reference/apis/js-apis-application-environmentCallback.md) - FA Model - [@ohos.ability.ability (Ability)](reference/apis/js-apis-ability-ability.md) - [@ohos.ability.featureAbility (FeatureAbility)](reference/apis/js-apis-ability-featureAbility.md) @@ -825,16 +1007,20 @@ - [@ohos.app.ability.appRecovery (appRecovery)](reference/apis/js-apis-app-ability-appRecovery.md) - [@ohos.app.ability.Configuration (Configuration)](reference/apis/js-apis-app-ability-configuration.md) - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](reference/apis/js-apis-app-ability-configurationConstant.md) + - [@ohos.app.ability.dataUriUtils (DataUriUtils)](reference/apis/js-apis-app-ability-dataUriUtils.md) + - [@ohos.app.ability.dialogRequest (dialogRequest)](reference/apis/js-apis-app-ability-dialogRequest.md) - [@ohos.app.ability.errorManager (ErrorManager)](reference/apis/js-apis-app-ability-errorManager.md) - [@ohos.app.ability.missionManager (missionManager)](reference/apis/js-apis-app-ability-missionManager.md) - [@ohos.app.ability.quickFixManager (quickFixManager)](reference/apis/js-apis-app-ability-quickFixManager.md) - [@ohos.app.ability.Want (Want)](reference/apis/js-apis-app-ability-want.md) - [@ohos.app.ability.wantAgent (WantAgent)](reference/apis/js-apis-app-ability-wantAgent.md) - [@ohos.app.ability.wantConstant (wantConstant)](reference/apis/js-apis-app-ability-wantConstant.md) + - [@ohos.app.businessAbilityRouter (Business Ability Router)](reference/apis/js-apis-businessAbilityRouter.md) - [@ohos.app.form.formBindingData (formBindingData)](reference/apis/js-apis-app-form-formBindingData.md) - [@ohos.app.form.formHost (FormHost)](reference/apis/js-apis-app-form-formHost.md) - [@ohos.app.form.formInfo (FormInfo)](reference/apis/js-apis-app-form-formInfo.md) - [@ohos.app.form.formProvider (FormProvider)](reference/apis/js-apis-app-form-formProvider.md) + - [@ohos.application.uriPermissionManager (URI Permission Management)](reference/apis/js-apis-uripermissionmanager.md) - Both Models (To Be Deprecated Soon) - [@ohos.ability.dataUriUtils (DataUriUtils)](reference/apis/js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode (ErrorCode)](reference/apis/js-apis-ability-errorCode.md) @@ -906,10 +1092,12 @@ - [continuationExtraParams](reference/apis/js-apis-continuation-continuationExtraParams.md) - [continuationResult](reference/apis/js-apis-continuation-continuationResult.md) - Common Event and Notification + - [System Common Events](reference/apis/commonEventManager-definitions.md) - [@ohos.commonEventManager (Common Event) (Recommended)](reference/apis/js-apis-commonEventManager.md) - [@ohos.events.emitter (Emitter)](reference/apis/js-apis-emitter.md) - [@ohos.notificationManager (NotificationManager) (Recommended)](reference/apis/js-apis-notificationManager.md) - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](reference/apis/js-apis-notificationSubscribe.md) + - [System Common Events (To Be Deprecated Soon)](reference/apis/commonEvent-definitions.md) - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](reference/apis/js-apis-commonEvent.md) - [@ohos.notification (Notification) (To Be Deprecated Soon)](reference/apis/js-apis-notification.md) - application @@ -928,6 +1116,10 @@ - [NotificationSlot](reference/apis/js-apis-inner-notification-notificationSlot.md) - [NotificationTemplate](reference/apis/js-apis-inner-notification-notificationTemplate.md) - [NotificationUserInput](reference/apis/js-apis-inner-notification-notificationUserInput.md) + - Common Events + - [Common Events of the Bundle Management Subsystem](reference/apis/common_event/commonEvent-bundleManager.md) + - [Common Events of the Notification Service](reference/apis/common_event/commonEvent-ans.md) + - [Common Events of the Telephony Subsystem](reference/apis/common_event/commonEvent-telephony.md) - Bundle Management - [@ohos.bundle.appControl(appControl)](reference/apis/js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager)](reference/apis/js-apis-bundleManager.md) @@ -937,29 +1129,38 @@ - [@ohos.bundle.freeInstall (freeInstall)](reference/apis/js-apis-freeInstall.md) - [@ohos.bundle.installer (installer)](reference/apis/js-apis-installer.md) - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](reference/apis/js-apis-launcherBundleManager.md) + - [@ohos.bundle.overlay (overlay)](reference/apis/js-apis-overlay.md) - [@ohos.zlib (Zip)](reference/apis/js-apis-zlib.md) - bundleManager - [abilityInfo](reference/apis/js-apis-bundleManager-abilityInfo.md) - [applicationInfo](reference/apis/js-apis-bundleManager-applicationInfo.md) + - [AppProvisionInfo](reference/apis/js-apis-bundleManager-AppProvisionInfo.md) - [bundleInfo](reference/apis/js-apis-bundleManager-bundleInfo.md) - [BundlePackInfo](reference/apis/js-apis-bundleManager-BundlePackInfo.md) + - [BusinessAbilityInfo](reference/apis/js-apis-bundleManager-businessAbilityInfo.md) - [dispatchInfo](reference/apis/js-apis-bundleManager-dispatchInfo.md) - [elementName](reference/apis/js-apis-bundleManager-elementName.md) - [extensionAbilityInfo](reference/apis/js-apis-bundleManager-extensionAbilityInfo.md) - [hapModuleInfo](reference/apis/js-apis-bundleManager-hapModuleInfo.md) - [launcherAbilityInfo](reference/apis/js-apis-bundleManager-launcherAbilityInfo.md) - [metadata](reference/apis/js-apis-bundleManager-metadata.md) + - [OverlayModuleInfo](reference/apis/js-apis-bundleManager-overlayModuleInfo.md) - [permissionDef](reference/apis/js-apis-bundleManager-permissionDef.md) - [remoteAbilityInfo](reference/apis/js-apis-bundleManager-remoteAbilityInfo.md) + - [SharedBundleInfo](reference/apis/js-apis-bundleManager-sharedBundleInfo.md) - [shortcutInfo](reference/apis/js-apis-bundleManager-shortcutInfo.md) - UI Page - [@ohos.animator (Animator)](reference/apis/js-apis-animator.md) + - [@ohos.arkui.componentSnapshot (Component Snapshot)](reference/apis/js-apis-arkui-componentSnapshot.md) + - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](reference/apis/js-apis-arkui-drawableDescriptor.md) - [@ohos.curves (Interpolation Calculation)](reference/apis/js-apis-curve.md) - [@ohos.matrix4 (Matrix Transformation)](reference/apis/js-apis-matrix4.md) - [@ohos.mediaquery (Media Query)](reference/apis/js-apis-mediaquery.md) - [@ohos.pluginComponent (PluginComponentManager)](reference/apis/js-apis-plugincomponent.md) - [@ohos.promptAction (Prompt)](reference/apis/js-apis-promptAction.md) - [@ohos.router (Page Routing)](reference/apis/js-apis-router.md) + - [@ohos.measure (Text Measurement)](reference/apis/js-apis-measure.md) + - [@ohos.uiAppearance (UI Appearance)](reference/apis/js-apis-uiappearance.md) - Graphics - [@ohos.animation.windowAnimationManager (Window Animation Management)](reference/apis/js-apis-windowAnimationManager.md) - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](reference/apis/js-apis-application-windowExtensionAbility.md) @@ -989,6 +1190,8 @@ - [@ohos.resourceschedule.workScheduler (Work Scheduler)](reference/apis/js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) + - application + - [WorkSchedulerExtensionContext](reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md) - Security - [@ohos.abilityAccessCtrl (Ability Access Control)](reference/apis/js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (Privacy Management)](reference/apis/js-apis-privacyManager.md) @@ -997,7 +1200,6 @@ - [@ohos.security.huks (HUKS)](reference/apis/js-apis-huks.md) - [@ohos.userIAM.faceAuth (Facial Authentication)](reference/apis/js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (User Authentication)](reference/apis/js-apis-useriam-userauth.md) - - [@system.cipher (Cipher Algorithm)](reference/apis/js-apis-system-cipher.md) - security - [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md) - Data Management @@ -1010,20 +1212,22 @@ - [@ohos.data.preferences (Preferences)](reference/apis/js-apis-data-preferences.md) - [@ohos.data.relationalStore (RDB Store)](reference/apis/js-apis-data-relationalStore.md) - [@ohos.data.ValuesBucket](reference/apis/js-apis-data-valuesBucket.md) - - data/rdb - - [resultSet (Result Set)](reference/apis/js-apis-data-resultset.md) - File Management + - [@ohos.file.backup (Backup and Restoration)](reference/apis/js-apis-file-backup.md) + - [@ohos.file.cloudSyncManager (Device-Cloud Synchronization Management)](reference/apis/js-apis-file-cloudsyncmanager.md) - [@ohos.file.environment (Directory Environment Capability)](reference/apis/js-apis-file-environment.md) - [@ohos.file.fileAccess (User File Access and Management)](reference/apis/js-apis-fileAccess.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](reference/apis/js-apis-fileExtensionInfo.md) + - [@ohos.file.fileuri (File URI)](reference/apis/js-apis-file-fileuri.md) - [@ohos.file.fs (File Management)](reference/apis/js-apis-file-fs.md) - [@ohos.file.hash (File Hash Processing)](reference/apis/js-apis-file-hash.md) + - [@ohos.file.picker (File Picker)](reference/apis/js-apis-file-picker.md) - [@ohos.file.securityLabel (Data Label)](reference/apis/js-apis-file-securityLabel.md) - [@ohos.file.statvfs (File System Space Statistics)](reference/apis/js-apis-file-statvfs.md) - - [@ohos.storageStatistics (Application Storage Statistics)](reference/apis/js-apis-file-storage-statistics.md) - - [@ohos.volumeManager (Volume Management)](reference/apis/js-apis-file-volumemanager.md) + - [@ohos.file.storageStatistics (Application Storage Statistics)](reference/apis/js-apis-file-storage-statistics.md) + - [@ohos.file.volumeManager (Volume Management)](reference/apis/js-apis-file-volumemanager.md) - [@ohos.filemanagement.userFileManager (User Data Management)](reference/apis/js-apis-userFileManager.md) - - [@ohos.multimedia.medialibrary (Media Library Management)](reference/apis/js-apis-medialibrary.md) + - [@ohos.fileShare (File Sharing)](reference/apis/js-apis-fileShare.md) - Telephony Service - [@ohos.contact (Contacts)](reference/apis/js-apis-contact.md) - [@ohos.telephony.call (Call)](reference/apis/js-apis-call.md) @@ -1036,12 +1240,14 @@ - [@ohos.net.connection (Network Connection Management)](reference/apis/js-apis-net-connection.md) - [@ohos.net.ethernet (Ethernet Connection Management)](reference/apis/js-apis-net-ethernet.md) - [@ohos.net.http (Data Request)](reference/apis/js-apis-http.md) + - [@ohos.net.mdns (mDNS Management)](reference/apis/js-apis-net-mdns.md) - [@ohos.net.sharing (Network Sharing)](reference/apis/js-apis-net-sharing.md) - [@ohos.net.socket (Socket Connection)](reference/apis/js-apis-socket.md) - [@ohos.net.webSocket (WebSocket Connection)](reference/apis/js-apis-webSocket.md) - [@ohos.request (Upload and Download)](reference/apis/js-apis-request.md) - Connectivity - [@ohos.bluetooth (Bluetooth)](reference/apis/js-apis-bluetooth.md) + - [@ohos.bluetoothManager (Bluetooth) (Recommended)](reference/apis/js-apis-bluetoothManager.md) - [@ohos.connectedTag (Active Tags)](reference/apis/js-apis-connectedTag.md) - [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](reference/apis/js-apis-cardEmulation.md) - [@ohos.nfc.controller (Standard NFC)](reference/apis/js-apis-nfcController.md) @@ -1087,6 +1293,7 @@ - [@ohos.batteryInfo (Battery Information)](reference/apis/js-apis-battery-info.md) - [@ohos.batteryStatistics (Battery Statistics)](reference/apis/js-apis-batteryStatistics.md) - [@ohos.brightness (Screen Brightness)](reference/apis/js-apis-brightness.md) + - [@ohos.charger (Charging Type)](reference/apis/js-apis-charger.md) - [@ohos.deviceInfo (Device Information)](reference/apis/js-apis-device-info.md) - [@ohos.distributedHardware.deviceManager (Device Management)](reference/apis/js-apis-device-manager.md) - [@ohos.geoLocationManager (Geolocation Manager)](reference/apis/js-apis-geoLocationManager.md) @@ -1118,9 +1325,15 @@ - [@ohos.account.osAccount (OS Account Management)](reference/apis/js-apis-osAccount.md) - Customization - [@ohos.configPolicy (Configuration Policy)](reference/apis/js-apis-configPolicy.md) - - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.accountManager (Account Management)](reference/apis/js-apis-enterprise-accountManager.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](reference/apis/js-apis-enterprise-adminManager.md) + - [@ohos.enterprise.bundleManager (Bundle Management)](reference/apis/js-apis-enterprise-bundleManager.md) - [@ohos.enterprise.dateTimeManager (System Time Management)](reference/apis/js-apis-enterprise-dateTimeManager.md) + - [@ohos.enterprise.deviceControl (Device Control Management)](reference/apis/js-apis-enterprise-deviceControl.md) + - [@ohos.enterprise.deviceInfo (Device Information Management)](reference/apis/js-apis-enterprise-deviceInfo.md) + - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.networkManager (Network Management)](reference/apis/js-apis-enterprise-networkManager.md) + - [@ohos.enterprise.wifiManager (Wi-Fi Management)](reference/apis/js-apis-enterprise-wifiManager.md) - Language Base Class Library - [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md) - [@ohos.convertxml (XML-to-JavaScript Conversion)](reference/apis/js-apis-convertxml.md) @@ -1162,17 +1375,18 @@ - [@ohos.fileio (File Management)](reference/apis/js-apis-fileio.md) - [@ohos.geolocation (Geolocation)](reference/apis/js-apis-geolocation.md) - [@ohos.hiAppEvent (Application Event Logging)](reference/apis/js-apis-hiappevent.md) + - [@ohos.multimedia.medialibrary (Media Library Management)](reference/apis/js-apis-medialibrary.md) - [@ohos.prompt (Prompt)](reference/apis/js-apis-prompt.md) - [@ohos.reminderAgent (Reminder Agent)](reference/apis/js-apis-reminderAgent.md) - [@ohos.statfs (statfs)](reference/apis/js-apis-statfs.md) - [@ohos.systemParameter (System Parameter)](reference/apis/js-apis-system-parameter.md) - [@ohos.systemTime (System Time and Time Zone)](reference/apis/js-apis-system-time.md) - [@ohos.usb (USB Management)](reference/apis/js-apis-usb-deprecated.md) - - [@ohos.usbV9 (USB Management)](reference/apis/js-apis-usb.md) - [@system.app (Application Context)](reference/apis/js-apis-system-app.md) - [@system.battery (Battery Information)](reference/apis/js-apis-system-battery.md) - [@system.bluetooth (Bluetooth)](reference/apis/js-apis-system-bluetooth.md) - [@system.brightness (Screen Brightness)](reference/apis/js-apis-system-brightness.md) + - [@system.cipher (Cipher Algorithm)](reference/apis/js-apis-system-cipher.md) - [@system.configuration (Application Configuration)](reference/apis/js-apis-system-configuration.md) - [@system.device (Device Information)](reference/apis/js-apis-system-device.md) - [@system.fetch (Data Request)](reference/apis/js-apis-system-fetch.md) @@ -1202,6 +1416,8 @@ - [PermissionDef](reference/apis/js-apis-bundle-PermissionDef.md) - [remoteAbilityInfo](reference/apis/js-apis-bundle-remoteAbilityInfo.md) - [shortcutInfo](reference/apis/js-apis-bundle-ShortcutInfo.md) + - data/rdb + - [resultSet](reference/apis/js-apis-data-resultset.md) - Error Codes - [Universal Error Codes](reference/errorcodes/errorcode-universal.md) - Ability Framework @@ -1253,7 +1469,15 @@ - [Telephony Error Codes](reference/errorcodes/errorcode-telephony.md) - Network Management - [Upload and Download Error Codes](reference/errorcodes/errorcode-request.md) + - [HTTP Error Codes](reference/errorcodes/errorcode-net-http.md) + - [Socket Error Codes](reference/errorcodes/errorcode-net-socket.md) + - [Network Connection Management Error Codes](reference/errorcodes/errorcode-net-connection.md) + - [Ethernet Connection Error Codes](reference/errorcodes/errorcode-net-ethernet.md) + - [Network Sharing Error Codes](reference/errorcodes/errorcode-net-sharing.md) + - [mDNS Error Codes](reference/errorcodes/errorcode-net-mdns.md) - Connectivity + - [Bluetooth Error Codes](reference/errorcodes/errorcode-bluetoothManager.md) + - [Wi-Fi Error Codes](reference/errorcodes/errorcode-wifi.md) - [NFC Error Codes](reference/errorcodes/errorcode-nfc.md) - [RPC Error Codes](reference/errorcodes/errorcode-rpc.md) - Basic Features @@ -1264,6 +1488,7 @@ - [HiDebug Error Codes](reference/errorcodes/errorcode-hiviewdfx-hidebug.md) - [Input Method Framework Error Codes](reference/errorcodes/errorcode-inputmethod-framework.md) - [Pasteboard Error Codes](reference/errorcodes/errorcode-pasteboard.md) + - [Screen Lock Management Error Codes](reference/errorcodes/errorcode-screenlock.md) - [Time and Time Zone Service Error Codes](reference/errorcodes/errorcode-time.md) - [Webview Error Codes](reference/errorcodes/errorcode-webview.md) - Account Management @@ -1293,10 +1518,7 @@ - [Native XComponent](reference/native-apis/_o_h___native_x_component.md) - [HiLog](reference/native-apis/_hi_log.md) - [NativeWindow](reference/native-apis/_native_window.md) - - [OH_NativeBuffer](reference/native-apis/_o_h___native_buffer.md) - [Drawing](reference/native-apis/_drawing.md) - - [OH_NativeImage](reference/native-apis/_o_h___native_image.md) - - [NativeVsync](reference/native-apis/_native_vsync.md) - [Image](reference/native-apis/image.md) - [Rawfile](reference/native-apis/rawfile.md) - [MindSpore](reference/native-apis/_mind_spore.md) @@ -1324,10 +1546,7 @@ - [external_window.h](reference/native-apis/external__window_8h.md) - [image_pixel_map_napi.h](reference/native-apis/image__pixel__map__napi_8h.md) - [log.h](reference/native-apis/log_8h.md) - - [native_buffer.h](reference/native-apis/native__buffer_8h.md) - - [native_image.h](reference/native-apis/native__image_8h.md) - [native_interface_xcomponent.h](reference/native-apis/native__interface__xcomponent_8h.md) - - [native_vsync.h](reference/native-apis/native__vsync_8h.md) - [raw_dir.h](reference/native-apis/raw__dir_8h.md) - [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md) - [raw_file.h](reference/native-apis/raw__file_8h.md) @@ -1353,7 +1572,6 @@ - [native_huks_type.h](reference/native-apis/native__huks__type_8h.md) - Structs - [OH_Drawing_BitmapFormat](reference/native-apis/_o_h___drawing___bitmap_format.md) - - [OH_NativeBuffer_Config](reference/native-apis/_o_h___native_buffer___config.md) - [OH_NativeXComponent_Callback](reference/native-apis/_o_h___native_x_component___callback.md) - [OH_NativeXComponent_MouseEvent](reference/native-apis/_o_h___native_x_component___mouse_event.md) - [OH_NativeXComponent_MouseEvent_Callback](reference/native-apis/_o_h___native_x_component___mouse_event___callback.md) @@ -1387,33 +1605,39 @@ - [OH_Huks_ParamSet](reference/native-apis/_o_h___huks___param_set.md) - [OH_Huks_PubKeyInfo](reference/native-apis/_o_h___huks___pub_key_info.md) - [OH_Huks_Result](reference/native-apis/_o_h___huks___result.md) - - Standard Libraries Supported by Native APIs - - [Node_API](reference/native-lib/third_party_napi/napi.md) - - [libuv](reference/native-lib/third_party_libuv/libuv.md) - - [Native Standard Libraries Supported by Openharmony](reference/native-lib/third_party_libc/musl.md) - - Appendix - - [Native API Symbols Not Exported](reference/native-lib/third_party_libc/musl-peculiar-symbol.md) - - [EGL Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/egl-symbol.md) - - [OpenGL ES 3.0 Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/openglesv3-symbol.md) + - Standard Libraries Supported by Native APIs + - [Node_API](reference/native-lib/third_party_napi/napi.md) + - [libuv](reference/native-lib/third_party_libuv/libuv.md) + - [Native Standard Libraries Supported by Openharmony](reference/native-lib/third_party_libc/musl.md) + - Appendix + - [Native API Symbols Not Exported](reference/native-lib/third_party_libc/musl-peculiar-symbol.md) + - [Native API Symbols That May Fail to Be Invoked Due to Permission Control](reference/native-lib/third_party_libc/musl-permission-control-symbol.md) + - [EGL Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/egl-symbol.md) + - [OpenGL ES 3.0 Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/openglesv3-symbol.md) + - [OpenSL ES Interfaces Supported by Native APIs](reference/native-lib/third_party_opensles/opensles.md) - FAQs - - [Guide to Switching to Full SDK](quick-start/full-sdk-switch-guide.md) - - [Programming Languages](faqs/faqs-language.md) + - [Full SDK Compilation Guide](faqs/full-sdk-compile-guide.md) + - [Guide to Switching to Full SDK](faqs/full-sdk-switch-guide.md) - [Ability Framework Development](faqs/faqs-ability.md) - - [Bundle Management Development](faqs/faqs-bundle.md) - - [ArkUI (ArkTS) Development](faqs/faqs-ui-ets.md) - - [ArkUI Web Component (ArkTS) Development](faqs/faqs-web-arkts.md) - - [ArkUI (JavaScript) Development](faqs/faqs-ui-js.md) + - ArkUI Framework Development (ArkTS) + - [ArkUI Development (ArkTS Syntax)](faqs/faqs-arkui-arkts.md) + - [Web Development](faqs/faqs-arkui-web.md) + - [Bundle Management Development](faqs/faqs-bundle-management.md) + - [Resource Management Development](faqs/faqs-globalization.md) - [Common Event and Notification Development](faqs/faqs-event-notification.md) - [Graphics and Image Development](faqs/faqs-graphics.md) + - [Window Management Development](faqs/faqs-window-manager.md) + - [Multimedia Development](faqs/faqs-multimedia.md) + - [Basic Security Capability Development](faqs/faqs-security.md) + - [Ability Access Control Development](faqs/faqs-ability-access-control.md) + - [Data Management Development](faqs/faqs-distributed-data-management.md) - [File Management Development](faqs/faqs-file-management.md) - - [Media Development](faqs/faqs-media.md) - - [Network and Connection Development](faqs/faqs-connectivity.md) - - [Device Management Development](faqs/faqs-data-management.md) - - [Device Management Development](faqs/faqs-device-management.md) + - [Network Management Development](faqs/faqs-network-management.md) - [DFX Development](faqs/faqs-dfx.md) - - [Intl Development](faqs/faqs-international.md) - - [Native API Usage](faqs/faqs-native.md) - - [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-party-library.md) - - [IDE Usage](faqs/faqs-ide.md) - - [Development Board](faqs/faqs-development-board.md) - + - [Pan-Sensor Development](faqs/faqs-sensor.md) + - [Startup Development](faqs/faqs-startup.md) + - [Distributed Device Development](faqs/faqs-distributed-device-profile.md) + - [SDK Usage](faqs/faqs-sdk.md) + - [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-fourth-party-library.md) + + \ No newline at end of file diff --git a/en/contribute/OpenHarmony-Application-Typescript-JavaScript-coding-guide.md b/en/contribute/OpenHarmony-Application-Typescript-JavaScript-coding-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..bced977f51134c7f2ef05e659f219b38961c8e5d --- /dev/null +++ b/en/contribute/OpenHarmony-Application-Typescript-JavaScript-coding-guide.md @@ -0,0 +1,1016 @@ +# TypeScript and JavaScript Coding Style Guide + +# Overview + +## Purpose + +This guide is applicable to the scenario where TypeScript and JavaScript are used during OpenHarmony application development. + +Based on the technical features of language engines and OpenHarmony, as well as industry standards and practices, this guide provides coding guide for improving code standardization, security, and performance. + +## Source + +This guide is developed based on the *JavaScript Coding Style Guide* [1]. It integrates the technical features of OpenHarmony without violating industry rules, including ESLint and TSC configuration. + +The correct and incorrect examples, marked with **@typescript-eslint**, in ESLint rules come from ESLint Rules [2]. + +## Document Structure + +- [OpenHarmony Application Environment Restrictions](#openharmony-application-environment-restrictions) + + All the restrictions provided in this section are raised for security purposes and therefore are mandatory. + +- Programming language features: [Declaration and Initialization](#declaration-and-initialization), [Data Types](#data-types), [Operation and Expressions](#operation-and-expressions), [Functions](#functions), [Classes and Objects](#classes-and-objects), and [Exceptions](#exceptions), [Async Functions](#async-functions), and [Types](#types). + +## Conventions + +**Rule**: a convention that must be complied with + +**Recommendation**: a convention that must be taken into consideration + +It is necessary to understand the reason for each rule or recommendation and try to comply with them. + +# OpenHarmony Application Environment Restrictions + +## Use Strict Mode + +**[Category] Rule** + +**[Description]** + +Strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting out of sloppy mode. + +1. Strict mode eliminates some JavaScript silent errors by throwing errors. +1. Strict mode fixes defects that make it difficult for JavaScript engines to perform optimizations. Sometimes, the same code can run faster in strict mode than in non-strict mode. +1. Strict mode prohibits some syntax that may be defined in future versions of ECMAScript. + +**Note: Currently, only TypeScript or JavaScript code in strict mode is supported on OpenHarmony ArkCompiler.** + +## Do Not Use eval() + +**[Category] Rule** + +**[Description]** + +Using **eval()** causes code disorder and poor readability. + +**[Incorrect Example]** + +```javascript +console.log (eval ({ a:2 })); // Output [object Object]. +console.log(eval('"a" + 2')); // Output 'a2'. +console.log(eval('{a: 2}')); // Output 2. +console.log(eval('let value = 1 + 1;'); // Output undefined. +``` + +## Do Not Use with() {} + +**[Category] Rule** + +**[Description]** + +Using **with()** makes the code semantically unclear because the object of **with()** may conflict with local variables, changing the original semantics. + +**[Incorrect Example]** + +```javascript +const foo = { x: 5 }; +with (foo) { + let x = 3; + console.log(x); // x = 3 +} +console.log(foo.x); // x = 3 +``` + +## Do Not Dynamically Create Functions + +**[Category] Rule** + +**[Description]** + +A function can be defined in three ways: declaration, constructor, and expression. No matter which means is used, the function created is an instance of the **Function** object and inherits all default or custom methods and attributes of the **Function** object. Defining a function by using a constructor is similar to the using of **eval()**. The constructor accepts any string as the function body, causing security vulnerabilities. + +**[Incorrect Example]** + +```javascript +let add = new Function('a','b','return a + b'); +// The function constructor can have only one parameter, which can be any string. +let dd = new Function('alert("hello")'); +``` + +**[Correct Example]** + +```javascript +// Function declaration. +function add(a,b){ + return a+b; +} +// Function expression. +let add = function(a,b){ + return a+b; +} +``` + +# Declaration and Initialization + +## Use const or let Instead of var to Declare Variables + +**[Category] Rule** + +**[Description]** + +ECMAScript 6 allows the use of the **let** and **const** keywords to declare variables in the block scope instead of the function scope. The block scope is commonly used in many programming languages. It is helpful in preventing errors. Use **const** to define read-only variables, and use **let** to define other variables. + +**[Incorrect Example]** + +```javascript +var number = 1; +var count = 1; +if (isOK) { + count += 1; +} +``` + +**[Correct Example]** + +```javascript +const number = 1; +let count = 1; +if (isOK) { + count += 1; +} +``` + +# Data Types + +## Do Not Omit 0s Before and After the Decimal Point of a Floating-Point Number + +**[Category] Rule** + +**[Description]** + +In JavaScript, a floating-point number must contain a decimal point, but no digit is required before or after the decimal point. This makes it difficult to distinguish between the decimal point and the dot operator. For this reason, you must use a digit before and after the decimal point for a floating-point number in OpenHarmony code. + +**[Incorrect Example]** + +```javascript +const num = .5; +const num = 2.; +const num = -.7; +``` + +**[Correct Example]** + +```javascript +const num = 0.5; +const num = 2.0; +const num = -0.7; +``` + +## Use isNaN() to Check Whether a Variable Is NaN + +**[Category] Rule** + +**[Description]** + +In JavaScript, NaN is a particular value of a numeric data type. It represents a non-numeric value in the double-precision 64-bit format, as defined in the IEEE floating-point standard. +NaN is unique in JavaScript because it is not equal to any value, including itself. Therefore, the result of comparison with NaN is confusing, as the values of **NaN !== NaN** and **NaN != NaN** are both **true**. +Therefore, you must use **Number.isNaN()** or the global **isNaN()** function to check whether a variable is NaN. + +**[Incorrect Example]** + +```javascript +if (foo == NaN) { + // ... +} +if (foo != NaN) { + // ... +} +``` + +**[Correct Example]** + +```javascript +if (isNaN(foo)) { + // ... +} +if (!isNaN(foo)) { + // ... +} +``` + +## Do Not Use == or === to Check Whether Floating-Point Numbers Are Equal + +**[Category] Rule** + +**[Description]** + +Due to the precision problem, mathematically equal numbers may not be equal in floating-point arithmetic. Therefore, the equality operators **==** and **===** cannot be used to check whether floating-point numbers are equal. + +**[Incorrect Example]** + +```javascript +0.1 + 0.2 == 0.3; // false +0.1 + 0.2 === 0.3; // false +``` + +**[Correct Example]** + +```javascript +const EPSILON = 1e-6; +const num1 = 0.1; +const num2 = 0.2; +const sum = 0.3; +if(Math.abs(num1 + num2 - sum) < EPSILON) { + ... +} +``` + +## Do Not Define or Use Non-numeric Attributes (Except Length) for Arrays + +**[Category] Rule** + +**[Description]** + +In JavaScript, an array is an object, which can be added with attributes. To facilitate processing and avoid errors, use an array to store only a group of ordered data, that is, data with continuous indexes. If attributes must be added, use **Map** or **Object** instead. + +**[Incorrect Example]** + +```javascript +const myHash = []; +myHash['key1'] = 'val1'; +myHash['key2'] = 'val2'; +myHash[0] = '222'; +for (const key in myHash) { + // The value of key is 0, key1, and key2. + console.log(key); +} +console.log(myHash.length); // The array length is 1. +``` + +**[Correct Example]** + +Use Map and Object for non-numeric attributes. + +```javascript +const map = new Map(); +map.set('key1', 'val1'); +map.set('key2', 'val2'); +for(const [key, value] of map) { + console.log('Attribute:' + key +', value: '+ value); +} +``` + +## Preferentially Use Array Object Methods for Array Traversal + +**[Category] Rule** + +**[Description]** + +To traverse an array, preferentially use the methods provided by **Array**, such as **forEach()**, **map()**, **every()**, **filter()**, **find()**, **findIndex()**, **reduce()**, and **some()**. +Do not use **for in** to traverse an array. + +**[Incorrect Example]** + +```javascript +const numbers = [1, 2, 3, 4, 5]; +let sum = 0; +// Use for in to traverse the array. +for (const num in numbers) { + console.log(num); + sum += num; +} +// Use for to traverse an existing array to generate a new array. +const increasedByOne = []; +for (let i = 0; i < numbers.length; i++) { + increasedByOne.push(numbers[i] + 1); +} +``` + +**[Correct Example]** + +```javascript +const numbers = [1, 2, 3, 4, 5]; +// Use for of to traverse the array and obtain the sum. +let sum = 0; +for (const num of numbers) { + sum += num; +} +// Use forEach to traverse the array and obtain the sum. +let sum = 0; +numbers.forEach(num => sum += num); +// Better: Use the reduce method to obtain the sum. +const sum = numbers.reduce((total, num) => total + num, 0); +// Use forEach to traverse an existing array to generate a new array. +const increasedByOne = []; +numbers.forEach(num => increasedByOne.push(num + 1)); +// Better: Use the map method. +const increasedByOne = numbers.map(num => num + 1); +``` + +# Operation and Expressions + +## Use === and !==, Instead of == or !=, to Check Whether the Operands Are Equal + +**[Category] Rule** + +**[Description]** + +In JavaScript, type conversion is automatically performed when the **==** operator is used for equality judgment. For example, the values of **[] == false**, **[] == ![]**, and **3 == '03'** are **true**. For higher efficiency, use **===** in comparison when the type is determined. + +**[Incorrect Example]** + +```javascript +age == bee +foo == true +bananas != 1 +value == undefined +typeof foo == 'undefined' +'hello' != 'world' +0 == 0 +true == true +``` + +**[Correct Example]** + +```javascript +age === bee +foo === true +bananas !== 1 +value === undefined +typeof foo === 'undefined' +'hello' !== 'world' +0 === 0 +true === true +``` + +**[Exceptions]** + +```javascript +// Use the following to determine whether an object is null: +obj == null +obj != null +``` + +## Do Not Assign Values in Control Conditional Expressions + +**[Category] Rule** + +**[Description]** + +Control conditional expressions are usually used in conditional statements such as **if**, **while**, **for**, and **?:**. +Assigning values in this type of expression often leads to unexpected behavior and poor code readability. + +**[Incorrect Example]** + +```javascript +// It is difficult to understand the value assignment in the control conditional expression. +if (isFoo = false) { + ... +} +``` + +**[Correct Example]** + +```javascript +const isFoo = someBoolean; // Assign a value above and directly use it in the if statement. +if (isFoo) { + ... +} +``` + +# Functions + +## Use the Same Return Statement + +**[Category] Rule** + +**[Description]** + +Unlike statically typed languages that force a function to return a value of a specified type, JavaScript allows different code paths in a function to return different types of values. + +JavaScript returns **undefined** in the following cases: + +1. The **return** statement is not executed before the exit. +1. The **return** statement is executed, but no value is explicitly assigned. +1. The **return undefined** statement is executed. +1. The **return void** statement is executed, followed by an expression (for example, a function call). +1. The **return** statement is executed, followed by another expression equivalent to **undefined**. + +In a function (especially in a larger function), if any code path explicitly returns a value but the other code paths do not explicitly return a value, this may be a coding error. Therefore, use the same **return** statement in a function. + +**[Incorrect Example]** + +```javascript +function doSomething(condition) { + if (condition) { + ... + return true; + } else { + ... + return; + } +} +function doSomething(condition) { + if (condition) { + ... + return true; + } +} +``` + +**[Correct Example]** + +```javascript +// Ensure that all paths return values in the same way. +function doSomething(condition) { + if (condition) { + ... + return true; + } else { + ... + return false; + } +} + +function doSomething(condition) { + if (condition) { + ... + return true; + } + ... + return false; +} +``` + +## Use rest Instead of arguments + +**[Category] Rule** + +**[Description]** + +The **rest** parameter is an array, and all array methods, such as **sort**, **map**, **forEach**, and **pop**, can be directly used on it. **arguments** is a class array. Therefore, use the **rest** syntax instead of **arguments**. In addition, place the **rest** parameter as the last parameter in the list. + +**[Incorrect Example]** + +```javascript +function concatenateAll() { + // arguments is a class array, and the join method can be used only after arguments is converted to a real array. + const args = Array.prototype.slice.call(arguments); + return args.join(''); +} +``` + +**[Correct Example]** + +```javascript +function concatenateAll(...args) { + return args.join(''); +} +``` + +## Do Not Assign this to a Variable; Use this in a Scope + +**[Category] Rule** + +**[Description]** + +Arrow functions provide a simpler syntax. **this** in an arrow function points to the object when it is defined. Assigning **this** to a variable is confusing. + +**[Incorrect Example]** + +```javascript +function foo() { + const self = this; + return function() { + console.log(self); + }; +} +``` + +**[Correct Example]** + +```javascript +function foo() { + return () => { + console.log(this); + }; +} +``` + +For details, see [@typescript-eslint/no-this-alias](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-this-alias.md). + +The description of ESLint is stricter. Therefore, do not assign **this** to a variable in any case. + +# Classes and Objects + +## Use Dots to Access Object Attributes and [] to Access Computed Attributes + +**[Category] Rule** + +**[Description]** + +In JavaScript, you can use dots (**foo.bar**) or square brackets (**foo['bar']**) to access attributes. The use of dots is preferred because it is more readable, concise, and more suitable for JavaScript compression. + +**[Correct Example]** + +```javascript +const name = obj.name; +const key = getKeyFromDB(); +const prop = obj[key]; // Use [] only when the attribute name is a variable. +``` + +## Do Not Modify the Prototype of a Built-in Object or Add Methods to the Prototype + +**[Category] Rule** + +**[Description]** + +As a set of public interfaces, built-in objects have conventional behavior modes. Any modification to the prototype of a built-in object may damage the semantics. Therefore, never modify the prototype of a built-in object, or add methods to the prototype. + +**[Incorrect Example]** + +```javascript +Array.prototype.indexOf = function () { + return -1; +} +// Used in other places. +const arr = [1, 1, 1, 1, 1, 2, 1, 1, 1]; +console.log (arr.indexOf(2)); // Output -1. +``` + +## Do Not Delete the Computed Attributes of an Object + +**[Category] Rule** + +**[Description]** + +The delete operation changes the layout of an object. Deleting the computed attributes of an object is a dangerous behavior. It greatly restricts the runtime optimization and affects the execution performance. + +You are advised not to delete any attribute of an object. If necessary, use **map** and **set**. + +**[Incorrect Example]** + +```javascript +// Can be replaced with the constant equivalents, such as container.aaa +delete container['aaa']; + +// Dynamic, difficult-to-reason-about lookups +const name = 'name'; +delete container[name]; +delete container[name.toUpperCase()]; +``` + +**[Correct Example]** + +```javascript +// The code affects the optimization performance to some extent, but it is better than deleting the computed attributes. +delete container.aaa; + +delete container[7]; +``` + +For details, see [@typescript-eslint/no-dynamic-delete](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-dynamic-delete.md). + +# Exceptions + +## Do Not Use return, break, continue, or throw to End the Finally Block Abnormally + +**[Category] Rule** + +**[Description]** + +In the finally block, if the **return**, **break**, **continue**, or **throw** statement is directly used or the exception that occurs during the method calling is not handled, the finally block ends abnormally. Such a block affects the throwing of exceptions in the **try** or **catch** block, or even the return value of the method. Therefore, you must ensure that the finally block ends normally. + +**[Incorrect Example]** + +```javascript +function foo() { + try { + ... + return 1; + } catch(err) { + ... + return 2; + } finally { + return 3; + } +} +``` + +**[Correct Example]** + +```javascript +function foo() { + try { + ... + return 1; + } catch(err) { + ... + return 2; + } finally { + console.log('XXX!'); + } +} +``` + +# Async Functions + +## Use return await Only When Necessary + +**[Category] Rule** + +**[Description]** + +The return value of an async function is always encapsulated in **Promise.resolve**. The **return await** statement does not actually do anything, but adds time before **Promise.resolve** or **reject**. Therefore, use **return await** only in the **try** or **catch** statement to capture errors of another promise-based function. + +**[Incorrect Example]** + +```javascript +async function foo() { + return await bar(); +} +``` + +**[Correct Example]** + +```javascript +async function foo() { + return bar(); +} +async function foo() { + await bar(); + return; +} +async function foo() { + const baz = await bar(); + return baz; +} +async function foo() { + try { + return await bar(); + } catch (error) { + // here can be executed, go on + } +} +``` + +## Do Not Wait for a Non-thenable Value + +**[Category] Rule** + +**[Description]** + +**await** converts a non-thenable value to a promise that has been processed normally and waits for the processing result. In this case, the use of **await** affects the code performance. + +**[Incorrect Example]** + +```javascript +async function f3() { + const y = await 20; + console.log(y); // 20 +} + +f3(); +console.log(30); + +// output +// 30 +// 20 +``` + +**[Correct Example]** + +```javascript +async function f3() { + const y = 20; + console.log(y); // 20 +} + +f3(); +console.log(30); + +// output +// 20 +// 30 +``` + +For details, see [@typescript-eslint/await-thenable](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/await-thenable.md). + +# Types + +## Forcibly Mark null and undefined as Independent Types + +**[Category] Rule** + +**[Description]** + +Marking **null** and **undefined** as independent types improves code security and avoids null pointer exceptions. + +**[Incorrect Example]** + +```javascript +let userName: string; +userName = 'hello'; +userName = undefined; +``` + +**[Correct Example]** + +```javascript +let userName: string | undefined; +userName = 'hello'; +userName = undefined; +``` + +## Explicitly Declare the Return Value Types of Functions and Class Methods + +**[Category] Rule** + +**[Description]** + +Explicitly declare the return value type to ensure that the return value is assigned to the variable of the correct type. In addition, the explicit declaration ensures that **undefined** is not assigned to a variable when there is no return value. + +**[Incorrect Example]** + +```javascript +// When there is no return value, the return value type is not declared as void. +function test() { + return; +} +// The return value type is not declared as number. +function fn() { + return 1; +}; +// The return value type is not declared as string. +let arrowFn = () => 'test'; +class Test { + // When there is no return value, the return value type is not declared as void. + method() { + return; + } +} +``` + +**[Correct Example]** + +```javascript +// When there is no return value, explicitly declare the return value type as void. +function test(): void { + return; +} +// Explicitly declare the return value type as number. +function fn(): number { + return 1; +}; +// Explicitly declare the return value type as string. +let arrowFn = (): string => 'test'; +class Test { + // When there is no return value, explicitly declare the return value type as void. + method(): void { + return; + } +} +``` + +For details, see [@typescript-eslint/explicit-function-return-type](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-function-return-type.md). + +## Use Consistent Export Types + +**[Category] Rule** + +**[Description]** + +To export a type, write the type to export and the objects to export separately. + +**[Incorrect Example]** + +```javascript +interface ButtonProps { + onClick: () => void; +} +class Button implements ButtonProps { + onClick() { + console.log('button!'); + } +} +export { Button, ButtonProps }; +``` + +**[Correct Example]** + +```javascript +interface ButtonProps { + onClick: () => void; +} +class Button implements ButtonProps { + onClick() { + console.log('button!'); + } +} +export { Button }; +export type { ButtonProps }; +``` + +For details, see [@typescript-eslint/consistent-type-exports](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/consistent-type-exports.md). + +## Use Consistent Import Types + +**[Category] Rule** + +**[Description]** + +To import a type, write the type to import and the objects to import separately. + +**[Incorrect Example]** + +```javascript +import { Foo } from 'Foo'; +import Bar from 'Bar'; +type T = Foo; +const x: Bar = 1; +``` + +**[Correct Example]** + +```javascript +import type { Foo } from 'Foo'; +import type Bar from 'Bar'; +type T = Foo; +const x: Bar = 1; +``` + +For details, see [@typescript-eslint/consistent-type-imports](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/consistent-type-imports.md). + +## Do Not Use any + +**[Category] Rule** + +**[Description]** + +If the **any** type is used, all type checks during compilation are ignored. This behavior is not necessary and does not meet expectations. If the type is unknown, use **unknown**. +If the introduced third-party component does not use TypeScript or does not provide the TypeScript type declaration, you can use **any** to declare the related third-party component objects. + +## Do Not Define the any Type + +**[Category] Rule** + +**[Description]** + +Do not define the **any** type. This restriction makes types as clear as possible in TypeScript and helps the runtime optimization. + +**[Incorrect Example]** + +```javascript +const age: any = 'seventeen'; +function greet(): any {} +function greet(param: Array): string {} +``` + +**[Correct Example]** + +```javascript +const age: number = 17; +function greet(): string {} +function greet(param: Array): string {} +``` + +For details, see [@typescript-eslint/no-explicit-any](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-explicit-any.md). + +## Do Not Pass In any as a Parameter + +**[Category] Rule** + +**[Incorrect Example]** + +```javascript +declare function foo(arg1: string, arg2: number, arg3: string): void; + +const anyTyped = 1 as any; + +foo(...anyTyped); +foo(anyTyped, 1, 'a'); + +const tuple1 = ['a', anyTyped, 'b'] as const; +foo(...tuple1); +``` + +**[Correct Example]** + +```javascript +declare function foo(arg1: string, arg2: number, arg3: string): void; + +foo('a', 1, 'b'); + +const tuple1 = ['a', 1, 'b'] as const; +foo(...tuple1); +``` + +For details, see [@typescript-eslint/no-unsafe-argument](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-argument.md). + +## Do Not Use any in Value Assignment + +**[Category] Rule** + +**[Incorrect Example]** + +```javascript +const x = 1 as any, + +const x: Set = new Set(); +``` + +**[Correct Example]** + +```javascript +const x = 1; + +const x: Set = new Set(); +``` + +For details, see [@typescript-eslint/no-unsafe-assignment](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md). + +## Do Not Call a Variable with the any Type + +**[Category] Rule** + +**[Incorrect Example]** + +```javascript +declare const anyVar: any; +declare const nestedAny: { prop: any }; + +anyVar(); +anyVar.a.b(); + +nestedAny.prop(); +nestedAny.prop['a'](); +``` + +**[Correct Example]** + +```javascript +declare const typedVar: () => void; +declare const typedNested: { prop: { a: () => void } }; + +typedVar(); +typedNested.prop.a(); +``` + +For details, see [@typescript-eslint/no-unsafe-call](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-call.md). + +## Do Not Access Members of an Object with the any Type + +**[Category] Rule** + +**[Incorrect Example]** + +```markup +declare const anyVar: any; +declare const nestedAny: { prop: any }; + +anyVar.a; +anyVar.a.b; + +nestedAny.prop.a; +nestedAny.prop['a']; +``` + +**[Correct Example]** + +```javascript +declare const properlyTyped: { prop: { a: string } }; + +properlyTyped.prop.a; +properlyTyped.prop['a']; +``` + +For details, see [@typescript-eslint/no-unsafe-member-access](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-member-access.md). + +## Do Not Declare the Return Value Type of a Function as any or any[] + +**[Category] Rule** + +**[Incorrect Example]** + +```javascript +function foo1() { + return 1 as any; +} +``` + +**[Correct Example]** + +```javascript +function foo1() : number { + return 1; +} +``` + +For details, see [@typescript-eslint/no-unsafe-return](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-return.md). + +# References + +1. [JavaScript Coding Style Guide](OpenHarmony-JavaScript-coding-style-guide.md) +1. [ESLint Rules](https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/eslint-plugin/docs/rules) +1. High Performance JavaScript diff --git a/en/design/OpenHarmony-part-design.md b/en/design/OpenHarmony-part-design.md index 7e6db1f4564b9f2262f2365ebbac01054755ab0d..9aa56571f2f1228080ead84bf8c01934ecad69b7 100644 --- a/en/design/OpenHarmony-part-design.md +++ b/en/design/OpenHarmony-part-design.md @@ -1,118 +1,353 @@ -# OpenHarmony Part Design Guide +# OpenHarmony Component Design Guide -## About This Document +## Basic Concepts -For easy software design and management, OpenHarmony decouples software from physical components, parts, and modules. A **component** can be independently deployed and reused at the binary level. A **part** can be independently developed, built, and tested. A **module** can be reused at the code level. +For easy software design and management, OpenHarmony decouples software from images, components (named components originally), and modules. Their relationship is shown below. -OpenHarmony abstracts system capabilities as parts, so you can assemble and configure these parts to customize an OS for different devices. +![](figures/Component-Module.png) -## Part Definition +### Component Definition -A part is the basic unit of system capabilities. Divided based on source code, every part has independent files and directories, and can be instantiated into libraries or executable files on different devices. +OpenHarmony abstracts system capabilities as components, so you can customize OSs for different devices by assembling and configuring these components. -## Part Division +A component is the basic unit of system capabilities. Divided based on source code, every component has independent files and directories, and can be instantiated into libraries or executable files on different devices. -Observe the following rules for part classification: +The introduction of components is to enable a set of OS code to support a variety of product forms, thereby solving the problem of hardware and product fragmentation in different industries and improving the device development efficiency. -- A part must have an independent code directory for compiling libraries or executable files. +![](figures/Component-Definition.png) -- A part must be able to be independently deployed in the small system or standard system. Optional parts can be tailored without causing system exceptions. +## Component Design -- Functions of a part must be able to be independently tested and verified. +### Component Classification Rules -A part always belongs to a specific subsystem. A subsystem is a logical concept and consists of specific parts. +When developing a new function that is optional and can be tailored, add a component, rather than a module. In addition, observe the following rules: -Note the following: +- A component must have an independent code directory for compiling libraries or executable files. +- A component must be able to be independently deployed in the small system or standard system. Optional functions can be tailored without causing system exceptions. +- A component must be able to be independently tested and verified. -- External APIs provided by a part must be the same regardless of whether the configurable features of the part are configured. +### **Rules and Recommendations** -- Dependent third-party open source software libraries and parts that provide basic capabilities are called **dependent parts**, which must be deployed with other parts. +Comply with the following rules and recommendations during component design: -- If a part can be split into smaller functional modules and provide APIs for applications, these modules are called **child parts**, which must be deployed with the parent part. A child part depends on a parent part, but a parent part does not depend on a child part. +**Rule 1.1** Components must be developed individually to ensure decoupling and independence. -## Basic Principles +**Rule 1.2** A common component should not depend on a specific chip, development board, or product form, except for a component related to drivers and kernels. -Comply with the following rules and recommendations during parts design and development: +**Rule 1.3** All components in the minimum system component set are mandatory. They should not depend on an optional component outside the minimum system component set. -**Rule 1.1** Parts must be developed individually to ensure decoupling and independence. +> For details about the definition of the minimum system and the minimum system component set, see **PCS** in [OpenHarmony Product Compatibility Specifications](https://www.openharmony.cn/certification/document/pcs). -**Rule 1.2** Parts must be managed in a decentralized manner. The dependency between parts must be simple, clear, and reasonable. +**Rule 1.4** New components must be reviewed by architects and designers in the respective domain. -**Rule 1.3** Reverse dependency and cyclic dependency between parts are prohibited. Lower-layer parts must not depend on upper-layer parts. +**Rule 1.5** Reverse dependency and cyclic dependency between components are prohibited. Lower-layer components must not depend on upper-layer components. -**Rule 1.4** It is prohibited that the implementation of a part depends on a specific development board or product form. +**Rule 1.6** Application APIs provided by a component must be stable and compatible with earlier versions. Deprecated APIs must be reclaimed as planned. -**Rule 1.5** APIs provided by a part must be stable and compatible. Changes to released APIs are prohibited. +**Rule 1.7** External APIs provided by a component must be the same regardless of whether the configurable features of the component are configured. -**Rec 1.1** Parts should support automated build and verification. +**Rule 1.8** The component name must reflect the key function of a component and must be globally unique in the system. The name can contain a maximum of 63 characters and must be in the unix_like style, where only lowercase letters separated by underscores (\_) are used. -## Naming Rules +**Rule 1.9** The component repository must be named in the format of \_. For example, the repository name of the storage service component in the file management subsystem is **filemanagement\_storage\_service**. The repository name can contain a maximum of 100 characters. -#### **Part Name** - -The name must reflect the key function of a part and must be globally unique in the system. It can contain a maximum of 63 characters and must be in the unix\_like style, where only lowercase letters separated by underscores (\_) are used. - -#### **Repository Name** - -The part repository is named in the format of \_. For example, the repository name of the storage service part in the file management subsystem is **filemanagement\_storage\_service**. The repository name can contain a maximum of 100 characters. - -> Note: +> **NOTE** > -> 1. In principle, there is a one-to-one mapping between parts and repositories. In some cases, multiple parts can share a repository, but they must have independent directories. +> 1. In principle, there is a one-to-one mapping between components and repositories. In some cases, multiple components can share a repository, but they must have independent directories. > -> 2. For a third-party open source part, use the original name with the prefix **third\_party**. All third-party open source parts are stored in the **third\_party** directory. +> 2. For a third-party open source component, retain the original component name, and add the prefix **third_party** to the repository name. All third-party open source components are stored in the **third_party** directory. > > 3. The subsystem names in the repository name and path should not contain underscores (\_). -#### **Path** - -The part name must be in the format of //, for example, **foundation/filemanagement/storage_service**. +**Rule 1.10**: The component source code path must be in the format of //, for example, **foundation/filemanagement/storage_service**. -#### **Part Directory Structure** +**Rule 1.11** The component directory structure must be as follows: ```xml ├── interfaces # APIs │ ├── kits # Application APIs (optional) │ │ ├── js # JS APIs (optional) │ │ └── native # C/C++ APIs (optional) -│ └── inner_api # Internal APIs of parts -├── frameworks # Implementation of the part without independent processes (optional) +│ └── inner_api # Internal APIs of components +├── frameworks # Implementation of components without independent processes (optional) │ ├── native # C/C++ API implementation (optional) -│ └── js # JS API implementation (optional) +│ └── js # JS API implementation (optional) │ ├── napi # Native API implementation (optional) │ ├── builtin # Specific to LiteOS-M (optional) │ └── plugin # Specific to ArkUI (optional) -├── services # Implementation of parts with independent processes (optional) +├── services # Implementation of components with independent processes (optional) ├── test # Test code (mandatory) ├── BUILD.gn # Entry to build (mandatory) -└── bundle.json # Part description file (mandatory) +└── bundle.json # Component description file (mandatory) ``` -## Adding, Deleting, or Modifying Parts +**Rec 1.1** Components should support automated build and verification. + +### System Capabilities + +System capabilities are provided by components. A system capability can be bound to one or more APIs. System capabilities function as a bridge between device development and application development. The differences in devices assembled with various components are represented by different system capabilities. In other words, the APIs that can be used vary according to the device in use. The figure below shows how system capabilities are used in the entire development process. + +![](figures/Component-SysCap.png) + +1. An application developer uses the normalized SDK that supports multiple devices to develop an application. The SDK contains a full set of system capabilities (optional and mandatory) and corresponding APIs. + +2. A device developer assembles optional components and adds private components to form the system capability set of a device. + +3. The system capability set is automatically written to the device during compilation and packaging. + +4. A Product Compatibility ID (PCID) is automatically generated during device compilation. When developing an application for a specific device, the application developer imports the PCID to DevEco Studio to obtain the system capability set of the device during development. -The addition, deletion, and modification of parts must be reviewed by the architecture SIG and [related domain SIGs](https://gitee.com/openharmony/community/blob/master/sig/sigs_subsystem_list.md). The review process is as follows: +5. A Required Product Compatibility ID (RPCID), a set of system capabilities required by the application, is automatically generated during application compilation and packaging. -1. Prepare the following part attribute review form. +6. When distributing an application, the application market matches the application's RPCID against the device's PCID. It distributes the application to that device only if the application's RPCID is within the device's PCID. -Table 1 Part attribute review form +7. In the ability continuation scenario, the system capabilities are synchronized between devices. -| Part Attribute | Description | -| ------------ | ------------------------------------------------------------ | -| Part name | The name must reflect the key function of a part and must be globally unique in the system. The name can contain a maximum of 63 characters and must be in the unix\_like style, where only lowercase letters separated by underscores (\_) are used. | -| Subsystem | Subsystem to which the part belongs. | -| Function description | Brief description of the functions of the part in one or two sentences. | -| Configurable features | Features that can be configured externally. | -| Applicable systems | Mini system, small system, standard system, or their combinations. | -| Source code directory | Root directory of the source code of the part. | -| ROM | ROM baseline value of the part. | -| RAM | RAM baseline value of the part. | -| Dependencies | Parts and open source software on which the part depends. | +8. In the installation-free scenario, the system capabilities of a device can be queried on the cloud. +#### Using System Capabilities During Application Development -2. Send an email to the architecture SIG (dev@openharmony.io) and the [related domain SIG leaders](https://gitee.com/openharmony/community/blob/master/sig/sigs_subsystem_list.md) for review. Use "Application for Adding/Deleting/Modifying OpenHarmony Parts" as the email subject, and include the filled-in **Table 1 Part Attribute Review Form** in the email body. +An application developer can call the **CanIUse** API to query the system capabilities of a device at runtime. The code snippet is as follows: + +```javascript +import geolocation from '@ohos.geolocation' + +const isLocationAvailable = canIUse('SystemCapability.Location.Location'); +if (isLocationAvailable) { + geolocation.getCurrentLocation((location) => { + console.log(location.latitude, location.longitue); + }); +} else { + console.log('Location not by this device.') +} +``` + +The SDK defines the system capability set for typical device types. If a device type is selected during application development and the API called exceeds the range supported by the mandatory system capabilities of the device type, DevEco Studio displays a message indicating that the API is not supported by the device and the application compilation will fail. + +#### Defining System Capabilities During Device Development + +There is a one-to-one relationship between components and system capabilities, and the APIs mapped to different system capabilities do not overlap. A system capability must be named in the format of SystemCapability.Category. Feature.Subfeature (optional), for example, **SystemCapability.Media.Camera** and **SystemCapability.Media.Camera.Front**. Generally, a subfeature is implemented by an independent component. This component depends on a component that provides the basic feature, and therefore the dependent component must also be assembled into the product. + +1. Declare the system capability in the **bundle.json** file of the component. The code snippet is as follows: + + ```json + { + ... + "component": { + "name": "camera", # Component name. + "syscap": [ "SystemCapability.Media.Camera" ] # System capability of the component. + }, + ... + } + ``` + +2. Declare the system capability attribute of the API in the corresponding .d.ts file for binding. The code snippet is as follows: + + ```js + /** + * @name camera + * @syscap SystemCapability.Media.Camera + * @ since 9 + */ + declare namespace camera { + ... + } + ``` + +### Component Review + +The addition, modification (function or interface changes), and deletion of components must be reviewed by the architecture SIG and [related domain SIGs](https://gitee.com/openharmony/community/tree/master/sig). The review process is as follows: + +1. Prepare the following component attribute review form. + + Table 1 Component attribute review form + + | Component Attribute | Description | + | ------------ | ------------------------------------------------------------ | + | Component name | The name must reflect the key function of a component and must be globally unique in the system. The name can contain a maximum of 63 characters and must be in the unix\_like style, where only lowercase letters separated by underscores (\_) are used.| + | Subsystem | Subsystem to which the component belongs. | + | Function description | Brief description of the functions of the component in one or two sentences. | + | Configurable features | Features that can be configured externally. | + | SysCap | System capability, for example, **SystemCapability.Media.Camera** or **SystemCapability.Media.Camera.Front**.| + | Applicable systems| Mini system, small system, standard system, or their combinations. | + | Source code directory | Root directory of the source code of the component. | + | ROM | ROM baseline value of the component. | + | RAM | RAM baseline value of the component. | + | Dependencies | Components and open source software on which the component depends. | + + +2. Send an email to the architecture SIG (dev@openharmony.io) and the [related domain SIG leaders](https://gitee.com/openharmony/community/tree/master/sig) for review. Use "Applying for Adding/Modifying/Deleting OpenHarmony Components" as the email subject, and include the filled-in **Table 1 Component Attribute Review Form** in the email body. + + > For deleted components, provide the plan for stopping component maintenance. Exercise caution when deleting or modifying components and evaluate the impact on existing versions. + +3. After the review is passed, create a component repository and modify the manifest according to [SIG Management Regulations](https://gitee.com/openharmony/community/blob/master/sig/README_EN.md). After the SIG is incubated, incorporate it into the main code library of OpenHarmony. + +## Component Development + +After the component passes the review, the component name, repository, and source code path are determined. You can perform component development as follows: + +### Adding a Description File + +In the development state, create a **bundle.json** file in the root directory of the component. The file contains the component name, compilation, test, system capability, features, and internal interfaces. For details about the fields, see [Description File](../device-dev/subsystems/subsys-build-component-building-rules.md#description-file). The code snippet is as follows: + +```json +{ + "name": "@ohos/my_component", + "description": "my first component", + "version": "4.0", + "license": "Apache License 2.0", + "publicAs": "code-segment", + "segment": { + "destPath": "my_domain/my_subsystem/my_component" + }, + "component": { + "name": "my_component", + "subsystem": "my_subsystem", + "syscap": [ + "SystemCapability.MySubsystem.MyComponent" + ], + "build": { + "moudles": [ + "//my_domain/my_subsystem/my_component/my_module:my_module" + ], + "inner_api": [ + "name": "//my_domain/my_subsystem/my_component/my_module:inner_api", + "header_base": "//my_domain/my_subsystem/my_component/interfaces/inner_api/my_module" + ], + "test": [ + "//my_domain/my_subsystem/my_component:unit_test" + ] + } + } +} +``` + +**inner_api** is an interface declared by the component for dependency between components within the system. The dependency must be specified in **external_deps**. The following is an example: + +```c +ohos_executable("other_component") { + ... + external_deps = [ "my_module:inner_api" ] +} +``` + +### Adding a Compilation Script + +In the **bundle.json** file, **build:modules** provides the component compilation entry. The following is an example of the compilation script of the **my_module** module in the dynamic library: + +```c +ohos_shared_library("my_module") { + sources = [ ... ] + ... + external_deps = [ ... ] + + part_name = "my_component" + subsystem_name = "my_subsystem" +} +``` -> Note: +The component compilation script must comply with component-based requirements. For details, see [Component Building Specifications](../device-dev/subsystems/subsys-build-component-building-rules.md#component-building-specifications). + +### Compilation Verification + +After adding the description file and compilation script of the component, compile the code source to develop the functions of the component. To enable the compilation of a component, configure the component in the product configuration file. The following is an example: + +```json +{ + "product_name": "my_product", + "device_company": "my_device_company", + "target_cpu": "arm", + ... + "subsystems": [ + { + "subsystem": "my_subsystem", + "components": [ + { + "component": "my_component" + } + ] + }, + ... + ] +} +``` + +The following code snippet is used to compile a component separately: + +```c +./build.sh --product-name my_product --build-target my_domain/my_subsystem/my_component/my_module:my_module +``` + +Upload the compilation products and test cases of the component to the device to verify the functions. + +Full compilation can also be used to verify a new component. For details, see [Adding and Compiling Components](../device-dev/subsystems/subsys-build-component.md#adding-and-building-a-component). + +## Assembling Components + +The product configuration file ***vendor*/*{company}*/*{product}*/config.json** can be used to assemble a product form based on the component and feature dimensions. It allows device developers to quickly build a product without intrusively modifying OpenHarmony source code. The product configuration includes the product name, development board, subsystems, and components. The following is an example: + +```json +{ + "product_name": "my_product", + "device_company": "my_device_company", + "target_cpu": "arm64", + "subsystems": [ + { + "subsystem": "my_subsystem", + "components": [ + { + "component": "my_component", + "features": [] + } + ] + }, + ... + ] +} +``` + +The compilation command is **./build.sh --product-name my_product**. + +### Determining Whether a Component Is Required + +A component set can be configured for a product based on hardware and product functions. For example, NFC-related components are not configured on a device that does not need to provide the NFC feature. + +> **NOTE** +> +> 1. The minimum system component set must be configured by default. > -> For modified parts, provide a before and after comparison of the part attributes. For deleted parts, provide the plan for stopping part maintenance. Exercise caution when deleting or modifying parts and evaluate the impact on existing versions. +> 2. A component and its dependent components must be configured together. Otherwise, the compilation fails. + +### Configuring Features + +#### During Compilation + +A feature in the **bundle.json** file of a component is the compilation state option declared by the component. It can be of the Boolean, numeric, or string type. The feature in the product configuration file can be changed to the default value provided by the component. For example, the screen saver feature of power management is disabled by default. You can enable it in the product as follows: + +```json +{ + { + "subsystem": "powermgr", + "components": [ + { "component": "powermgr", "features":[ "powermgr_screensaver_enable = true" ] } + ] + } +} +``` + +For details about the feature configuration, see [Feature](../device-dev/subsystems/subsys-build-feature.md). + +#### Runtime + +For complex components, system parameters can be read or custom configuration files can be used during runtime to load different features, thereby meeting diverse product requirements. With feature configuration at the runtime, a component needs to be compiled only once. For different products, you only need to modify system parameters or configuration files during assembly and then create images. + +### Inheritance + +The product configuration file can inherit the component set through the **inherit** field. Currently, OpenHarmony provides two types of components: minimum system component set and typical product form set, which are defined in the **productdefine/common/base** and **productdefine/common/inherit** directories, respectively. The following is an example of inheriting the minimum system component set: + +```json +{ + "inherit": [ "productdefine/common/base/standard_system.json" ], +} +``` -3. After the review is passed, create a part repository and modify the manifest according to [SIG Management Regulations](https://gitee.com/openharmony/community/blob/master/sig/README_EN.md). After the SIG is incubated, incorporate it into the main code library of OpenHarmony. +Inheritance can simplify product configuration and improve efficiency. diff --git a/en/design/figures/Component-Definition.png b/en/design/figures/Component-Definition.png new file mode 100644 index 0000000000000000000000000000000000000000..7315ba6499270c4910fdd2f3ff815868104f1140 Binary files /dev/null and b/en/design/figures/Component-Definition.png differ diff --git a/en/design/figures/Component-Module.png b/en/design/figures/Component-Module.png new file mode 100644 index 0000000000000000000000000000000000000000..28dd092a067b644c7d5dea9fe493d9d96d068a50 Binary files /dev/null and b/en/design/figures/Component-Module.png differ diff --git a/en/design/figures/Component-SysCap.png b/en/design/figures/Component-SysCap.png new file mode 100644 index 0000000000000000000000000000000000000000..0ff5674d430bfb260acb867dc1716f85d2ecc4c3 Binary files /dev/null and b/en/design/figures/Component-SysCap.png differ diff --git a/en/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md b/en/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md index c92f86c100993cbd0fc346562a5c4558f6206c2f..b80a13d2b99edff2652a84f075fd2d5f56b70769 100644 --- a/en/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md +++ b/en/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md @@ -1229,10 +1229,10 @@ To adapt the multimedia subsystem, you need to add the `histreamer` component in { "component": "histreamer", "features": [ - "multimedia_histreamer_enable_plugin_hdi_adapter = true", - "multimedia_histreamer_enable_plugin_minimp3_adapter = true", - "multimedia_histreamer_enable_plugin_ffmpeg_adapter = false", - "config_ohos_multimedia_histreamer_stack_size = 65536" + "histreamer_enable_plugin_hdi_adapter = true", + "histreamer_enable_plugin_minimp3_adapter = true", + "histreamer_enable_plugin_ffmpeg_adapter = false", + "config_ohos_histreamer_stack_size = 65536" ] } ] @@ -1241,12 +1241,12 @@ To adapt the multimedia subsystem, you need to add the `histreamer` component in The configuration items of the `histreamer` component are described as follows: -| Item | Description | -| --------------------------------------------------- | ------------------------------- | -| multimedia_histreamer_enable_plugin_hdi_adapter | Whether to enable histreamer to connect to the HDMI interface.| -| multimedia_histreamer_enable_plugin_minimp3_adapter | Whether to enable the plug-in to adapt to miniMP3. | -| multimedia_histreamer_enable_plugin_ffmpeg_adapter | Whether to enable the plug-in to adapt to FFmpeg. | -| config_ohos_multimedia_histreamer_stack_size | Size of the histreamer stack. | +| Item | Description | +| ---------------------------------------- | ------------------------------------------------------------- | +| histreamer_enable_plugin_hdi_adapter | Whether to enable histreamer to connect to the HDMI interface.| +| histreamer_enable_plugin_minimp3_adapter | Whether to enable the plug-in to adapt to miniMP3. | +| histreamer_enable_plugin_ffmpeg_adapter | Whether to enable the plug-in to adapt to FFmpeg. | +| config_ohos_histreamer_stack_size | Size of the histreamer stack. | #### utils Subsystem Adaptation diff --git a/en/device-dev/subsystems/Readme-EN.md b/en/device-dev/subsystems/Readme-EN.md index ee9395bf43e05bb96162763054bef034a971c3b0..d56854b895f3138843dba4ef56bd2858f82316d2 100644 --- a/en/device-dev/subsystems/Readme-EN.md +++ b/en/device-dev/subsystems/Readme-EN.md @@ -18,6 +18,10 @@ - [Configuring Parameters for Accelerating Local Build](subsys-build-reference.md) - [Viewing Ninja Build Information](subsys-build-reference.md) - [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md) + - Rust Build Guide + - [Rust Module Configuration Rules and Guide](subsys-build-rust-compilation.md) + - [Using Interactive Tools](subsys-build-bindgen-cxx-guide.md) + - [Using Cargo2gn](subsys-build-cargo2gn-guide.md) - [FAQs](subsys-build-FAQ.md) - [ArkCompiler Development](subsys-arkcompiler-guide.md) - [Distributed Remote Startup](subsys-remote-start.md) @@ -122,4 +126,6 @@ - [Thermal Policy Customization](subsys-thermal_policy.md) - [Thermal Scene Customization](subsys-thermal_scene.md) - Power Management - - [Power Mode Customization](subsys-power-mode-customization.md) \ No newline at end of file + - [Power Mode Customization](subsys-power-mode-customization.md) + - [Default Hibernation Behavior Customization](subsys-power-default-sleep-behavior-customization.md) + - [Wakeup Source Customization](subsys-power-wakeup-source-customization.md) \ No newline at end of file diff --git a/en/device-dev/subsystems/figures/bindgen_and_cxx_tools.png b/en/device-dev/subsystems/figures/bindgen_and_cxx_tools.png new file mode 100644 index 0000000000000000000000000000000000000000..655472225f3dd5581e5849e0af80ff89468094a1 Binary files /dev/null and b/en/device-dev/subsystems/figures/bindgen_and_cxx_tools.png differ diff --git a/en/device-dev/subsystems/figures/bindgen_test.png b/en/device-dev/subsystems/figures/bindgen_test.png new file mode 100644 index 0000000000000000000000000000000000000000..4c4d01b567e35fd07ce7a8a90256281cd9fcc165 Binary files /dev/null and b/en/device-dev/subsystems/figures/bindgen_test.png differ diff --git a/en/device-dev/subsystems/figures/cpp_call_rust.png b/en/device-dev/subsystems/figures/cpp_call_rust.png new file mode 100644 index 0000000000000000000000000000000000000000..49503982f893fb6c24d1e41c24ae54aa9681e2c6 Binary files /dev/null and b/en/device-dev/subsystems/figures/cpp_call_rust.png differ diff --git a/en/device-dev/subsystems/figures/rust_call_cpp.png b/en/device-dev/subsystems/figures/rust_call_cpp.png new file mode 100644 index 0000000000000000000000000000000000000000..eba899d0b111c71420b43c36c21e519228a06d54 Binary files /dev/null and b/en/device-dev/subsystems/figures/rust_call_cpp.png differ diff --git a/en/device-dev/subsystems/figures/test_rlib_cargo_crate.png b/en/device-dev/subsystems/figures/test_rlib_cargo_crate.png new file mode 100644 index 0000000000000000000000000000000000000000..86ade8272f625e6aa4336c713d52ee537918531c Binary files /dev/null and b/en/device-dev/subsystems/figures/test_rlib_cargo_crate.png differ diff --git a/en/device-dev/subsystems/figures/test_rlib_crate.png b/en/device-dev/subsystems/figures/test_rlib_crate.png new file mode 100644 index 0000000000000000000000000000000000000000..3df5877b7a3f583513527de1adcdabb80755961a Binary files /dev/null and b/en/device-dev/subsystems/figures/test_rlib_crate.png differ diff --git a/en/device-dev/subsystems/subsys-boot-init-sysparam.md b/en/device-dev/subsystems/subsys-boot-init-sysparam.md index 1b5541a741273c7db7551bc6441bbfb44d1532a6..0dfc391b06ed14caf4bc5d0e17ce8a4654af723e 100644 --- a/en/device-dev/subsystems/subsys-boot-init-sysparam.md +++ b/en/device-dev/subsystems/subsys-boot-init-sysparam.md @@ -1,30 +1,39 @@ # Parameter Management + ## Overview + ### Function -The parameter management module, namely, sysparam, provides an easy-to-use key-value pair access interface for system services to configure service functions based on their own system parameters. +The parameter management subsystem, namely, sysparam, provides easy-to-use key-value pair access interfaces for system services to customize functions based on their own system parameters. ### Basic Concepts -Figure 1 System parameter operation primitives +#### Operation Primitives + +Figure 1 shows the primitives used to operate system parameters. For details about how they work, see Table 1. + +Figure 1 Overview of system parameter operation primitives ![System parameter operation primitives](figures/system-parameter-operation-primitives.png) **Table 1** Description of system parameter operation primitives -| Operation Primitive| Description| + +| Operation Primitive | Description | | -------- | -------- | | get | Obtains the value of a system parameter. | | set | Sets the value of a system parameter. | | wait | Waits for value change of a system parameter synchronously.| | watch | Observes value change of a system parameter asynchronously.| -#### System Parameter Definition +#### Parameter Definition - Naming format - A system parameter name consists of multiple segments in dotted notation. Each segment can be a string that consists of letters, digits, and underscores (_). The total length cannot exceed 96 bytes. System parameter names are categorized into the following two types. + A system parameter name consists of multiple segments in dotted notation. Each segment can be a string that consists of letters, digits, and underscores (_). The total length cannot exceed 96 bytes. + + Two naming formats are supported for system parameters, as described in Table 2. - **Table 2** System parameter names + **Table 2** Description of system parameter naming formats | Type | Example | Description | | -------- | -------- | -------- | @@ -33,31 +42,33 @@ Figure 1 System parameter operation primitives - Type - System parameters are categorized into three types. + System parameters are categorized into three types, as described in Table 3. - **Table 3** System parameter types + **Table 3** Description of system parameter types | Type| Prefix| Description| | -------- | -------- | -------- | - | Constant| const. | Constant parameter, which will not be changed once a value is assigned. The value can contain a maximum of 4,096 bytes (including the terminator).| - | Writable| Others| Writable parameter, which will be lost after system restart. The value can contain a maximum of 96 bytes (including the terminator).| - | Persistent| persist. | Writable and persistent parameter, which will not be lost after system restart. The value can contain a maximum of 96 bytes (including the terminator).| + | Constant| const. | Constant parameter, which will not change once a value is assigned. The value can contain a maximum of 4,096 bytes (including the end-of-text character).| + | Writable| Others| Writable parameter, which will be discarded after a system restart. The value can contain a maximum of 96 bytes (including the end-of-text character).| + | Persistent| persist. | Writable and persistent parameter, which will not be discarded after a system restart. The value can contain a maximum of 96 bytes (including the end-of-text character).| - The general naming format is as follows: + Given below is the general naming format for system parameters: ``` [ const | persist ].$sub_system.$desc ``` - **$sub_system** is the name of the subsystem or module. + wherein, + + - **$sub_system** is the subsystem or module name. - **$desc** indicates the description of a system parameter. The description can contain multiple segments in dotted notation. + - **$desc** is the parameter description, which can contain multiple segments in dotted notation. -#### Definition Rules +#### Parameter Definition Rule -Each subsystem defines the system parameters of its own modules, including the system parameter name, default value, and access permission information. +System parameters are defined per module on each subsystem. The parameter definition includes the system parameter name, default value, and access permission information. -- System parameter value definition file +- Value definition file - - The system parameter value definition file ends with the **.para** extension. An example of the file format is as follows: + - A value definition file of system parameters ends with the **.para** extension. The following is an example format of file content: ```shell # This is comment @@ -66,43 +77,49 @@ Each subsystem defines the system parameters of its own modules, including the s const.telephony.enable=false|true const.test.withblank=My Value - const.test.withcomment=MyValue # This should be ommitted + const.test.withcomment=MyValue # This should be omitted const.test.multiline="This is a multiline parameter. Line2 value. Last line." ``` - - You must use a complete system parameter command when assigning a value for a system parameter. The following table describes the value assignment modes. + - A complete system parameter command is required to assign a value for a system parameter. See Table 4 for the value assignment modes. - **Table 4** Value assignment modes + **Table 4** Description of value assignment modes | Type| Example| Description| | -------- | -------- | -------- | - | String | const.product.name=OHOS-PRODUCT | A multi-line string must be enclosed in double quotation marks ("").| - | Number | const.os.version.api=26 | Numbers do not need to be enclosed in quotation marks.| + | String | const.product.name=OHOS-PRODUCT | A string that spans multiple lines must be enclosed in double quotation marks ("").| + | Number | const.os.version.api=26 | A number that spans multiple lines does not need to be enclosed in double quotation marks ("").| | Boolean | const.telephony.enable=false | A Boolean value can be **0**, **1**, **false**, or **true**.| - DAC definition file - Currently, access permissions of system parameters are managed in Discretionary Access Control (DAC) mode. The access permission definition file ends with the **.para.dac** extension. The following is an example: + Access permissions of system parameters are managed in discretionary access control (DAC) mode. A DAC definition file ends with the **.para.dac** extension. The following is an example format of DAC information: ```java const.product.="root:root:660" ``` - As shown above, we can use **parameter directory** to define the same access permission for system parameters with the same prefix. The DAC information is divided into three segments, user, group, and UGO rule, which are separated using a semicolon (:). + As shown in this example, a **parameter directory** can be used to define the same access permission for system parameters with the same prefix. A piece of DAC information is divided into three segments, user, group, and Ugo rule, which are separated using a semicolon (:). + + > **NOTE** + > + > Ugo is the abbreviation for user access, group access, ad other system user's access, respectively. These permissions are set to allow or deny access to members of their own group, or any other groups. + + Figure 2 shows the Ugo rule structure. - The following figure shows the structure of the UGO rule. + **Figure 2** Overview of the Ugo rule structure - **Figure 2** UGO rule structure + ![Ugo rule](figures/dac-definition.png) - ![UGO rule](figures/dac-definition.png) +- SELinux policy -- SELinux policy for system parameter configuration + An SELinux policy defines the access permissions for all users, programs, processes, and files. - - Add SELinux tags. + - Adding an SELinux tag - To add a SELinux tag to system parameters, you first need to define the tag in the **/base/security/selinux/sepolicy/base/public/parameter.te** file. For example: + To add an SELinux tag to system parameters, you first need to define the tag in the **/base/security/selinux/sepolicy/base/public/parameter.te** file. For example: ```java type servicectrl_param, parameter_attr @@ -114,62 +131,71 @@ Each subsystem defines the system parameters of its own modules, including the s ohos.servicectrl. u:object_r:servicectrl_param:s0 ``` - - Grant operation permissions. For example, to grant operation permissions such as map for the init process, add the following content to the **/base/security/selinux/sepolicy/ohos_policy/startup/init/public/init.te** file: + - Granting access permissions for a process + + For example, to grant access permissions such as map for the init process, add the following code to the **/base/security/selinux/sepolicy/ohos_policy/startup/init/public/init.te** file: ```java allow servicectrl_param tmpfs:filesystem associate; allow init servicectrl_param:file { map open read relabelto relabelfrom }; ``` - - Set the write permission. For example, grant the system parameter write permission for services such as **init**, **samgr**, and **hdf_devmgr**. + - Granting the write permission + + For example, to grant the write permission for services such as **init**, **samgr**, and **hdf_devmgr**, use the following code: ```java allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set }; ``` - - Set the read permission. If you want to grant the permission only for certain services, replace **xxx** with the services in the following code: + - Granting the read permission + + If you want to grant the read permission only for certain services, replace **xxx** with these services in the following code: ```java allow { xxx } servicectrl_param:file { map open read }; ``` - - If you want to grant the permission for all services, use the following code: + - Granting access permissions for all services + + If you want to grant access permissions for all services, use the following code: ```java allow { domain -limit_domain } servicectrl_param:file { map open read }; ``` -- Suggestions +- System parameter tag - Keep only two system parameter tags for each subsystem: + You are advised to keep only two system parameter tags for each subsystem: - A private tag to control system parameter settings. - - A public tag to grant access from all services. + - A public tag to grant access permissions from all services. - Loading sequence - The following table provides the sequence of loading system parameters. + System parameters are loaded by priority in the specified sequence, as described in Table 5. + + **Table 5** Description of the system parameter loading sequence - **Table 5** System parameter loading sequence | Type| Path| Description| | -------- | -------- | -------- | | Kernel parameters | /proc/cmdline | Convert some values of kernel parameters into system parameters. Specifically, convert all **ohospara.xxx=valXXX** parameters to **ohos.boot.xxx=valXXX** parameters.| | OS system parameters| /system/etc/param/ohos_const/*.para | Load the definition file containing OS constants preferentially. | | Vendor parameters| /vendor/etc/param/*.para | Load the system parameters defined by vendors with the secondary priority. | - | System parameters| /system/etc/param/*.para | Load the parameters defined by each subsystem. If a system parameter already exists, ignore it.| - | Persistent parameters| /data/parameters/ | If persistent parameters exist, load them at last. Persistent parameters will overwrite the default system parameters that have been loaded.| + | System parameters| /system/etc/param/*.para | Load the system parameters defined by each subsystem. A system parameter will be ignored if it already exists.| + | Persistent parameters| /data/parameters/ | Load persistent parameters, if any, at last. Persistent parameters will overwrite the default system parameters that have been loaded.| -#### System Parameter Tag File Size +#### Tag File Size -If one tag corresponds to more than five system parameters, you need to set the size of the system parameter tag file in **/base/startup/init/services/etc/param/ohos.para.size**. The size value is **512** by default. +If one tag is associated with more than five system parameters, you need to set the size of the system parameter tag file in **/base/startup/init/services/etc/param/ohos.para.size**. The default value is **512**. -Configuring rule: +The configuration rule is as follows: System parameter tag = Size -Example: +For example: ```java startup_init_param=40960 @@ -178,18 +204,21 @@ startup_init_param=40960 ### Constraints -The service management module is available only for the mini system and standard system. +The parameter management subsystem is available only for the mini system and standard system. ## How to Develop -### Use Cases +### Application Scenario + You can set specific system parameters as needed to meet your service demand. -### Available APIs +### Implementation Method - - Shell commands +The parameter management subsystem allows you to manage system parameters by running shell commands or calling **syspara** APIs. - You can operate system parameters directly by using shell commands. This operation mode is available only for the standard system. The following table lists the shell commands. + - Shell command mode + + You can operate system parameters directly by running shell commands. This operation mode is available only for the standard system. Table 6 is a list of the shell commands. **Table 6** Description of shell commands @@ -200,51 +229,52 @@ You can set specific system parameters as needed to meet your service demand. | param wait **key** **value** | Waits for the system parameter value of the specified key to match the specified value. Fuzzy match is supported. For example, * indicates any value, and val* indicates matching of only the first three val characters.| | param watch | Observes value change of a system parameter asynchronously.| - - syspara APIs + - syspara API mode - The following table lists the APIs used to obtain system parameter values. The return result is a const string and the free operation is not supported. + Besides shell commands, you can use **syspara** APIs to manage system parameters. The return result is a constant string and the **free** operation is not supported. Table 7 is a list of the **syspara** APIs. **Table 7** Description of syspara APIs + | API| Description| | -------- | -------- | | int GetParameter(const char\* key, const char\* def, char\* value, unsigned int len) | Obtains system parameters.| | int SetParameter(const char\* key, const char\* value) | Sets or updates system parameters.| | const char\* GetDeviceType(void) | Obtains the device type.| - | const char\* GetManufacture(void) | Obtains the device manufacturer.| - | const char\* GetBrand(void) | Obtains the device brand.| - | const char\* GetMarketName(void) | Obtains the device marketing name.| - | const char\* GetProductSeries(void) | Obtains the device series name.| - | const char\* GetProductModel(void) | Obtains the device authentication model.| - | const char\* GetSoftwareModel(void) | Obtains the device software model.| - | const char\* GetHardwareModel(void) | Obtains the device hardware model.| - | const char\* GetHardwareProfile(void) | Obtains the device hardware profile.| - | const char\* GetSerial(void) | Obtains the device serial number (SN).| - | const char\* GetOSFullName(void) | Obtains the operating system name.| - | const char\* GetDisplayVersion(void) | Obtains the software version visible to users.| - | const char\* GetBootloaderVersion(void) | Obtains the bootloader version of this device.| - | const char\* GetSecurityPatchTag(void) | Obtains the security patch tag.| - | const char\* GetAbiList(void) | Obtains the list of application binary interfaces (ABIs) supported on this device.| - | int GetSdkApiVersion(void) | Obtains the SDK API level that matches the current system software.| - | int GetFirstApiVersion(void) | Obtains the first SDK API level of the system software.| - | const char\* GetIncrementalVersion(void) | Obtains the incremental version.| + | const char\* GetManufacture(void) | Obtains the device's manufacturer name.| + | const char\* GetBrand(void) | Obtains the device's brand name.| + | const char\* GetMarketName(void) | Obtains the device's marketing name.| + | const char\* GetProductSeries(void) | Obtains the device's product series name.| + | const char\* GetProductModel(void) | Obtains the device's authentication model.| + | const char\* GetSoftwareModel(void) | Obtains the device's software model.| + | const char\* GetHardwareModel(void) | Obtains the device's hardware model.| + | const char\* GetHardwareProfile(void) | Obtains the device's hardware profile.| + | const char\* GetSerial(void) | Obtains the device's serial number (SN).| + | const char\* GetOSFullName(void) | Obtains the device's OS name.| + | const char\* GetDisplayVersion(void) | Obtains the device's displayed software version.| + | const char\* GetBootloaderVersion(void) | Obtains the device's bootloader version.| + | const char\* GetSecurityPatchTag(void) | Obtains the device's security patch tag.| + | const char\* GetAbiList(void) | Obtains the list of supported application binary interfaces (ABIs).| + | int GetSdkApiVersion(void) | Obtains the SDK API version that matches the current system software.| + | int GetFirstApiVersion(void) | Obtains the first SDK API version of the system software.| + | const char\* GetIncrementalVersion(void) | Obtains the incremental version of the system software.| | const char\* GetVersionId(void) | Obtains the version ID.| | const char\* GetBuildType(void) | Obtains the build type.| - | const char\* GetBuildUser(void) | Obtains the build account user name.| - | const char\* GetBuildHost(void) | Obtains the build host name.| + | const char\* GetBuildUser(void) | Obtains the build user.| + | const char\* GetBuildHost(void) | Obtains the build host.| | const char\* GetBuildTime(void) | Obtains the build time.| - | const char\* GetBuildRootHash(void) | Obtains the buildroot hash value of this version.| + | const char\* GetBuildRootHash(void) | Obtains the buildroot hash value of the current version.| | const char\* GetOsReleaseType(void) | Obtains the system release type.| - | int GetDevUdid(char \*udid, int size) | Obtains the device identifier (UDID).| - | const char *AclGetSerial(void); | Obtains the device SN (with ACL check).| - | int AclGetDevUdid(char *udid, int size); | Obtains the UDID (with ACL check).| + | int GetDevUdid(char \*udid, int size) | Obtains the device's unique device ID (UDID).| + | const char *AclGetSerial(void); | Obtains the device's SN with ACL check.| + | int AclGetDevUdid(char *udid, int size); | Obtains the device's UDID with ACL check.| -### How to Develop +### Development Procedure -1. System parameter definition +#### Parameter Definition - You can define default system parameters and implement permission control on them by configuring the subsystem or product .para and .para.dac files. +You can define default system parameters and implement permission control on them by configuring the .para and .para.dac files of the respective subsystem or product. - ​ On a standard system, use the ohos_prebuilt_para template to install the configuration file to the /etc/param/ directory. The following is an example of the GN script: +- On a standard system, use the ohos_prebuilt_para template to install the configuration file to the /etc/param/ directory. The following is an example of the GN script: ```go import("//base/startup/init/services/etc/param/param_fixer.gni") @@ -262,7 +292,7 @@ You can set specific system parameters as needed to meet your service demand. } ``` - On a small system, run the copy command to copy the corresponding system parameter definition file to the system/etc/param directory. +- On a small system, run the copy command to copy the corresponding system parameter definition file to the system/etc/param directory. ```go copy("ohos.para") { sources = [ "//base/startup/init/services/etc/param/ohos.para" ] @@ -273,7 +303,7 @@ You can set specific system parameters as needed to meet your service demand. outputs = [ "$root_out_dir/system/etc/param/ohos.para.dac" ] } ``` - On a mini system, convert all defined default system parameters into header files through **action** and compile them into the system. +- On a mini system, convert all defined default system parameters into header files through **action** and compile them into the system. ```go action("lite_const_param_to") { script = "//base/startup/init/scripts/param_cfg_to_code.py" @@ -289,7 +319,7 @@ You can set specific system parameters as needed to meet your service demand. outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ] } ``` -2. Development example +#### Development Example ``` // set && get char key1[] = "rw.sys.version"; diff --git a/en/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md b/en/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..cd9bdd0db7b444dc30ed56b666a62d54e194fdcb --- /dev/null +++ b/en/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md @@ -0,0 +1,421 @@ +# Interactive Tool User Guide + +## Introduction + +You can use Bindgen and CXX to implement the interaction between Rust and C/C++. Bindgen enables Rust to call C by converting C interfaces into Rust interfaces. CXX implement interaction between C++ and Rust by generating bindings between C interfaces and Rust interfaces. + +![bindgen_and_cxx_tools](./figures/bindgen_and_cxx_tools.png) + +## Using Bindgen + +### Procedure +The following example shows how to use Bindgen to implement invocation of C by Rust. + +1. In the header file **lib.h**, define two interfaces **FuncAAddB** and **SayHello** in C. The **FuncAAddB** interface calculates the sum of two numbers, and the **SayHello** interface prints strings. + + ```c + #ifndef BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_ + #define BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_ + #include + #include "build/rust/tests/test_bindgen_test/test_for_hello_world/lib2.h" + + uint32_t FuncAAddB(uint32_t a, uint32_t b); + void SayHello(const char *message); + + #endif // BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_ + ``` + + +2. Add the implementation of the two interfaces to **lib.c**. + + ```c + #include "build/rust/tests/test_bindgen_test/test_for_hello_world/lib.h" + #include + #include + + void SayHello(const char *message) + { + printf("This is a test for bindgen hello world:\n"); + printf("%s\n", message); + } + + uint32_t FuncAAddB(uint32_t a, uint32_t b) + { + printf("This is a test for bindgen of a + b:\n"); + return a + b; + } + ``` + +3. Create the **main.rs** file to call C interfaces through c_ffi using Rust. Note that insecure interfaces called by Rust must be encapsulated by using **unsafe**. + + ```rust + //! bindgen test for hello world + #![allow(clippy::approx_constant)] + mod c_ffi { + #![allow(dead_code)] + #![allow(non_upper_case_globals)] + #![allow(non_camel_case_types)] + include!(env!("BINDGEN_RS_FILE")); + } + /// pub fn add_two_numbers_in_c + pub fn add_two_numbers_in_c(a: u32, b: u32) -> u32 { + unsafe { c_ffi::FuncAAddB(a, b) } + } + + use std::ffi::c_char; + use std::ffi::CString; + + /// fn main() + fn main() { + println!("{} + {} = {}", 3, 7, add_two_numbers_in_c(3, 7)); + let c_str = CString::new("This is a message from C").unwrap(); + let c_world: *const c_char = c_str.as_ptr() as *const c_char; + unsafe { + c_ffi::SayHello(c_world); + } + } + + ``` + +4. Create the **BUILD.gn** file to define the dependency of the Rust module on the C module. + + ```GN + import("//build/ohos.gni") + + ohos_shared_library("c_lib") { + sources = [ "lib.c" ] + defines = [ "COMPONENT_IMPLEMENTATION" ] + } + + rust_bindgen("c_lib_bindgen") { + header = "lib.h" + } + + ohos_rust_executable("bindgen_test") { + deps = [ ":c_lib" ] + deps += [ ":c_lib_bindgen" ] + sources = [ "main.rs" ] + bindgen_output = get_target_outputs(":c_lib_bindgen") + inputs = bindgen_output + rustenv = [ "BINDGEN_RS_FILE=" + rebase_path(bindgen_output[0]) ] + crate_root = "main.rs" + } + ``` + +**Verification** + +![bindgen_test](./figures/bindgen_test.png) + + +## Using CXX + +### Calling Rust Interfaces by C++ + +1. In the Rust **lib.rs** file, add the C++ interfaces to be called in **mod ffi**, and add the interfaces in **extern "Rust"** to expose them to C++. + + ```rust + //! #[cxx::bridge] + #[cxx::bridge] + mod ffi{ + #![allow(dead_code)] + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] + struct Shared { + z: usize, + } + extern "Rust"{ + fn print_message_in_rust(); + fn r_return_primitive() -> usize; + fn r_return_shared() -> Shared; + fn r_return_rust_string() -> String; + fn r_return_sum(_: usize, _: usize) -> usize; + } + } + + fn print_message_in_rust(){ + println!("Here is a test for cpp call Rust."); + } + fn r_return_shared() -> ffi::Shared { + println!("Here is a message from Rust,test for ffi::Shared:"); + ffi::Shared { z: 1996 } + } + fn r_return_primitive() -> usize { + println!("Here is a message from Rust,test for usize:"); + 1997 + } + fn r_return_rust_string() -> String { + println!("Here is a message from Rust,test for String"); + "Hello World!".to_owned() + } + fn r_return_sum(n1: usize, n2: usize) -> usize { + println!("Here is a message from Rust,test for {} + {} is:",n1 ,n2); + n1 + n2 + } + + ``` + +2. Include **lib.rs.h** (converted from **lib.rs** by the CXX tool) in C++ code. + + ```c++ + #include + #include "build/rust/tests/test_cxx/src/lib.rs.h" + + int main(int argc, const char* argv[]) + { + int a = 2021; + int b = 4; + print_message_in_rust(); + std::cout << r_return_primitive() << std::endl; + std::cout << r_return_shared().z << std::endl; + std::cout << std::string(r_return_rust_string()) << std::endl; + std::cout << r_return_sum(a, b) << std::endl; + return 0; + } + ``` + +3. Create the **BUILD.gn** file. The underlying rust_cxx calls the CXX tool to convert the **lib.rs** file into **lib.rs.h** and **lib.rs.cc**. **ohos_rust_static_ffi** implements compilation of the Rust source code, and **ohos_executable** implements compilation of the C++ code. + + ``` + import("//build/ohos.gni") + import("//build/templates/rust/rust_cxx.gni") + + rust_cxx("test_cxx_exe_gen") { + sources = [ "src/lib.rs" ] + } + + ohos_rust_static_ffi("test_cxx_examp_rust") { + sources = [ "src/lib.rs" ] + deps = [ "//build/rust:cxx_rustdeps" ] + } + + ohos_executable("test_cxx_exe") { + sources = [ "main.cpp" ] + sources += get_target_outputs(":test_cxx_exe_gen") + + include_dirs = [ "${target_gen_dir}" ] + deps = [ + ":test_cxx_examp_rust", + ":test_cxx_exe_gen", + "//build/rust:cxx_cppdeps", + ] + } + ``` + +**Verification** +![cpp_call_rust](./figures/cpp_call_rust.png) + + +### Calling C++ by Rust + +1. Create the header file **client_blobstore.h**. + + ```c++ + #ifndef BUILD_RUST_TESTS_CLIENT_BLOBSTORE_H + #define BUILD_RUST_TESTS_CLIENT_BLOBSTORE_H + #include + #include "third_party/rust/cxx/include/cxx.h" + + namespace nsp_org { + namespace nsp_blobstore { + struct MultiBufs; + struct Metadata_Blob; + + class client_blobstore { + public: + client_blobstore(); + uint64_t put_buf(MultiBufs &buf) const; + void add_tag(uint64_t blobid, rust::Str add_tag) const; + Metadata_Blob get_metadata(uint64_t blobid) const; + + private: + class impl; + std::shared_ptr impl; + }; + + std::unique_ptr blobstore_client_new(); + } // namespace nsp_blobstore + } // namespace nsp_org + #endif + ``` + +2. Create the **client_blobstore.cpp** file. + + ```c++ + #include + #include + #include + #include + #include + #include "src/main.rs.h" + #include "build/rust/tests/test_cxx_rust/include/client_blobstore.h" + + namespace nsp_org { + namespace nsp_blobstore { + // Toy implementation of an in-memory nsp_blobstore. + // + // The real implementation of client_blobstore could be a large complex C++ + // library. + class client_blobstore::impl { + friend client_blobstore; + using Blob = struct { + std::string data; + std::set tags; + }; + std::unordered_map blobs; + }; + + client_blobstore::client_blobstore() : impl(new class client_blobstore::impl) {} + + // Upload a new blob and return a blobid that serves as a handle to the blob. + uint64_t client_blobstore::put_buf(MultiBufs &buf) const + { + std::string contents; + + // Traverse the caller's res_chunk iterator. + // + // In reality there might be sophisticated batching of chunks and/or parallel + // upload implemented by the nsp_blobstore's C++ client. + while (true) { + auto res_chunk = next_chunk(buf); + if (res_chunk.size() == 0) { + break; + } + contents.append(reinterpret_cast(res_chunk.data()), res_chunk.size()); + } + + // Insert into map and provide caller the handle. + auto res = std::hash {} (contents); + impl->blobs[res] = {std::move(contents), {}}; + return res; + } + + // Add add_tag to an existing blob. + void client_blobstore::add_tag(uint64_t blobid, rust::Str add_tag) const + { + impl->blobs[blobid].tags.emplace(add_tag); + } + + // Retrieve get_metadata about a blob. + Metadata_Blob client_blobstore::get_metadata(uint64_t blobid) const + { + Metadata_Blob get_metadata {}; + auto blob = impl->blobs.find(blobid); + if (blob != impl->blobs.end()) { + get_metadata.size = blob->second.data.size(); + std::for_each(blob->second.tags.cbegin(), blob->second.tags.cend(), + [&](auto &t) { get_metadata.tags.emplace_back(t); }); + } + return get_metadata; + } + + std::unique_ptr blobstore_client_new() + { + return std::make_unique(); + } + } // namespace nsp_blobstore + } // namespace nsp_org + + ``` + +3. In **ffi** of the **main.rs** file, use the macro **includes!** to import the header file **client_blobstore.h**. Then, the **main()** function of Rust can call the C++ interfaces in ffi mode. + + ```rust + //! test_cxx_rust + #[cxx::bridge(namespace = "nsp_org::nsp_blobstore")] + mod ffi { + // Shared structs with fields visible to both languages. + struct Metadata_Blob { + size: usize, + tags: Vec, + } + + // Rust types and signatures exposed to C++. + extern "Rust" { + type MultiBufs; + + fn next_chunk(buf: &mut MultiBufs) -> &[u8]; + } + + // C++ types and signatures exposed to Rust. + unsafe extern "C++" { + include!("build/rust/tests/test_cxx_rust/include/client_blobstore.h"); + + type client_blobstore; + + fn blobstore_client_new() -> UniquePtr; + fn put_buf(&self, parts: &mut MultiBufs) -> u64; + fn add_tag(&self, blobid: u64, add_tag: &str); + fn get_metadata(&self, blobid: u64) -> Metadata_Blob; + } + } + + // An iterator over contiguous chunks of a discontiguous file object. + // + // Toy implementation uses a Vec> but in reality this might be iterating + // over some more complex Rust data structure like a rope, or maybe loading + // chunks lazily from somewhere. + /// pub struct MultiBufs + pub struct MultiBufs { + chunks: Vec>, + pos: usize, + } + /// pub fn next_chunk + pub fn next_chunk(buf: &mut MultiBufs) -> &[u8] { + let next = buf.chunks.get(buf.pos); + buf.pos += 1; + next.map_or(&[], Vec::as_slice) + } + + /// fn main() + fn main() { + let client = ffi::blobstore_client_new(); + + // Upload a blob. + let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()]; + let mut buf = MultiBufs { chunks, pos: 0 }; + let blobid = client.put_buf(&mut buf); + println!("This is a test for Rust call cpp:"); + println!("blobid = {}", blobid); + + // Add a add_tag. + client.add_tag(blobid, "rust"); + + // Read back the tags. + let get_metadata = client.get_metadata(blobid); + println!("tags = {:?}", get_metadata.tags); + } + ``` + +4. Create the **BUILD.gn** file. Use CXX to convert **main.rs** into **lib.rs.h** and **lib.rs.cc**, which are used as the source code of **test_cxx_rust_staticlib**. Compile Rust **main.rs**, and add the dependency **test_cxx_rust_staticlib**. + + ``` + import("//build/ohos.gni") + + rust_cxx("test_cxx_rust_gen") { + sources = [ "src/main.rs" ] + } + + ohos_static_library("test_cxx_rust_staticlib") { + sources = [ "src/client_blobstore.cpp" ] + sources += get_target_outputs(":test_cxx_rust_gen") + include_dirs = [ + "${target_gen_dir}", + "//third_party/rust/cxx/v1/crate/include", + "include", + ] + deps = [ + ":test_cxx_rust_gen", + "//build/rust:cxx_cppdeps", + ] + } + + ohos_rust_executable("test_cxx_rust") { + sources = [ "src/main.rs" ] + deps = [ + ":test_cxx_rust_staticlib", + "//build/rust:cxx_rustdeps", + ] + } + ``` + +**Verification** +![rust_call_cpp](./figures/rust_call_cpp.png) diff --git a/en/device-dev/subsystems/subsys-build-cargo2gn-guide.md b/en/device-dev/subsystems/subsys-build-cargo2gn-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..fcf8a04804809485cbaed0cee49ca467272a4caf --- /dev/null +++ b/en/device-dev/subsystems/subsys-build-cargo2gn-guide.md @@ -0,0 +1,95 @@ +# Using Cargo2gn +## Overview + +Rust uses Cargo as its build system and package manager. **Cargo.toml** is the manifest file of Cargo. It contains metadata such as the name, version, and dependencies for crates (packages) in Rust. + +When used in OpenHarmony, **Cargo.toml** needs to be converted into **BUILD.gn** rules. cargo2gn is the tool that can achieve this purpose. It can convert one or more Rust libraries. + +## Converting a Single Library +1. Go to the directory of the rust library to be converted, for example, **bindgen**. + + ``` + cd openharmony/third_party/rust/bindgen + ``` + +2. Create the configuration file **cargo2gn.json**. + + ``` + { + "copy-out": true, + "run": true, + "add-workspace": true, + "cargo-bin": "/mnt/xxx/openharmony/prebuilts/rustc/linux-x86_64/current/bin" + } + ``` + +3. Run the following command to perform the conversion: + + ``` + python /mnt/xxx/openharmony/build/scripts/cargo2gn.py --config cargo2gn.json + ``` + + The conversion result is as follows: + + ``` + import("//build/templates/rust/ohos_cargo_crate.gni") + + ohos_cargo_crate("lib") { + crate_name = "bindgen" + crate_type = "rlib" + crate_root = "./lib.rs" + + sources = ["./lib.rs"] + edition = "2018" + cargo_pkg_version = "0.64.0" + cargo_pkg_authors = "Jyun-Yan You , Emilio Cobos Álvarez , Nick Fitzgerald , The Servo project developers" + cargo_pkg_name = "bindgen" + cargo_pkg_description = "Automatically generates Rust FFI bindings to C and C++ libraries." + deps = [ + "//third_party/rust/bitflags:lib", + "//third_party/rust/cexpr:lib", + "//third_party/rust/clang-sys:lib", + "//third_party/rust/lazy_static:lib", + "//third_party/rust/lazycell:lib", + "//third_party/rust/log:lib", + "//third_party/rust/peeking_take_while:lib", + "//third_party/rust/proc-macro2:lib", + "//third_party/rust/quote:lib", + "//third_party/rust/regex:lib", + "//third_party/rust/rustc-hash:lib", + "//third_party/rust/shlex:lib", + "//third_party/rust/syn:lib", + "//third_party/rust/which:lib", + ] + features = [ + "default", + "log", + "logging", + "static", + "which", + "which-rustfmt", + ] + build_root = "build.rs" + build_sources = ["build.rs"] + build_script_outputs = ["host-target.txt"] + } + ``` + + + +## Converting Multiple Libraries in Batches +1. Go to the **rust** directory. + + ``` + cd openharmony/third_party/rust + ``` +2. Add all the rust libraries to be converted to [workspace] in **Cargo.toml** in the **rust** directory. + + ``` + [workspace] + members = [ + "aho-corasick", + "memchr", + ] + ``` +3. Perform steps 2 and 3 in section "Converting a Single Library". diff --git a/en/device-dev/subsystems/subsys-build-module.md b/en/device-dev/subsystems/subsys-build-module.md index bc5ec28957f446b4b4ca8b221580467083d2963f..49f58da2bdc3b0b8577b178eb0b418cec59eb3d3 100644 --- a/en/device-dev/subsystems/subsys-build-module.md +++ b/en/device-dev/subsystems/subsys-build-module.md @@ -23,6 +23,17 @@ ohos_app_scope ohos_js_assets ohos_resources +# Rust templates +ohos_rust_executable +ohos_rust_shared_library +ohos_rust_static_library +ohos_rust_proc_macro +ohos_rust_shared_ffi +ohos_rust_static_ffi +ohos_rust_cargo_crate +ohos_rust_systemtest +ohos_rust_unittest + # Other templates # Configuration file ohos_prebuilt_etc @@ -33,7 +44,7 @@ ohos_sa_profile You are advised to use the OpenHarmony customized templates. -### C/C++ Template Examples +### C/C++ Template Example The .gni file corresponding to the templates starting with **ohos** is located in **openharmony/build/templates/cxx/cxx.gni**. @@ -69,7 +80,7 @@ ohos_shared_library("helloworld") { cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. integer_overflow = [boolean] # Whether to enable the integer overflow check. - boundary_sanitize = [boolean] # Whether to enable the bounds check. + boundary_sanitize = [boolean] # Whether to enable the boundary check. ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -91,12 +102,12 @@ ohos_shared_library("helloworld") { } ``` -**ohos_static_library** example: +**ohos_static_library** example ```shell import("//build/ohos.gni") ohos_static_library("helloworld") { - sources = ["file"] # Source code in .c format. + sources = ["file"] # .c files. include_dirs = ["dir"] # Directories to be included. configs = [] # Configuration. deps = [] # Define dependent modules that belong to the same component. @@ -114,11 +125,11 @@ ohos_static_library("helloworld") { # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. sanitize = { # Sanitizer settings - cfi = [boolean] # Whether to enable the CFI check. + cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. integer_overflow = [boolean] # Whether to enable the integer overflow check. - boundary_sanitize = [boolean] # Whether to enable the bounds check. - ubsan = [boolean] # Whether to enable some UBSAN options. + boundary_sanitize = [boolean] # Whether to enable the boundary check. + ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -139,7 +150,7 @@ ohos_static_library("helloworld") { ```shell import("//build/ohos.gni") ohos_executable("helloworld") { - configs = [] # Configuration. + configs = [] # Configuration. part_name = [string] # Component name. subsystem_name = [string] # Subsystem name. deps = [] # Define dependent modules that belong to the same component. @@ -153,10 +164,10 @@ ohos_executable("helloworld") { # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. sanitize = { # Sanitizer settings - cfi = [boolean] # Whether to enable the CFI check. + cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. integer_overflow = [boolean] # Whether to enable the integer overflow check. - boundary_sanitize = [boolean] # Whether to enable the bounds check. + boundary_sanitize = [boolean] # Whether to enable the boundary check. ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -181,32 +192,32 @@ ohos_executable("helloworld") { } ``` -**ohos_source_set** example: +**ohos_source_set** example ```shell import("//build/ohos.gni") ohos_source_set("helloworld") { - sources = ["file"] # Source code in .c format. - include_dirs = [] # Directories to be included. - configs = [] # Configuration. - public = [] # Header files. + sources = ["file"] # .c files. + include_dirs = [] # Directories to be included. + configs = [] # Configuration. + public = [] # .h header files. defines = [] public_configs = [] - part_name = [string] # Component name. - subsystem_name = [string] # Subsystem name. - deps = [] # Define dependent modules that belong to the same component. + part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + deps = [] # Define dependent modules that belong to the same component. - external_deps = [ # Define dependent modules that belong to different components. - "part_name:module_name", # The value is in the Component_name:Module_name format. - ] # The dependent modules must be declared in inner_kits by the dependent component. + external_deps = [ # Define dependent modules that belong to different components. + "part_name:module_name", # The value is in the Component_name:Module_name format. + ] # The dependent modules must be declared in inner_kits by the dependent component. # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. sanitize = { # Sanitizer settings - cfi = [boolean] # Whether to enable the CFI check. + cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. integer_overflow = [boolean] # Whether to enable the integer overflow check. - boundary_sanitize = [boolean] # Whether to enable the bounds check. + boundary_sanitize = [boolean] # Whether to enable the boundary check. ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -226,72 +237,71 @@ ohos_source_set("helloworld") { } ``` -> **NOTE** -> -> - Only **sources** and **part_name** are mandatory. -> - For details about the Sanitizer configuration, see [Using Sanitizer](subsys-build-reference.md#using-sanitizer). +**NOTE**
+ - Only **sources** and **part_name** are mandatory. + - For details about the Sanitizer configuration, see [Using Sanitizer](subsys-build-reference.md#using-sanitizer). -### Prebuilt Template Examples +### Prebuilt Template Example The .gni file of the prebuilt templates is located in **openharmony/build/templates/cxx/prebuilt.gni**. -**ohos_prebuilt_executable** example: +**ohos_prebuilt_executable** example ```shell import("//build/ohos.gni") ohos_prebuilt_executable("helloworld") { - sources = ["file"] # Source. + sources = ["file"] # Source. output = [] - install_enable = [boolean] + install_enable = [boolean] - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. public_configs = [] - subsystem_name = [string] # Subsystem name. - part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + part_name = [string] # Component name. testonly = [boolean] visibility = [] install_images = [] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. symlink_target_name = [] - license_file = [] # A .txt file. + license_file = [] # A .txt file. license_as_sources = [] } ``` -**ohos_prebuilt_shared_library** example: +**ohos_prebuilt_shared_library** example ```shell import("//build/ohos.gni") ohos_prebuilt_shared_library("helloworld") { - sources = ["file"] # .so files. + sources = ["file"] # .so files. output = [] install_enable = [boolean] - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. public_configs = [] - subsystem_name = [string] # Subsystem name. - part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + part_name = [string] # Component name. testonly = [boolean] visibility = [] install_images = [] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. symlink_target_name = [string] - license_file = [string] # A .txt file. + license_file = [string] # A .txt file. license_as_sources = [] } ``` -**ohos_prebuilt_static_library** example: +**ohos_prebuilt_static_library** example ```shell import("//build/ohos.gni") @@ -312,13 +322,15 @@ ohos_prebuilt_static_library("helloworld") { } ``` ->**NOTE**
Only **sources** and **part_name** are mandatory. +![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: Only **sources** and **part_name** are mandatory. ### HAP Templates -For details, see [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md). +For details about the HAP templates, see [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md). +### Rust Templates +For details about the Rust templates, see [Rust Module Configuration Rules and Guide](subsys-build-rust-compilation.md). ### Other Templates @@ -329,14 +341,14 @@ import("//build/ohos.gni") ohos_prebuilt_etc("helloworld") { # The most common attributes of the ohos_prebuilt_etc template. sources = ["file"] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - subsystem_name = [string] # Subsystem name. - part_name = [string] # (Mandatory) Component name. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + subsystem_name = [string] # Subsystem name. + part_name = [string] # (Mandatory) Component name. install_images = [] - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. # Uncommon attributes of the ohos_prebuilt_etc template: - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. testonly = [boolean] visibility = [] public_configs = [] @@ -357,7 +369,7 @@ ohos_sa_profile("helloworld") { } ``` -> **NOTE**
Only **sources** and **part_name** are mandatory. +![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: Only **sources** and **part_name** are mandatory. ## Adding and Building a Module @@ -379,47 +391,49 @@ The following figure shows the logic for adding a module. Generally, you need to ```shell { - "name": "@ohos/, # HPM component name, in the "@Organization/Component_name" format. - "description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions. - "version": "3.1", # Version, which must be the same as the version of OpenHarmony. - "license": "MIT", # Component license. - "publishAs": "code-segment", # HPM package release mode. The default value is code-segment. + "name": "@ohos/, # HPM component name, in the "@Organization/Component_name" format. + "description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions. + "version": "3.1", # Version, which must be the same as the version of OpenHarmony. + "license": "MIT", # Component license. + "publishAs": "code-segment", # HPM package release mode. The default value is code-segment. "segment": { "destPath": "third_party/nghttp2" - }, # Code restoration path (source code path) set when publishAs is code-segment. - "dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty. - "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty. + }, # Code restoration path (source code path) set when publishAs is code-segment. + "dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty. + "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty. "licensePath": "COPYING", "readmePath": { "en": "README.rst" }, - "component": { # Component attributes. - "name": "", # Component name. - "subsystem": "", # Subsystem to which the component belongs. - "syscap": [], # System capabilities provided by the component for applications. - "features": [], # List of configurable features of the component. Generally, this parameter corresponds to sub_component in build. - "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, standard, or their combinations. - "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. - "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. + "component": { # Component attributes. + "name": "", # Component name. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of configurable features of the component. Generally, this parameter corresponds to sub_component in build. + "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, standard, or their combinations. + "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. + "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. "deps": { - "components": [ # Other components on which this component depends. - "third_party": [ # Third-party open-source software on which this component depends. + "components": [ # Other components on which this component depends. + "third_party": [ # Third-party open-source software on which this component depends. }, - "build": { # Build-related configuration. + "build": { # Build-related configuration. "sub_component": [ - "//foundation/arkui/napi:napi_packages", # Existing module 1. - "//foundation/arkui/napi:napi_packages_ndk"# Existing module 2. - "//foundation/arkui/napi:new" # Module to add. - ], # Component build entry. Configure the module here. - "inner_kits": [], # APIs between components. - "test": [] # Entry for building the component's test cases. + "//foundation/arkui/napi:napi_packages", # Existing module 1. + "//foundation/arkui/napi:napi_packages_ndk" # Existing module 2. + "//foundation/arkui/napi:new" # Module to add. + ], # Component build entry. Configure the module here. + "inner_kits": [], # APIs between components. + "test": [] # Entry for building the component's test cases. } } } ``` - > **NOTE**
The **bundle.json** file must be in the folder of the corresponding subsystem. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > The **bundle.json** file must be in the folder of the corresponding subsystem. 3. Start the build and check whether a .so file or binary file is generated. @@ -429,16 +443,16 @@ The following figure shows the logic for adding a module. Generally, you need to 2. Create a **bundle.json** file in the folder of the corresponding subsystem. -3. Add the new component to the end of existing components in **vendor/{product_company}/{product_name}/config.json**. +3. Add the new component to the end of existing components in **vendor/{product_company}/{product-name}/config.json**. ```shell "subsystems": [ { "subsystem": "Subsystem to which the component belongs", "components": [ - {"component": "Component 1 name", "features":[]}, # Existing component 1 in the subsystem - { "component": "Component 2 name", "features":[] }, # Existing component 2 in the subsystem - {"component": "New component name", "features":[]} # New component in the subsystem + {"component": "Component 1 name", "features":[]}, # Existing component 1 in the subsystem + { "component": "Component 2 name", "features":[] }, # Existing component 2 in the subsystem + {"component": "New component name", "features":[]} # New component in the subsystem ] }, . @@ -476,7 +490,7 @@ The following figure shows the logic for adding a module. Generally, you need to The **subsystem_config.json** file defines the subsystems and their directories. When adding a subsystem, specify **path** and **name** for the subsystem. -4. If **product_name** in the **vendor/{product_company}/{product_name}** directory is **hispark_taurus_standard**, add the new component information to the end of existing components in the **config.json** file. +4. If **product-name** in the **vendor/{product_company}/{product-name}** directory is **hispark_taurus_standard**, add the new component information to the end of existing components in the **config.json** file. ```shell "subsystems": [ @@ -517,19 +531,19 @@ The following figure shows the logic for adding a module. Generally, you need to You can start the build by using the [CLI or hb tool](subsys-build-all.md#build-commands). The following uses the CLI as an example: -You can run the **--build-target** *Module_name* command to build a module separately. + You can run the **--build-target** *Module_name* command to build a module separately. ```shell ./build.sh --build-target Module_name ``` -You can also build a product. For example, to build hispark_taurus_standard, run the following command: + You can also build a product. For example, to build hispark_taurus_standard, run the following command: ```shell ./build.sh --product-name hispark_taurus_standard --build-target Module_name --ccache ``` -You can also build the component to which the module belongs. + You can also build the component to which the module belongs. ```shell ./build.sh --product-name hispark_taurus_standard --build-target musl --build-target Module_name --ccache diff --git a/en/device-dev/subsystems/subsys-build-rust-compilation.md b/en/device-dev/subsystems/subsys-build-rust-compilation.md new file mode 100644 index 0000000000000000000000000000000000000000..b02f52d3d27110bc29f29a3fc245e92af78ed0db --- /dev/null +++ b/en/device-dev/subsystems/subsys-build-rust-compilation.md @@ -0,0 +1,369 @@ +# Rust Module Configuration Rules and Guide + +## Introduction + +Rust is a static, strongly typed programming language. It has advantages such as secure memory management, high running performance, and native support for multi-thread development. Rust uses Cargo to create projects and compile and build Rust code. + +To integrate C/C++ code and improve the build speed, OpenHarmony uses Generate Ninja (GN) and Ninja as its build system. GN has simple and easy-to-use build language, and Ninja provides direct and efficient assembly-level build rules. + +To integrate Rust code and maximize the interaction between the C/C++ code used in OpenHarmony and Rust, OpenHarmony uses GN as a unified build tool to build Rust source code files (xxx.rs) and is added with features such as interoperability with C/C++, compile time lints, test, IDL conversion, third-party library integration, and IDE. In addition, the GN framework is extended to support automatic interface conversion, which greatly simplifying development. + +### Basic Concepts + +| Term | Description | +| ----- | ------------------------------------------------------------ | +| Cargo | Cargo is an official build tool used by Rust. It allows Rust projects to declare dependencies and ensures reproducible builds.| +| crate | Crate is a unit that can be independently compiled. | +| Lint| Lint is a code analysis tool used to flag programming errors, bugs, stylistic errors, and suspicious constructs. It performs extensive error analysis on programs.| + + + +## Configure Rules +OpenHarmony provides a variety of GN templates for compiling Rust executables, dynamic libraries, and static libraries. The following table describes the templates. + +| GN Template | Description | Output | +| ------------------------ | ----------------- | ----------------------------------------------- | +| ohos_rust_executable | Rust executable file. | Rust executable file, without the file name extension. | +| ohos_rust_shared_library | Rust dynamic library. | Rust dylib dynamic library, with the default file name extension **.dylib.so**. | +| ohos_rust_static_library | Rust static library. | Rust rlib static library, with the default file name extension **.rlib**. | +| ohos_rust_proc_macro | Rust proc_macro library. | Rust proc_macro library, with the default file name extension **.so**. | +| ohos_rust_shared_ffi | Rust Foreign Function Interface (FFI) dynamic library. | Rust cdylib dynamic library, which is called by the C/C++ module. The default file name extension is **.so**.| +| ohos_rust_static_ffi | Rust FFI static library. | Rust staticlib library, which is called by the C/C++ module. The default file name extension is **.a**. | +| ohos_rust_cargo_crate | Third-party Cargo crate.| Third-party Rust crates, which support rlib, dylib, and bin. | +| ohos_rust_systemtest | Rust system test cases. | Executable system test cases for Rust, without the file name extension. | +| ohos_rust_unittest | Rust unit test cases. | Executable unit test cases for Rust, without the file name extension. | + + + +## Configuration Guide +The configuration of the Rust module is similar to that of the C/C++ module. For details, see [Module Configuration Rules](subsys-build-module.md). The following provides examples of using different Rust templates. +### Configuring a Rust Static Library +The following example shows how to use the **ohos_rust_executable** and **ohos_rust_static_library** templates to build a binary executable and a static rlib library, respectively. The executable depends on the static library. + +The procedure is as follows: + +1. Create **build/rust/tests/test_rlib_crate/src/simple_printer.rs**. + + ```rust + //! simple_printer + + /// struct RustLogMessage + + pub struct RustLogMessage { + /// i32: id + pub id: i32, + /// String: msg + pub msg: String, + } + + /// function rust_log_rlib + pub fn rust_log_rlib(msg: RustLogMessage) { + println!("id:{} message:{:?}", msg.id, msg.msg) + } + ``` + +2. Create **build/rust/tests/test_rlib_crate/src/main.rs**. + + ```rust + //! rlib_crate example for Rust. + + extern crate simple_printer_rlib; + + use simple_printer_rlib::rust_log_rlib; + use simple_printer_rlib::RustLogMessage; + + fn main() { + let msg: RustLogMessage = RustLogMessage { + id: 0, + msg: "string in rlib crate".to_string(), + }; + rust_log_rlib(msg); + } + ``` + +3. Configure the GN build script **build/rust/tests/test_rlib_crate/BUILD.gn**. + + ``` + import("//build/ohos.gni") + + ohos_rust_executable("test_rlib_crate") { + sources = [ "src/main.rs" ] + deps = [ ":simple_printer_rlib" ] + } + + ohos_rust_static_library("simple_printer_rlib") { + sources = [ "src/simple_printer.rs" ] + crate_name = "simple_printer_rlib" + crate_type = "rlib" + features = [ "std" ] + } + ``` + +4. Run the **BUILD.gn** to generate the build targets. + + ![test_rlib_crate](./figures/test_rlib_crate.png) + +### Configuring a Third-Party Library +The following example shows how to use the **ohos_rust_executable** and **ohos_rust_cargo_crate** templates to build a third-party static rlib library whose code contains a prebuilt file **build.rs**. + +The procedure is as follows: + +1. Create **build/rust/tests/test_rlib_cargo_crate/crate/src/lib.rs**. + + ```rust + include!(concat!(env!("OUT_DIR"), "/generated/generated.rs")); + + pub fn say_hello_from_crate() { + assert_eq!(run_some_generated_code(), 45); + #[cfg(is_new_rustc)] + println!("Is new rustc"); + #[cfg(is_old_rustc)] + println!("Is old rustc"); + #[cfg(is_ohos)] + println!("Is ohos"); + #[cfg(is_mac)] + println!("Is darwin"); + #[cfg(has_feature_a)] + println!("Has feature_a"); + #[cfg(not(has_feature_a))] + panic!("Wasn't passed feature_a"); + #[cfg(not(has_feature_b))] + #[cfg(test_a_and_b)] + panic!("feature_b wasn't passed"); + #[cfg(has_feature_b)] + #[cfg(not(test_a_and_b))] + panic!("feature_b was passed"); + } + + #[cfg(test)] + mod tests { + /// Test features are passed through from BUILD.gn correctly. This test is the target configuration. + #[test] + #[cfg(test_a_and_b)] + fn test_features_passed_target1() { + #[cfg(not(has_feature_a))] + panic!("feature a was not passed"); + #[cfg(not(has_feature_b))] + panic!("feature b was not passed"); + } + + #[test] + fn test_generated_code_works() { + assert_eq!(crate::run_some_generated_code(), 45); + } + } + ``` + +2. Create **build/rust/tests/test_rlib_cargo_crate/crate/src/main.rs**. + + ```rust + pub fn main() { + test_rlib_crate::say_hello_from_crate(); + } + ``` + +3. Create **build/rust/tests/test_rlib_cargo_crate/crate/build.rs**. + + ```rust + use std::env; + use std::path::Path; + use std::io::Write; + use std::process::Command; + use std::str::{self, FromStr}; + + fn main() { + println!("cargo:rustc-cfg=build_script_ran"); + let my_minor = match rustc_minor_version() { + Some(my_minor) => my_minor, + None => return, + }; + + if my_minor >= 34 { + println!("cargo:rustc-cfg=is_new_rustc"); + } else { + println!("cargo:rustc-cfg=is_old_rustc"); + } + + let target = env::var("TARGET").unwrap(); + + if target.contains("ohos") { + println!("cargo:rustc-cfg=is_ohos"); + } + if target.contains("darwin") { + println!("cargo:rustc-cfg=is_mac"); + } + + let feature_a = env::var_os("CARGO_FEATURE_MY_FEATURE_A").is_some(); + if feature_a { + println!("cargo:rustc-cfg=has_feature_a"); + } + let feature_b = env::var_os("CARGO_FEATURE_MY_FEATURE_B").is_some(); + if feature_b { + println!("cargo:rustc-cfg=has_feature_b"); + } + + // Tests used to verify whether Cargo features are enabled. + assert!(Path::new("build.rs").exists()); + assert!(Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("build.rs").exists()); + assert!(Path::new(&env::var_os("OUT_DIR").unwrap()).exists()); + + // Ensure that the following env var is set. + env::var_os("CARGO_CFG_TARGET_ARCH").unwrap(); + + generate_some_code().unwrap(); + } + + fn generate_some_code() -> std::io::Result<()> { + let test_output_dir = Path::new(&env::var_os("OUT_DIR").unwrap()).join("generated"); + let _ = std::fs::create_dir_all(&test_output_dir); + // Test that environment variables from .gn files are passed to build scripts. + let preferred_number = env::var("ENV_VAR_FOR_BUILD_SCRIPT").unwrap(); + let mut file = std::fs::File::create(test_output_dir.join("generated.rs"))?; + write!(file, "fn run_some_generated_code() -> u32 {{ {} }}", preferred_number)?; + Ok(()) + } + + fn rustc_minor_version() -> Option { + let rustc_bin = match env::var_os("RUSTC") { + Some(rustc_bin) => rustc_bin, + None => return None, + }; + + let output = match Command::new(rustc_bin).arg("--version").output() { + Ok(output) => output, + Err(_) => return None, + }; + + let rustc_version = match str::from_utf8(&output.stdout) { + Ok(rustc_version) => rustc_version, + Err(_) => return None, + }; + + let mut pieces = rustc_version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + + let next_var = match pieces.next() { + Some(next_var) => next_var, + None => return None, + }; + + u32::from_str(next_var).ok() + } + ``` + +4. Configure the GN build script **build/rust/tests/test_rlib_cargo_crate/BUILD.gn**. + + ``` + import("//build/templates/rust/ohos_cargo_crate.gni") + + ohos_cargo_crate("target") { + crate_name = "test_rlib_crate" + crate_root = "crate/src/lib.rs" + sources = [ "crate/src/lib.rs" ] + + #To generate the build_script binary + build_root = "crate/build.rs" + build_sources = [ "crate/build.rs" ] + build_script_outputs = [ "generated/generated.rs" ] + + features = [ + "my-feature_a", + "my-feature_b", + "std", + ] + rustflags = [ + "--cfg", + "test_a_and_b", + ] + rustenv = [ "ENV_VAR_FOR_BUILD_SCRIPT=45" ] + } + + # Exists to test the case that a single crate has both a library and a binary + ohos_cargo_crate("test_rlib_crate_associated_bin") { + crate_root = "crate/src/main.rs" + crate_type = "bin" + sources = [ "crate/src/main.rs" ] + + #To generate the build_script binary + build_root = "crate/build.rs" + build_sources = [ "crate/build.rs" ] + features = [ + "my-feature_a", + "my-feature_b", + "std", + ] + rustenv = [ "ENV_VAR_FOR_BUILD_SCRIPT=45" ] + deps = [ ":target" ] + } + ``` + +5. Run the **BUILD.gn** to generate the build target. + + ![test_rlib_cargo_crate](./figures/test_rlib_cargo_crate.png) + +### Other Configuration Examples +You can find the Rust module configuration examples in the **build/rust/tests** directory. +| Directory | Description | +| -------------------------------------------- | ------------------------------------------------------------ | +| build/rust/tests/test_bin_crate | Tests the build of an executable file on the host platform and running of the executable file on the target platform. | +| build/rust/tests/test_static_link | Tests the static linking of an executable file to a standard library. | +| build/rust/tests/test_dylib_crate | Tests the build of a dynamic library and dynamic linking. | +| build/rust/tests/test_rlib_crate | Tests the build of a static library and static linking. | +| build/rust/tests/test_proc_macro_crate | Tests the build of Rust process macros and the linking function. Test cases are provided for different types of macros. | +| build/rust/tests/test_cdylib_crate | Tests the generation of Rust FFI bindings to a C/C++ dynamic library. | +| build/rust/tests/test_staticlib_crate | Tests the generation of Rust FFI bindings to a C/C++ static library. | +| build/rust/tests/test_rust_ut | Tests the Rust code unit test template. | +| build/rust/tests/test_rust_st | Tests the Rust code system test template. | +| build/rust/tests/test_bin_cargo_crate | Tests the build and running of a Rust third-party executable file. The third-party code contains the **build.rs**. | +| build/rust/tests/test_rlib_cargo_crate | Tests the build of a Rust third-party static library and static linking. The third-party code contains the **build.rs**. | +| build/rust/tests/test_proc_macro_cargo_crate | Tests the build of Rust third-party process macros and linking. The third-party code contains the **build.rs**. | + +## Reference + +### Feature Examples + +#### Linking a C/C++ library in Rust Source Code +By default, the dynamic library of the OpenHarmony C/C++ module is in the **.z.so** format. However, when the Rust **-l** command is executed, only the dynamic library in the **.so** format is linked by default. If a C/C++ dynamic library is used as the dependency, you need to add **output_extension = "so"** to the GN build script of the dynamic library to make the generated dynamic library be named with **.so** instead of **.z.so**. + +If a dynamic library is directly linked in the Rust source code, the dynamic library must be in **.so** format. In this case, use the dynamic library name without "lib". The following is an example of linking **libhilog.so** in the Rust source code. + +```rust +#[link(name = "hilog")] +``` +#### Using externs +If a module depends on the binary rlib library, you can use the **externs** attribute. +``` +executable("foo") { + sources = [ "main.rs" ] + externs = [{ # Convert it to `--extern bar=path/to/bar.rlib` during the compilation. + crate_name = "bar" + path = "path/to/bar.rlib" + }] +} +``` +### Lint Rules +The OpenHarmony framework supports two types of lints: rustc lints and Clippy lints. Each type of lint has three levels: openharmony (highest), vendor, and none (lowest). + +When configuring the Rust module, you can specify the lint level in **rustc_lints** or **clippy_lints**. +If **rustc_lints** or **clippy_lints** is not configured in the module, the lint level is matched based on the module path. Different restrictions apply to the syntax specifications of Rust code in different directories. Therefore, you need to pay attention to the path of the module when configuring the Rust module to build in OpenHarmony. + +#### Levels of rustc Lints and Clippy Lints +| **Lint Type**| **Module Attribute**| **Lint Level**| **Lint Level Flag**| **Lint Content** | +| ------------- | ------------ | ------------- | ----------------- | ------------------------------------------------------------ | +| rustc lints | rustc_lints | openharmony | RustOhosLints | "-A deprecated", "-D missing-docs", "-D warnings" | +| rustc lints | rustc_lints | vendor | RustcVendorLints | "-A deprecated", "-D warnings" | +| rustc lints | rustc_lints | none | allowAllLints | "-cap-lints allow" | +| Clippy lints | clippy_lints | openharmony | ClippyOhosLints | "-A clippy::type-complexity", "-A clippy::unnecessary-wraps", "-A clippy::unusual-byte-groupings", "-A clippy::upper-case-acronyms" | +| Clippy lints | clippy_lints | vendor | ClippyVendorLints | "-A clippy::complexity", "-A Clippy::perf", "-A clippy::style" | +| Clippy lints | clippy_lints | none | allowAllLints | "--cap-lints allow" | + +#### Mapping Between Code Paths and Lint Levels +| Path | Lint Level | +| ---------- | ----------- | +| thirdparty | none | +| prebuilts | none | +| vendor | vendor | +| device | vendor | +| others | openharmony | diff --git a/en/device-dev/subsystems/subsys-dfx-hidumper.md b/en/device-dev/subsystems/subsys-dfx-hidumper.md index 5c6bc09ecf931c46bb458e6d1c19111431bf0ddb..bd1c46cdd275fc17d2858d9d2d2c65acd67633ee 100644 --- a/en/device-dev/subsystems/subsys-dfx-hidumper.md +++ b/en/device-dev/subsystems/subsys-dfx-hidumper.md @@ -115,7 +115,7 @@ The procedure is as follows: hidumper -s 3008 ``` -9. Run the **hidumper -e** command to obtain the crash information generated by the FaultLoger module. +9. Run the **hidumper -e** command to obtain the crash information generated by the FaultLogger module. ``` hidumper -e @@ -163,6 +163,22 @@ The procedure is as follows: ``` hidumper --mem [pid] ``` + The following table describes the parameters in the first column of the command output when the PID of the process is specified. + | Name | Description| + |----------------|----| + | GL | GPU memory. | + | Graph | Graphics memory. | + | ark ts heap | Memory usage of the ArkTS heap. | + | guard | Memory occupied by the protection section. | + | native heap | Heap memory. | + | AnonPage other | Memory occupied by other pages that are not mapped to files. | + | stack | Stack memory. | + | .hap | Memory occupied by the application. | + | .db | Memory occupied by the **.db** files loaded by processes. | + | .so | Memory occupied by the **.so** dynamic library files loaded by processes. | + | .ttf | Memory occupied by the **.ttf** font files loaded by processes. | + | dev | Memory occupied by the files that are named with the **/dev** prefix and loaded by processes. | + | FilePage other | Memory occupied by other pages that are mapped to files. | 17. Run the **hidumper --zip** command to compress data to the **/data/dumper** directory. diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md index 2f5cd08ffab5ac1499f9e4a6e324caf1de64f106..76d048f3056769b13338e3a7629d6be00d2513ae 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md @@ -81,10 +81,6 @@ The **condition** parameter must be in the specified JSON string format. For exa "and":[ {"param":"type_","op":">","value":0}, {"param":"uid_","op":"=","value":1201} - ], - "or":[ - {"param":"NAME","op":"=","value":"SysEventService"}, - {"param":"NAME","op":"=","value":"SysEventSource"} ] } } @@ -93,7 +89,6 @@ The **condition** parameter must be in the specified JSON string format. For exa - The **version** field is mandatory, indicating the supported version of the input condition. Currently, only **V1** is supported. - The **condition** field is mandatory, indicating the input condition. - The **and** field is optional, indicating the AND relationship between conditions. - - The **or** field is optional, indicating the OR relationship between conditions. - The **param** field is mandatory, indicating the parameter name for condition matching. The value must be a string. - The **op** field is mandatory, indicating the parameter comparison operator for condition matching. The value must be a string. Supported comparison operators include the following: =, >, <, >=, and <=. - The **value** field is mandatory, indicating the parameter value for condition matching. The value must be a string or an integer. diff --git a/en/device-dev/subsystems/subsys-power-default-sleep-behavior-customization.md b/en/device-dev/subsystems/subsys-power-default-sleep-behavior-customization.md new file mode 100644 index 0000000000000000000000000000000000000000..032395511926c8466dd714b79687d08bb3222085 --- /dev/null +++ b/en/device-dev/subsystems/subsys-power-default-sleep-behavior-customization.md @@ -0,0 +1,161 @@ +# Default Hibernation Behavior Customization + +## Overview + +### Introduction + +By default, after a device screen is turned off, OpenHarmony starts the running lock loop detection thread and then enters the hibernation state. For different devices, the mode of turning off the screen is different, which can be closing the lid, setting a timeout, or pressing the power button. Besides, the default hibernation behavior is also different, which can be performing no action, powering off the screen, or entering the hibernation state. To address this issue, OpenHarmony provides the default hibernation behavior customization function, allowing you to customize the default hibernation behavior depending on your hardware specifications. + +### Constraints + +The configuration paths for battery level customization are subject to the configuration policy. +The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy. + +## How to Develop + +### Setting Up the Environment + +**Hardware requirements:** + +Development board running the standard system, for example, the DAYU200 or Hi3516D V300 open source suite. + +**Environment requirements:** + +For details about the requirements on the Linux environment, see [Quick Start](../quick-start/quickstart-overview.md). + +### Getting Started with Development + +The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568) as an example to illustrate default hibernation behavior customization. + +1. Create the `power_manager` folder in the product directory [/vendor/hihope/rk3568](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568). + +2. Create a target folder by referring to the [default folder of hibernation behavior configuration](https://gitee.com/openharmony/powermgr_power_manager/tree/master/services/native/profile), and install it in `/vendor/hihope/rk3568/power_manager`. The content is as follows: + + ```text + profile + ├── BUILD.gn + ├── power_suspend.json + ``` + +3. Write the custom `power_suspend.json` file that contains the custom default hibernation behavior. The following is an example of hibernation behavior configuration: + + ```json + { + "powerkey": { + "action": 1, + "delayMs": 0 + }, + "timeout": { + "action": 1, + "delayMs": 0 + }, + "lid": { + "action": 1, + "delayMs": 0 + }, + "switch": { + "action": 1, + "delayMs": 0 + } + } + ``` + + **Table 1** Description of hibernation sources + + | Hibernation Source| Description| + | -------- | -------- | + | powerkey | Hibernation by power button| + | timeout | Hibernation by timeout| + | lid | Hibernation by lid| + | switch | Hibernation by switch| + + **Table 2** Description of the hibernation source configuration + + | Item| Description| + | -------- | -------- | + | action | Action to take after the screen is turned off. Set this parameter to an enumerated value. For details, see Table 3.| + | delayMs | Delay, in ms.| + + **Table 3** Description of action + + | action | Value| Description| + | -------- | -------- | -------- | + | ACTION_NONE | 0 | No action.| + | ACTION_AUTO_SUSPEND | 1 | Automatically entering the sleep mode.| + | ACTION_FORCE_SUSPEND | 2 | Forcibly entering the sleep mode.| + | ACTION_HIBERNATE | 3 | Entering the hibernation state.| + | ACTION_SHUTDOWN | 4 | Shutting down the system.| + +4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/BUILD.gn) file in the default folder of hibernation behavior configuration to pack the `power_suspend.json` file to the `/vendor/etc/power_config` directory. The configuration is as follows: + + ```shell + import("//build/ohos.gni") # Reference build/ohos.gni. + + ohos_prebuilt_etc("suspend_config") { + source = "power_suspend.json" + relative_install_dir = "power_config" + install_images = [ chipset_base_dir ] # Required configuration for installing the battery_config.json file in the vendor directory. + part_name = "product_rk3568" # Set part_name to product_rk3568 for subsequent build. + } + ``` + +5. Add the build target to `module_list` in [ohos.build](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/ohos.build) in the `/vendor/hihope/rk3568` directory. For example: + + ```json + { + "parts": { + "product_rk3568": { + "module_list": [ + "//vendor/hihope/rk3568/default_app_config:default_app_config", + "//vendor/hihope/rk3568/image_conf:custom_image_conf", + "//vendor/hihope/rk3568/preinstall-config:preinstall-config", + "//vendor/hihope/rk3568/resourceschedule:resourceschedule", + "//vendor/hihope/rk3568/etc:product_etc_conf", + "//vendor/hihope/rk3568/power_manager/profile:wakeup_config" // Add the configuration for building of suspend_config. + ] + } + }, + "subsystem": "product_hihope" + } + ``` + In the preceding code, `//vendor/hihope/rk3568/power_manager/` is the folder path, `profile` is the folder name, and `suspend_config` is the build target. + +6. Build the customized version by referring to [Quick Start](../quick-start/quickstart-overview.md). + + ```shell + ./build.sh --product-name rk3568 --ccache + ``` + +7. Burn the customized version to the DAYU200 development board. + +### Debugging and Verification + +1. Customize hibernation sources in the `power_suspend.json` file. + ```json + { + "powerkey": { + "action": 4, + "delayMs": 0 + }, + "timeout": { + "action": 1, + "delayMs": 0 + }, + "lid": { + "action": 1, + "delayMs": 0 + }, + "switch": { + "action": 1, + "delayMs": 0 + } + } + ``` + +2. Power on the device, and then press the power button. + + The device is powered off. + +3. Power on the device again, and then wait for a while. + + The device screen is turned off. diff --git a/en/device-dev/subsystems/subsys-power-stats-power-average-customization.md b/en/device-dev/subsystems/subsys-power-stats-power-average-customization.md index d7867ed30ad70c2088416d5668441803a4d6ebfb..384b4350f417afc69717d0a4a98102f6ce66d4f5 100644 --- a/en/device-dev/subsystems/subsys-power-stats-power-average-customization.md +++ b/en/device-dev/subsystems/subsys-power-stats-power-average-customization.md @@ -4,7 +4,7 @@ ### Introduction -By default, OpenHarmony provides the power consumption statistics feature. However, the power consumption benchmarks vary according to hardware specifications of different products. To address this issue, OpenHarmony provides the power consumption statistics customization function, allowing you to customize power consumption benchmarks depending on your hardware specifications. +By default, OpenHarmony provides the power consumption statistics feature. However, the power consumption benchmarks vary according to hardware specifications of different products. To address this issue, OpenHarmony provides the power consumption statistics customization function, allowing you to customize power consumption benchmarks depending on your hardware specifications. ### Basic Concepts diff --git a/en/device-dev/subsystems/subsys-power-wakeup-source-customization.md b/en/device-dev/subsystems/subsys-power-wakeup-source-customization.md new file mode 100644 index 0000000000000000000000000000000000000000..a4d8f57c4792175adefa295470730f3fa19c2d46 --- /dev/null +++ b/en/device-dev/subsystems/subsys-power-wakeup-source-customization.md @@ -0,0 +1,178 @@ +# Wakeup Source Customization + +## Overview + +### Introduction + +OpenHarmony supports multiple wakeup sources, such as the power button, keyboard, and mouse, and provides custom modes for turning on and off these wakeup sources. After a device enters the sleep state, you can turn on the screen and wake up the device by pressing the power button, keyboard, or mouse. However, different products may support different peripherals, for example, stylus or folio keyboard. To address this issue, OpenHarmony provides the wakeup source customization function, allowing you to customize wakeup sources depending on your hardware specifications. + +### Constraints + +The configuration paths for battery level customization are subject to the configuration policy. +The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy. + +## How to Develop + +### Setting Up the Environment + +**Hardware requirements:** + +Development board running the standard system, for example, the DAYU200 or Hi3516D V300 open source suite. + +**Environment requirements:** + +For details about the requirements on the Linux environment, see [Quick Start](../quick-start/quickstart-overview.md). + +### Getting Started with Development + +The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568) as an example to illustrate wakeup source customization. + +1. Create the `power_manager` folder in the product directory [/vendor/hihope/rk3568](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568). + +2. Create a target folder by referring to the [default folder of wakeup source configuration](https://gitee.com/openharmony/powermgr_power_manager/tree/master/services/native/profile), and install it in `/vendor/hihope/rk3568/power_manager`. The content is as follows: + + ```text + profile + ├── BUILD.gn + ├── power_wakeup.json + ``` + +3. Write the custom `power_wakeup.json` file that contains the custom wakeup sources. The following is an example of wakeup source configuration: + + ```json + { + "powerkey": { + "enable": true + }, + "keyborad": { + "enable": true + }, + "mouse": { + "enable": true + }, + "touchscreen": { + "enable": true, + "click": 2 + }, + "touchpad": { + "enable": true + }, + "pen": { + "enable": true + }, + "lid": { + "enable": true + }, + "switch": { + "enable": true + } + } + ``` + + **Table 1** Description of wakeup sources + + | Wakeup Source| Description| + | -------- | -------- | + | powerkey | Wakeup by power button| + | keyborad | Wakeup by keyboard| + | mouse | Wakeup by mouse| + | touchscreen | Wakeup by touchscreen| + | touchpad | Wakeup by touchpad| + | pen | Wakeup by stylus| + | lid | Wakeup by lid| + | switch | Wakeup by switch| + + **Table 2** Description of the wakeup source configuration + + | Item| Type| Description| + | -------- | -------- | -------- | + | enable | bool | Whether to enable wakeup listening| + | click | int | Number of clicks| + + +4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/BUILD.gn) file in the default folder of wakeup source configuration to pack the `power_wakeup.json` file to the `/vendor/etc/power_config` directory. The configuration is as follows: + + ```shell + import("//build/ohos.gni") # Reference build/ohos.gni. + + ohos_prebuilt_etc("wakeup_config") { + source = "power_wakeup.json" + relative_install_dir = "power_config" + install_images = [ chipset_base_dir ] # Required configuration for installing the battery_config.json file in the vendor directory. + part_name = "product_rk3568" # Set part_name to product_rk3568 for subsequent build. + } + ``` + +5. Add the build target to `module_list` in [ohos.build](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/ohos.build) in the `/vendor/hihope/rk3568` directory. For example: + + ```json + { + "parts": { + "product_rk3568": { + "module_list": [ + "//vendor/hihope/rk3568/default_app_config:default_app_config", + "//vendor/hihope/rk3568/image_conf:custom_image_conf", + "//vendor/hihope/rk3568/preinstall-config:preinstall-config", + "//vendor/hihope/rk3568/resourceschedule:resourceschedule", + "//vendor/hihope/rk3568/etc:product_etc_conf", + "//vendor/hihope/rk3568/power_manager/profile:wakeup_config" // Add the configuration for building of wakeup_config. + ] + } + }, + "subsystem": "product_hihope" + } + ``` + In the preceding code, `//vendor/hihope/rk3568/power_manager/` is the folder path, `profile` is the folder name, and `wakeup_config` is the build target. + +6. Build the customized version by referring to [Quick Start](../quick-start/quickstart-overview.md). + + ```shell + ./build.sh --product-name rk3568 --ccache + ``` + +7. Burn the customized version to the DAYU200 development board. + +### Debugging and Verification + +1. Customize wakeup sources in the `power_wakeup.json` file. + ```json + { + "powerkey": { + "enable": true + }, + "keyborad": { + "enable": true + }, + "mouse": { + "enable": true + }, + "touchscreen": { + "enable": false, + "click": 2 + }, + "touchpad": { + "enable": false + }, + "pen": { + "enable": false + }, + "lid": { + "enable": false + }, + "switch": { + "enable": false + } + } + ``` + +2. After the device is powered on, press the power button to switch the device to the sleep mode. Then, press the power button again. + + The device screen is turned on and the device is woken up. + +3. Press the power button to switch the device to the sleep mode, and then press the keyboard. + + The device screen is turned on and the device is woken up. + +4. Press the power button to switch the device to the sleep mode, and then move the mouse. + + The device screen is turned on and the device is woken up. diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md index 42a3db4829466d03e219c919f7cb7f200734b108..f8f27e77b91602c5d1b54a8e7e5d06f7fabd69c5 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md @@ -2,11 +2,11 @@ ## cl.filemanagement.1 environment Module Change -The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **environment** module supports error code handling. +The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **environment** module supports error code processing. **Change Impact** -If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **environment** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). +If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **environment** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. **Key API/Component Changes** @@ -24,11 +24,11 @@ import environment from '@ohos.file.environment'; ## cl.filemanagement.2 securityLabel Change -Moved the file management subsystem **d.ts** file to the **file** directory. The **securityLabel** module supports error code handling. +Moved the file management subsystem **d.ts** file to the **file** directory. The **securityLabel** module supports error code processing. **Change Impact** -If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **securityLabel** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). +If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **securityLabel** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. **Key API/Component Changes** @@ -58,11 +58,11 @@ The type of the **ino** attribute of **Stat** is changed from number to BigInt. ## cl.filemanagement.4 fileAccess Change -Moved the file management subsystem **d.ts** file to the **file** directory. The **fileAccess** module supports error code handling. +Moved the file management subsystem **d.ts** file to the **file** directory. The **fileAccess** module supports error code processing. **Change Impact** -If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileAccess** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). +If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileAccess** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. **Key API/Component Changes** @@ -80,11 +80,11 @@ import fileAccess from '@ohos.file.fileAccess'; ## cl.filemanagement.5 fileExtensionInfo Change -Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code handling. +Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code processing. **Change Impact** -If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileExtensionInfo** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). +If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileExtensionInfo** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. **Key API/Component Changes** @@ -102,11 +102,11 @@ import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; ## cl.filemanagement.6 storageStatistics Change -Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code handling. +Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code processing. **Change Impact** -If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **storageStatistics** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). +If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **storageStatistics** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. **Key API/Component Changes** @@ -124,11 +124,11 @@ import storageStatistics from '@ohos.file.storageStatistics'; ## cl.filemanagement.7 volumeManager Change -Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code handling. +Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code processing. **Change Impact** -If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **volumeManager** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). +If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **volumeManager** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. **Key API/Component Changes** diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-ability.md b/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..5920a7cdf72d6f3b02f7fca84eafea67abbfcc1e --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-ability.md @@ -0,0 +1,34 @@ +# Ability Framework Changelog + +Compared with OpenHarmony 3.2 Release, OpenHarmony 3.2.12.2 provides more detailed error code information for the APIs of the ability framework. + +## cl.ability.1 Added and Optimized API Error Code Description + +The error code description and all error codes that may be returned by the APIs are commented out. This helps developers control the error process more accurately. + +**Change Impact** + +The external declaration of the JS APIs of API version 9 is affected, but the API functionalities are not affected. You can determine whether to adapt to the JS APIs. + +**Key API/Component Changes** + +The comments of the following modules are updated. For details, see the corresponding external API declaration and API development guide. + +| Module | Description of Major Changes | +| ----------------------------------- | ------------------------------------------------------------ | +| @ohos.app.ability.UIAbility | Added the description of error codes 16200001, 16200002, 16200004, 16200005, 16000050.| +| @ohos.app.ability.abilityManager | Added the description of error codes 201, 202, and 16000050, and adjusted the description of error code 401.| +| @ohos.app.ability.appManager | Added the description of error codes 201, 202, and 16000050, and adjusted the description of error code 401.| +| @ohos.app.ability.dataUriUtils | Added the description of error code 401. | +| @ohos.app.ability.errorManager | Added the description of error code 16000003. | +| @ohos.app.ability.missionManager | Added the description of error codes 201, 202, 16300001, 16300002, and 16000009, and adjusted the description of error code 401.| +| @ohos.app.ability.quickFixManager | Added the description of error codes 201, 202, 18500001, 18500002, and 18500008. | +| @ohos.app.ability.wantAgent | Added the description of error codes 16000007, 16000015, and 16000151. | +| application/AbilityDelegator | Added the description of error codes 16000001, 16000002, 16000004, 16000005, 16000006, 16000008, 16000009, 16000010, 16000011, 16000050, 16000053, 16000055, 16200001, and 16000100.| +| application/ApplicationContext | Added the description of error codes 16000011 and 16000050. | +| application/Context | Added the description of error codes 201, 202, and 401. | +| application/ServiceExtensionContext | Added the description of error codes 201, 202, 16000001, 16000002, 16000004, 16000005, 16000006, 16000008, 16000009, 16000010, 16000011, 16000050, 16000053, 16000055, and 16200001.| +| application/UIAbilityContext | Added the description of error codes 201, 16000001, 16000002, 16000004, 16000005, 16000006, 16000008, 16000009, 16000010, 16000011, 16000050, 16000053, 16000055, 16200001, and 16000100.| +| @ohos.app.form.formHost | Added the description of error codes 201, 202, 16500050, 16500060, 16501000, 16501001, and 16501003, and adjusted the description of error code 401.| +| @ohos.app.form.formProvider | Added the error codes 202, 16500050, 16500060, 16500100, 16501000, 16501001, 16501002, and 16501003, and adjusted the description of error code 401.| +| application/FormExtensionContext | Added the description of error codes 202, 401, 16500050, 16500100, 16500101, and 16501000.| diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-notification.md b/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..6912ea1b5e419a71e017f54e91202ff5570f2477 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-notification.md @@ -0,0 +1,21 @@ +# Notification Subsystem Changelog + +Compared with OpenHarmony 3.2 Release, OpenHarmony 3.2.12.2 provides more detailed error code information for the APIs of the notification subsystem. + +## cl.notification.1 Added and Optimized API Error Code Description + +The error code description and all error codes that may be returned by the APIs are commented out. This helps developers control the error process more accurately. + +**Change Impact** + +The external declaration of the JS APIs of API version 9 is affected, but the API functionalities are not affected. You can determine whether to adapt to the JS APIs. + +**Key API/Component Changes** + +The comments of the following modules are updated. For details, see the corresponding external API declaration and API development guide. + +| Module | Major Change | +| --------------------------- | ------------------------------------------------------------ | +| @ohos.commonEventManager | Added the description of error codes 801, 1500007, and 1500008. | +| @ohos.notificationManager | Added the description of error codes 201, 202, 1600001, 1600002, 1600003, 1600004, 1600005, 1600007, 1600008, 1600009, 1600010, and 17700001, and adjusted the description of error code 401.| +| @ohos.notificationSubscribe | Added the description of error codes 201, 202, 1600001, 1600002, 1600003, 1600007, 1600008, and 17700001, and adjusted the description of error code 401.| diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-bundlemanager.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..f41df5b62252f03508110ed8931d47e6198b8b61 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-bundlemanager.md @@ -0,0 +1,14 @@ +# Bundle Management Subsystem Changelog + +## cl.bundlemanager.1 Changed Underlying Capability by Not Decompressing the HAP During HAP Installation + +The HAP will no longer be decompressed during installation. After the installation is complete, only the HAP file exists in the installation directory. As a result, the application must use the standard resource management interface, rather than a combined path, to access a resource file. + +**Change Impact**
+If the application uses a combined path to access a resource file, the access fails. It must use the resource management interface. + +**Key API/Component Changes**
+No API or component change is involved. + +**Adaptation Guide**
+The resource management subsystem provides the JS interface for accessing resource files. Reference: [Accessing Resource Files](../../../application-dev/reference/apis/js-apis-resource-manager.md#getrawfilecontent9) diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.5.5/changelogs-arkui.md b/en/release-notes/changelogs/OpenHarmony_4.0.5.5/changelogs-arkui.md new file mode 100644 index 0000000000000000000000000000000000000000..eaeba8adecf79591f6f27c06a4d8ba394d2fd42a --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.5.5/changelogs-arkui.md @@ -0,0 +1,53 @@ +# ArkUI Subsystem Changelog + +## cl.arkui.1 Change in the Default Scrollbar State of \ and \ Components + +Changed the default state of the scrollbar in the **\** and **\** components from **BarState.Off** to **BarState.Auto**. + +**Change Impact** + +In the scenario where the scrollbar status is not set in the **\** and **\** components: + +- Before change: + + The scrollbar is not displayed. + +- After change: + + The scrollbar is displayed during scrolling and is hidden 2 seconds after the scrolling stops. + +**Key API/Component Changes** + +**scrollBar** attribute of the **\** and **\** components: +- [List](../../../application-dev/reference/arkui-ts/ts-container-list.md#attributes) +- [Grid](../../../application-dev/reference/arkui-ts/ts-container-grid.md#attributes) + +**Adaptation Guide** + +In scenarios where the scrollbar is not required, set the **scrollBar** attribute of the **\** and **\** components to **BarState.Off**. + +The code snippet is as follows: +```ts +// xxx.ets +@Entry +@Component +struct ListItemExample { + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%').height(100).fontSize(16) + .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) + } + }, item => item) + } + .width('90%') + .scrollBar(BarState.Off) + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) + } +} +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.6.3/changelogs-arkui.md b/en/release-notes/changelogs/OpenHarmony_4.0.6.3/changelogs-arkui.md new file mode 100644 index 0000000000000000000000000000000000000000..344aa3f1f64081b00755ac6b622dee3d0bbc5ad2 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.6.3/changelogs-arkui.md @@ -0,0 +1,33 @@ +# ArkUI Subsystem Changelog +Fixed the issue where the layout of child components in the [\](../../../application-dev/reference/arkui-ts/ts-container-stack.md) container does not follow the **alignContent** settings when the child components do not fit in the container. + +Example: + +```ts +@Entry +@Component +struct StackExample { + build() { + Stack({alignContent:Alignment.TopEnd}){ + Text('First child, show in bottom') + .width(200).height(200).backgroundColor(0xd2cab3).margin(10) + }.width(150).height(150).backgroundColor(Color.Pink).margin(100) + } +} +``` +Before: Child components are not arranged based on **alignContent:Alignment.TopEnd**. + +![stack](figures/stack_before.jpg) + +After: Child components are arranged based on **alignContent:Alignment.TopEnd**. + +![stack](figures/stack_after.jpg) + + +**Change Impact** + +The previous workaround – setting the **Offset** or **translate** attribute – needs to be removed. + +**Adaptation Guide** + +Remove the **Offset** and **translate** settings for the child components and use **alignContent** for layout. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.6.3/figures/stack_after.jpg b/en/release-notes/changelogs/OpenHarmony_4.0.6.3/figures/stack_after.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eacfe82a9b1175a8a944be8a793ec940a4a80e0d Binary files /dev/null and b/en/release-notes/changelogs/OpenHarmony_4.0.6.3/figures/stack_after.jpg differ diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.6.3/figures/stack_before.jpg b/en/release-notes/changelogs/OpenHarmony_4.0.6.3/figures/stack_before.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b7b26a73935e28ce34d9895ac3e0cf519bbb41b5 Binary files /dev/null and b/en/release-notes/changelogs/OpenHarmony_4.0.6.3/figures/stack_before.jpg differ diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md b/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md index a9fe611ff2dab83d847e9cbea3db9c401f35a4e0..d6f1aea78f0f0c625df6cf46c59a4750c2f081d5 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-working-principles.md @@ -56,3 +56,5 @@ ArkTS卡片相较于JS卡片具备了更加丰富的能力,但也增加了使 - 不支持import,会在后续版本支持。 - 不支持极速预览,会在后续版本支持。 + +- 不支持Hot Reload热重载,会在后续版本支持。 diff --git a/zh-cn/application-dev/application-models/common-event-static-subscription.md b/zh-cn/application-dev/application-models/common-event-static-subscription.md index 3c77b9fd6e6846773bab03f4616a5592278598e0..3fb53ab476f4f00ecf807413a0167b57505500b8 100644 --- a/zh-cn/application-dev/application-models/common-event-static-subscription.md +++ b/zh-cn/application-dev/application-models/common-event-static-subscription.md @@ -103,12 +103,10 @@ ```json [ - ... { - "bundleName": "com.example.myapplication", // Bundle名称 - "app_signature": ["****"], // 指纹信息 - "allowCommonEvent": ["usual.event.A", "usual.event.B"], // 允许静态广播拉起的公共事件项 - ] + "bundleName": "com.example.myapplication", + "app_signature": ["****"], + "allowCommonEvent": ["usual.event.A", "usual.event.B"] } ] ``` diff --git a/zh-cn/application-dev/application-models/serviceextensionability.md b/zh-cn/application-dev/application-models/serviceextensionability.md index 1845ff4f140437db44b27c7b4b0eb553322c8761..143b7c53190d15f18ad647f278ca9cfb67af42a5 100644 --- a/zh-cn/application-dev/application-models/serviceextensionability.md +++ b/zh-cn/application-dev/application-models/serviceextensionability.md @@ -1,17 +1,5 @@ # ServiceExtensionAbility -- [概述](#概述) -- [生命周期](#生命周期) -- [实现一个后台服务(仅对系统应用开放)](#实现一个后台服务仅对系统应用开放) - - [开发准备](#开发准备) - - [定义IDL接口](#定义idl接口) - - [创建ServiceExtensionAbility](#创建serviceextensionability) -- [启动一个后台服务(仅对系统应用开放)](#启动一个后台服务仅对系统应用开放) -- [连接一个后台服务](#连接一个后台服务) -- [客户端与服务端通信](#客户端与服务端通信) -- [服务端对客户端身份校验](#服务端对客户端身份校验) -- [相关示例](#相关示例) - ## 概述 [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)是SERVICE类型的ExtensionAbility组件,提供后台服务能力,其内部持有了一个[ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md),通过[ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md)提供了丰富的接口供外部使用。 diff --git a/zh-cn/application-dev/connectivity/http-request.md b/zh-cn/application-dev/connectivity/http-request.md index 02459f5296451f936bdf14d5aa1a2637474d64e0..b70938d8a2416722798558c9dd13a99501cf6e81 100644 --- a/zh-cn/application-dev/connectivity/http-request.md +++ b/zh-cn/application-dev/connectivity/http-request.md @@ -78,6 +78,8 @@ httpRequest.request( // data.header为HTTP响应头,可根据业务需要进行解析 console.info('header:' + JSON.stringify(data.header)); console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ + // 当该请求使用完毕时,调用destroy方法主动销毁 + httpRequest.destroy(); } else { console.info('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件 diff --git a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md index 8b753e9e2927fcc379ab752026be25d5bcfcb618..f0a2a4db4bf4653a1e9cf57f4d775b6aa6e45522 100644 --- a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md +++ b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md @@ -116,7 +116,7 @@ int GenerateInputDataWithRandom(OH_AI_TensorHandleArray inputs) { 情形2:创建NNRT(Neural Network Runtime)和CPU异构推理上下文。 - NNRT是OpenHarMony系统中面向AI领域的跨芯片推理计算运行时,一般来说,NNRT对接的加速硬件如NPU,推理能力较强,但支持的算子规格少;而通用CPU推理能力较弱,但支持算子规格更全面。MindSpore Lite支持配置NNRT硬件和CPU异构推理:优先将模型算子调度到NNRT推理,若某些算子NNRT不支持,将其调度到CPU进行推理。通过下面的操作即可配置NNRT/CPU异构推理。 + NNRT是面向AI领域的跨芯片推理计算运行时,一般来说,NNRT对接的加速硬件如NPU,推理能力较强,但支持的算子规格少;而通用CPU推理能力较弱,但支持算子规格更全面。MindSpore Lite支持配置NNRT硬件和CPU异构推理:优先将模型算子调度到NNRT推理,若某些算子NNRT不支持,将其调度到CPU进行推理。通过下面的操作即可配置NNRT/CPU异构推理。 > **说明:** > @@ -130,7 +130,7 @@ int GenerateInputDataWithRandom(OH_AI_TensorHandleArray inputs) { return OH_AI_STATUS_LITE_ERROR; } // 优先使用NNRT推理。 - // 这里利用查找到的第一个ACCELERATORS类别的NNRT硬件,来创建nnrt设备信息,并设置硬件使用高性能模式推理。还可以通过如:OH_AI_GetAllNNRTDeviceDescs()接口获取当前环境中所有NNRT硬件的描述信息,按设备名、类型等信息查找,找到某一具体设备作为NNRT推理硬件。具体可参考:[Native接口参考:MindSpore](https://docs.openharmony.cn/pages/v3.2/zh-cn/application-dev/reference/native-apis/_mind_spore.md/) + // 这里利用查找到的第一个ACCELERATORS类别的NNRT硬件,来创建nnrt设备信息,并设置硬件使用高性能模式推理。还可以通过如:OH_AI_GetAllNNRTDeviceDescs()接口获取当前环境中所有NNRT硬件的描述信息,按设备名、类型等信息查找,找到某一具体设备作为NNRT推理硬件。 OH_AI_DeviceInfoHandle nnrt_device_info = OH_AI_CreateNNRTDeviceInfoByType(OH_AI_NNRTDEVICE_ACCELERATORS); if (nnrt_device_info == NULL) { printf("OH_AI_DeviceInfoCreate failed.\n"); diff --git a/zh-cn/application-dev/quick-start/multi-hap-release-deployment.md b/zh-cn/application-dev/quick-start/multi-hap-release-deployment.md index d592140c8371f4a16346248d401cc3f39a91d303..3fa01718df7eb39c4446365247dc187de27a221d 100644 --- a/zh-cn/application-dev/quick-start/multi-hap-release-deployment.md +++ b/zh-cn/application-dev/quick-start/multi-hap-release-deployment.md @@ -9,7 +9,9 @@ 开发者通过[DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio)工具按照业务的需要创建多个Module,在相应的Module中完成自身业务的开发。 ## 调试 -通过DevEco Studio编译打包,生成单个或者多个HAP,即可基于HAP进行调试。在调试前,需要先安装或更新HAP,以下介绍具体做法。 +通过DevEco Studio编译打包,生成单个或者多个HAP,即可基于HAP进行调试。如需根据不同的部署环境、目标人群、运行环境等,将同一个HAP定制编译为不同版本,请参见[定制编译指导](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/customized-multi-targets-and-products-0000001430013853-V3?catalogVersion=V3)。 + +在调试前,需要先安装或更新HAP,以下介绍具体做法。 * 使用DevEco Studio进行调试 使用指导可参考[应用程序包调试方法](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520),其中包括了单HAP与多HAP通过DevEco Studio工具的安装调试方法。 diff --git a/zh-cn/application-dev/quick-start/start-with-ets-stage.md b/zh-cn/application-dev/quick-start/start-with-ets-stage.md index 8fcf87f0f79c324924ecfbddef3efb5db94733d5..4ebd11ba03a96828fd31457093a0cce1161708ba 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-stage.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-stage.md @@ -37,14 +37,14 @@ - **AppScope > app.json5**:应用的全局配置信息。 - **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 -- **oh_modules**:用于存放三方库依赖信息。关于原npm工程适配ohpm操作,请参考[历史工程手动迁移](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212)。 - **src > main > ets**:用于存放ArkTS源码。 - **src > main > ets > entryability**:应用/服务的入口。 - **src > main > ets > pages**:应用/服务包含的页面。 - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](resource-categories-and-access.md#资源分类)。 - **src > main > module.json5**:模块配置文件。主要包含HAP的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[module.json5配置文件](module-configuration-file.md)。 - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。其中targets中可配置当前运行环境,默认为HarmonyOS。若需开发OpenHarmony应用,则需开发者自行修改为OpenHarmony。 -- **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 + - **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 +- **oh_modules**:用于存放三方库依赖信息。关于原npm工程适配ohpm操作,请参考[历史工程手动迁移](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212)。 - **build-profile.json5**:应用级配置信息,包括签名、产品配置等。 - **hvigorfile.ts**:应用级编译构建任务脚本。 diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md old mode 100755 new mode 100644 index aef70007b6be8336f6315586a58b9a8e5552bb41..54747d3f3df65453d59ae2aed92eb305a88212c3 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -213,6 +213,9 @@ - [@ohos.multimedia.camera (相机管理)](js-apis-camera.md) - [@ohos.multimedia.image (图片处理)](js-apis-image.md) - [@ohos.multimedia.media (媒体服务)](js-apis-media.md) + - [@ohos.multimedia.systemSoundManager (系统声音管理)](js-apis-systemSoundManager.md) + - multimedia + - [ringtonePlayer (铃声播放器)](js-apis-inner-multimedia-ringtonePlayer.md) - 资源管理 - [@ohos.i18n (国际化-I18n)](js-apis-i18n.md) @@ -250,6 +253,7 @@ - [@ohos.data.distributedKVStore (分布式键值数据库)](js-apis-distributedKVStore.md) - [@ohos.data.preferences (用户首选项)](js-apis-data-preferences.md) - [@ohos.data.relationalStore (关系型数据库)](js-apis-data-relationalStore.md) + - [@ohos.data.UDMF (统一数据管理框架)](js-apis-data-udmf.md) - [@ohos.data.ValuesBucket (数据集)](js-apis-data-valuesBucket.md) - 文件管理 @@ -332,6 +336,7 @@ - [@ohos.web.webview (Webview)](js-apis-webview.md) - [console (控制台)](js-apis-logs.md) - [Timer (定时器)](js-apis-timer.md) + - [syscap (系统能力)](js-apis-syscap.md) - application - [AccessibilityExtensionContext (辅助功能扩展上下文)](js-apis-inner-application-accessibilityExtensionContext.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md index 18c89d87f89719c70a87007b7abe72f5f10a913d..8e87141a86ae135fd6ea581b8666a2433caf3bf7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md @@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability'; | 名称 | 类型 | 描述 | | ----------- | -------------------- | ------------------------------------------------------------ | | DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | DataAbilityHelper二级模块。 | -| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | PacMap二级模块。 | +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | PacMap二级模块。 | | DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | DataAbilityOperation二级模块。 | | DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | DataAbilityResult二级模块。 | | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-animator.md b/zh-cn/application-dev/reference/apis/js-apis-animator.md index 33fdf28b6f19f070a15e294004f4f2c4ccf8d6ca..b0c58257114f39e21f789d3239e32dfb6b9f913d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-animator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-animator.md @@ -5,6 +5,8 @@ > **说明:** > > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)中使用。 ## 导入模块 diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md index 9389a1a82f36d996ba87cc8e51fa87fe83923977..f5c71a99fb3f6683dd36c007e6bfd434e36253aa 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -1,6 +1,6 @@ # @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry) -AbilityDelegatorRegistry是[测试框架](../../ability-deprecated/ability-delegator.md)模块,该模块用于获取[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)和[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象,其中[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)对象提供添加用于监视指定ability的生命周期状态更改的AbilityMonitor对象的能力,[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象提供获取当前测试参数的能力。 +AbilityDelegatorRegistry是[自动化测试框架使用指南](../../application-test/arkxtest-guidelines.md)模块,该模块用于获取[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)和[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象,其中[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)对象提供添加用于监视指定ability的生命周期状态更改的AbilityMonitor对象的能力,[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象提供获取当前测试参数的能力。 > **说明:** > diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md index 6b864a63ac5748aa57d97536d44f53b0ce0107ef..101320203d58556a56d6d5d742dd87d573148a05 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md @@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common'; | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | FormExtensionContext二级模块。 | | ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | ServiceExtensionContext二级模块。 | | EventHub | [EventHub](js-apis-inner-application-eventHub.md) | EventHub二级模块。 | -| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | PacMap二级模块。 | +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | PacMap二级模块。 | | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-want.md b/zh-cn/application-dev/reference/apis/js-apis-application-want.md index 184d2ee6fe82c73a60046da37d1b83473491ae73..79ec55abac8102f1ede8c637a516988c1f31a1d3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-want.md @@ -130,6 +130,6 @@ import Want from '@ohos.application.Want'; }); ``` -- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want +- 更多详细说明和示例请参见: [应用模型](../../application-models/application-model-composition.md)的信息传递载体Want \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md index 7f77be34f723e569c6da131ed9e6faa3aa73f981..9c4ee351f92055fd5c4b1245529a785905143861 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @@ -19,7 +19,7 @@ import componentSnapshot from "@ohos.arkui.componentSnapshot"; get(id: string, callback: AsyncCallback): void -获取已加载的组件的截图,传入组件的[ID 标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。 +获取已加载的组件的截图,传入组件的[组件标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。 > **说明:** > @@ -50,8 +50,8 @@ struct SnapshotExample { Image(this.pixmap) .width(300).height(300) // ...Component - // ...Components - // ...Components + // ...Component + // ...Component Button("click to generate UI snapshot") .onClick(() => { componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-call.md b/zh-cn/application-dev/reference/apis/js-apis-call.md index a2f6a42f20cd78caa3a3e45f21e40e43266397b2..92e280289e4501a046c62eae17409827deb11740 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-call.md +++ b/zh-cn/application-dev/reference/apis/js-apis-call.md @@ -2719,6 +2719,91 @@ call.off('mmiCodeResult', data => { }); ``` + +## call.on('audioDeviceChange')10+ + +on\(type: 'audioDeviceChange', callback: Callback\\): void + +订阅通话音频设备切换事件。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | --------------------------------------------------- | +| type | string | 是 | 通话音频设备发生变化,参数固定为'audioDeviceChange'。 | +| callback | Callback<[AudioDeviceInfo](#audiodeviceinfo10)> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +call.on('audioDeviceChange', data => { + console.log(`callback: data->${JSON.stringify(data)}`); +}); +``` + + +## call.off('audioDeviceChange')10+ + +off\(type: 'audioDeviceChange', callback?: Callback\\): void + +取消订阅audioDeviceChange事件。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------- | +| type | string | 是 | 通话音频设备发生变化,参数固定为'audioDeviceChange'。 | +| callback | Callback<[AudioDeviceInfo](#audiodeviceinfo10)> | 否 | 回调函数。不填该参数将不会收到取消订阅的处理结果。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +call.off('audioDeviceChange', data => { + console.log(`callback: data->${JSON.stringify(data)}`); +}); +``` + + ## call.isNewCallAllowed8+ isNewCallAllowed\(callback: AsyncCallback\\): void @@ -4062,6 +4147,472 @@ promise.then(data => { }); ``` + +## call.closeUnfinishedUssd10+ + +closeUnfinishedUssd\(slotId: number, callback: AsyncCallback\\): void + +取消未激活完成的非结构化补充数据业务。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +call.closeUnfinishedUssd(slotId, (err) => { + console.log(`callback: err->${JSON.stringify(err)}`); +}); +``` + +## call.closeUnfinishedUssd10+ + +closeUnfinishedUssd\(slotId: number\): Promise\ + +取消未激活完成的非结构化补充数据业务。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | --------------------------- | +| Promise<void> | 以Promise形式异步返回结果。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +call.closeUnfinishedUssd(slotId).then(() => { + console.log(`closeUnfinishedUssd success.`); +}).catch((err) => { + console.error(`closeUnfinishedUssd fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +## call.setVoNRState10+ + +setVoNRState\(slotId: number, state: VoNRState, callback: AsyncCallback\\): void + +设置NR语音的开关状态。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ----------------------------- | ---- | ---------------------------------------------------- | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | +| state | [VoNRState](#vonrstate10) | 是 | 开关状态。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示设置成功,返回false表示设置失败。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +let state = 1; +call.setVoNRState(slotId, state, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setVoNRState10+ + +setVoNRState\(slotId: number, state: VoNRState\): Promise\ + +设置NR语音的开关状态。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.SET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ----------------------------- | ---- | ------------------------------------------- | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2。 | +| state | [VoNRState](#vonrstate10) | 是 | 开关状态。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | --------------------------------------------- | +| Promise<boolean> | 以Promise形式异步返回开关状态是否设置成功。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +let state = 1; +call.setVoNRState(slotId, state).then(() => { + console.log(`setVoNRState success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`setVoNRState fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +## call.getVoNRState10+ + +getVoNRState\(slotId: number, callback: AsyncCallback\\): void + +查询NR语音的开关状态。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------ | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | +| callback | AsyncCallback<[VoNRState](#vonrstate10)>| 是 | 回调函数。返回NR语音开关的状态。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +call.getVoNRState(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getVoNRState10+ + +getVoNRState\(slotId: number\): Promise\ + +查询NR语音的开关状态。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ----------------------------- | ---- | ------------------------------------------- | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | ------------------------------------------- | +| Promise<[VoNRState](#vonrstate10)> | 以Promise形式异步返回开关状态。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +let promise = call.getVoNRState(slotId); +promise.then(data => { + console.log(`getVoNRState success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getVoNRState fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +## call.canSetCallTransferTime10+ + +canSetCallTransferTime\(slotId: number, callback: AsyncCallback\\): void + +检查是否可以设置呼叫转移时间。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ----------------------------- | ---- | ----------------------------------------------------- | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示可以设置,返回false表示不可以设置。| + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +call.canSetCallTransferTime(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.canSetCallTransferTime10+ + +canSetCallTransferTime\(slotId: number\): Promise\ + +检查是否可以设置呼叫转移时间。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.GET_TELEPHONY_STATE + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ----------------------------- | ---- | ------------------------------------------- | +| slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | --------------------------------------------- | +| Promise<boolean> | 以Promise形式异步返回是否可以设置呼叫转移时间。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | +| 8300999 | Unknown error code. | + +**示例:** + +```js +let slotId = 0; +call.canSetCallTransferTime(slotId).then(() => { + console.log(`canSetCallTransferTime success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`canSetCallTransferTime fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + +## call.inputDialerSpecialCode10+ + +inputDialerSpecialCode\(inputCode: string, callback: AsyncCallback\\): void + +暗码广播。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.PLACE_CALL + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ---------------------------- | ---- | ----------------------------------------- | +| inputCode | string | 是 | 暗码。支持暗码字段, 如:2846579(工程菜单)。 | +| callback | AsyncCallback<void> | 是 | 回调函数 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | + +**示例:** + +```js +call.inputDialerSpecialCode('2846579', (err) => { + console.log(`callback: err->${JSON.stringify(err)}`); +}); +``` + +## call.inputDialerSpecialCode10+ + +inputDialerSpecialCode\(inputCode: string\): Promise\ + +暗码广播。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限**:ohos.permission.PLACE_CALL + +**系统能力**:SystemCapability.Telephony.CallManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ---------------------------- | ---- | ----------------------------------------- | +| inputCode | string | 是 | 暗码。支持暗码字段, 如:2846579(工程菜单)。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | --------------------------- | +| Promise<void> | 以Promise形式异步返回结果。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.telephony(电话子系统)错误码](../../reference/errorcodes/errorcode-telephony.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Non-system applications use system APIs. | +| 401 | Parameter error. | +| 8300001 | Invalid parameter value. | +| 8300002 | Operation failed. Cannot connect to service. | +| 8300003 | System internal error. | + +**示例:** + +```js +try { + call.inputDialerSpecialCode('2846579'); + console.log(`inputDialerSpecialCode success`); +} catch (error) { + console.log(`inputDialerSpecialCode fail, promise: err->${JSON.stringify(error)}`); +} +``` + + ## DialOptions 拨打电话的可选参数。 @@ -4071,23 +4622,25 @@ promise.then(data => { | 名称 | 类型 | 必填 | 说明 | | ------------------------ | ---------------------------------- | ---- | ----------------------------------------------------------------------------------------------- | | extras | boolean | 否 | 根据extras的值判断是否为视频通话,默认为语音通话。
- true:视频通话。
- false:语音通话。 | -| accountId 8+ | number | 否 | 帐户Id。
- 0:卡槽1
- 1:卡槽2
。 | -| videoState 8+ | [VideoStateType](#videostatetype7) | 否 | 视频状态类型。 | -| dialScene 8+ | [DialScene](#dialscene8) | 否 | 拨号场景。 | -| dialType 8+ | [DialType](#dialtype8) | 否 | 拨号类型。 | +| accountId 8+ | number | 否 | 帐户Id。
- 0:卡槽1
- 1:卡槽2
。此接口为系统接口。 | +| videoState 8+ | [VideoStateType](#videostatetype7) | 否 | 视频状态类型。此接口为系统接口。 | +| dialScene 8+ | [DialScene](#dialscene8) | 否 | 拨号场景。此接口为系统接口。 | +| dialType 8+ | [DialType](#dialtype8) | 否 | 拨号类型。此接口为系统接口。 | ## DialCallOptions9+ 拨打电话的可选参数。 +**系统接口:** 此接口为系统接口。 + **系统能力**:SystemCapability.Telephony.CallManager -| 名称 | 类型 | 必填 | 说明 | -| ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ | -| accountId 9+ | number | 否 | 帐户Id。
- 0:卡槽1
- 1:卡槽2
此接口为系统接口。| -| videoState 9+ | [VideoStateType](#videostatetype7) | 否 | 视频状态类型。此接口为系统接口。 | -| dialScene 9+ | [DialScene](#dialscene8) | 否 | 拨号场景。此接口为系统接口。 | -| dialType 9+ | [DialType](#dialtype8) | 否 | 拨号类型。此接口为系统接口。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------------------ | ---------------------------------- | ---- | ------------------------------------------- | +| accountId 9+ | number | 否 | 帐户Id。
- 0:卡槽1
- 1:卡槽2
。| +| videoState 9+ | [VideoStateType](#videostatetype7) | 否 | 视频状态类型。 | +| dialScene 9+ | [DialScene](#dialscene8) | 否 | 拨号场景。 | +| dialType 9+ | [DialType](#dialtype8) | 否 | 拨号类型。 | ## CallState @@ -4138,6 +4691,19 @@ IP多媒体系统调用模式。 | CALL_MODE_SEND_RECEIVE | 3 | 允许发送和接收呼叫 | | CALL_MODE_VIDEO_PAUSED | 4 | 暂停视频呼叫 | +## VoNRState10+ + +5G语音开关状态。 + +**系统接口:** 此接口为系统接口。 + +**系统能力**:SystemCapability.Telephony.CallManager + +| 名称 | 值 | 说明 | +| ---------------------- | ---- | ----------------- | +| VONR_STATE_OFF | 0 | 关闭状态 | +| VONR_STATE_ON | 1 | 打开状态 | + ## AudioDevice8+ 音频设备。 @@ -4154,6 +4720,36 @@ IP多媒体系统调用模式。 | DEVICE_BLUETOOTH_SCO | 3 | 蓝牙SCO设备 | | DEVICE_MIC | 4 | 麦克风设备 | +## AudioDeviceType10+ + +音频设备类型。 + +**系统接口:** 此接口为系统接口。 + +**系统能力**:SystemCapability.Telephony.CallManager + +| 名称 | 值 | 说明 | +| -------------------- | ---- | ----------- | +| DEVICE_EARPIECE | 0 | 耳机设备 | +| DEVICE_SPEAKER | 1 | 扬声器设备 | +| DEVICE_WIRED_HEADSET | 2 | 有线耳机设备 | +| DEVICE_BLUETOOTH_SCO | 3 | 蓝牙SCO设备 | + +## AudioDeviceInfo10+ + +音频设备信息。 + +**系统接口:** 此接口为系统接口。 + +**系统能力**:SystemCapability.Telephony.CallManager + +| 名称 | 类型 | 必填 | 说明 | +| --------------------------------- | ------------------------------------- | ---- | ---------------- | +| audioDeviceList 10+ | [Array\](#audiodevice8) | 是 | 音频设备列表。 | +| currentAudioDevice 10+ | [AudioDevice](#audiodevice8) | 是 | 音频设备类型。 | +| isMuted 10+ | boolean | 是 | 是否静音。 | + + ## CallRestrictionType8+ 呼叫限制类型。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md b/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md index c054dc17b8104720f529cc46c9961b59da782a8f..d27fd96d514743ed0665e9bb40ecbfb0b1fb2e97 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md @@ -76,7 +76,7 @@ let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; try { dataShare.createDataShareHelper(this.context, uri, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); return; } @@ -88,9 +88,57 @@ try { }; ``` +## dataShare.createDataShareHelper10+ +createDataShareHelper(context: Context, uri: string, options: DataShareHelperOptions, callback: AsyncCallback<DataShareHelper>): void + +创建DataShareHelper实例。使用callback异步回调。 + +使用规则: + - 调用方应用位于后台时,使用该接口访问DataShareExtension需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 + - 跨应用场景下,目标DataShareExtension的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md) + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | [Context](js-apis-inner-application-context.md#context) | 是 | 应用的上下文环境。 | +| uri | string | 是 | 指示要连接的服务端应用的路径。 | +| options | [DataShareHelperOptions](#datasharehelperoptions10)| 是 | 可选配置。指定[DataShareHelper](#datasharehelper)是否在代理模式下。| +| callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | 是 | 回调函数。当创建DataShareHelper实例成功,err为undefined,data为获取到的DataShareHelper实例;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------------------- | +| 15700010 | The DataShareHelper is not initialized successfully. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); +let dataShareHelper; +try { + dataShare.createDataShareHelper(this.context, uri, {isProxy : true}, (err, data) => { + if (err !== undefined) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("createDataShareHelper succeed, data : " + data); + dataShareHelper = data; + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; +``` ## dataShare.createDataShareHelper -createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper> +createDataShareHelper(context: Context, uri: string, options?: DataShareHelperOptions): Promise<DataShareHelper> 创建DataShareHelper实例。使用Promise异步回调。 @@ -107,6 +155,7 @@ createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper | ------- | ------------------------------------------------- | ---- | ------------------------------ | | context | [Context](js-apis-inner-application-context.md#context) | 是 | 应用的上下文环境。 | | uri | string | 是 | 指示要连接的服务端应用的路径。 | +| options | [DataShareHelperOptions](#datasharehelperoptions10) | 否 | 可选配置。从API version 10开始支持此参数,如果不设置,则表示[DataShareHelper](#datasharehelper)不在代理模式下。| **返回值:** @@ -127,10 +176,10 @@ createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -let uri = ("datashare:///com.samples.datasharetest.DataShare"); +let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); let dataShareHelper; try { - dataShare.createDataShareHelper(this.context, uri).then((data) => { + dataShare.createDataShareHelper(this.context, uri, {isProxy : true}).then((data) => { console.info("createDataShareHelper succeed, data : " + data); dataShareHelper = data; }). catch((err) => { @@ -141,6 +190,83 @@ try { }; ``` +## DataShareHelperOptions10+ + +指定[DataShareHelper](#datasharehelper)是否在代理模式下。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| isProxy | boolean | 否 | 默认为false,如果为true,则要创建的[DataShareHelper](#datasharehelper)处于代理模式,所有操作都不会打开数据提供者APP,除非数据库不存在,当数据库不存在时,[createDataShareHelper](#datasharecreatedatasharehelper10)会拉起数据提供者创建数据库。 | + +## TemplateId10+ + +标记模板的数据结构,TemplateId是在[addTemplate](#addtemplate10)中自动生成的,在[addTemplate](#addtemplate10)后,可以使用模板id来标记模板。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| subscriberId | string | 是 | 指定处理回调的订阅者的id,与[addTemplate](#addtemplate10)中的subscriberId相同,每个订阅者的ID是唯一的。 | +| bundleNameOfOwner | string | 是 | 指定创建模板的模板所有者的bundleName,与[addTemplate](#addtemplate10)中的bundleName相同。 | + +## PublishedItem10+ + +指定发布的数据类型。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | string | 是 | 指定发布数据的键。 | +| data | string \| [Ashmem](js-apis-rpc.md#ashmem8) | 是 | 指定发布的数据。如果数据很大,请使用Ashmem。 | +| subscriberId | string | 是 | 指定订阅者id。 | + +## RdbDataChangeNode10+ + +订阅/取消订阅RDB数据变更的结果。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| uri | string | 是 | 指定回调的uri。 | +| templateId | [TemplateId](#templateid10) | 是 | 处理回调的templateId。 | +| data | Array<string> | 是 | 指定回调的数据。 | + +## PublishedDataChangeNode10+ + +订阅/取消订阅已发布数据变更的结果。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| bundleName | string | 是 | 指定回调的bundleName。 | +| data | Array<[PublishedItem](#publisheditem10)> | 是 | 指定回调的数据。 | + +## Template10+ + +指定订阅中的模板结构。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| predicates | { [key: string]: string } | 是 | 指定模板的谓词。当调用[on](#onrdbdatachange10)的回调时,谓词用于生成数据。仅适用于rdb存储数据。 | +| scheduler | string | 是 | 指定模板的调度程序sql。其中嵌入自定义函数处理,目前预置自定义函数remindTimer处理。remindTimer在指定场景触发一次订阅刷新。
触发场景:
1. 修改数据时且有订阅的情况下触发对应的调度程序sql语句。
2. 添加对应库第一个订阅的情况下触发对应的调度程序sql语句。 | + +## OperationResult10+ + +订阅/取消订阅数据变更和发布数据的操作结果。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | ----- | -------- | +| key | string | 是 | 指定运算结果的键。 | +| result | number | 是 | 指定运算结果。 | ## DataShareHelper DataShare管理工具实例,可使用此实例访问或管理服务端的数据。在调用DataShareHelper提供的方法前,需要先通过[createDataShareHelper](#datasharecreatedatasharehelper)构建一个实例。 @@ -164,8 +290,6 @@ on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - function onCallback() { console.info("**** Observer on callback ****"); } @@ -192,8 +316,6 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - function callback() { console.info("**** Observer callback ****"); } @@ -202,6 +324,437 @@ dataShareHelper.on("dataChange", uri, callback); dataShareHelper.off("dataChange", uri, callback); ``` +### addTemplate10+ + +addTemplate(uri: string, subscriberId: string, template: Template): void + +添加一个指定订阅者的数据模板。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | -------------------------| +| uri | string | 是 | 指示要插入的数据的路径。 | +| subscriberId | string | 是 | 要添加模板的订阅者ID,每个订阅者的ID是唯一的。 | +| template | [Template](#template10) | 是 | 要添加的数据模板。 | + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------- | +| 15700011 | The uri is not exist.| + +**示例:** + +```ts +let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); +let subscriberId = '11'; +let template = { + predicates : { + "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true", + "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false", + }, + scheduler : "select remindTimer(time) from TBL00" +} +dataShareHelper.addTemplate(uri, subscriberId, template); +``` + +### delTemplate10+ + +delTemplate(uri: string, subscriberId: string): void + +删除一个指定订阅者的数据模板。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------| ---- | ------------------------- | +| uri | string | 是 | 指示要插入的数据的路径。 | +| subscriberId | string | 是 | 订阅者ID,每个订阅者的ID是唯一的。 | + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------- | +| 15700011 | The uri is not exist.| + +**示例:** + +```ts +let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); +let subscriberId = '11'; +let template = { + predicates : { + "p1" : "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true", + "p2" : "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false", + }, + scheduler : "select remindTimer(time) from TBL00" +} +dataShareHelper.addTemplate(uri, subscriberId, template); +dataShareHelper.delTemplate(uri, subscriberId); +``` + +### on('rdbDataChange')10+ + +on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> + +订阅指定URI和模板对应的数据变更事件。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------| ---- | ------------------------------------------------------------ | +| type | string | 是 | 订阅的事件类型,支持的事件为'rdbDataChange',表示rdb数据的变更事件。 | +| uris | Array<string> | 是 | 要操作的数据的路径。 | +| templateId | [TemplateId](#templateid10) | 是 | 处理回调的templateId。 | +| callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | 是 | 回调函数。当触发变更通知时调用,err为undefined,node为订阅数据变更结果;否则不被触发或为错误对象。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Array<[OperationResult](#operationresult10)> | 返回操作结果。| + +**示例:** + +```ts +function onCallback(err, node:dataShare.RdbDataChangeNode) { + console.info("onCallback " + JSON.stringify(node.uri)); + console.info("onCallback " + JSON.stringify(node.templateId)); + console.info("onCallback " + node.data.length); + for (let i = 0; i < node.data.length; i++) { + console.info("onCallback " + typeof node.data[i] + " " + node.data[i]); + } +} + +let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); +let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; +let result:Array = dataShareHelper.on("rdbDataChange", [uri], templateId, onCallback); +``` + +### off('rdbDataChange')10+ + +off(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback?: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> + +取消订阅指定URI和模板对应的数据变更事件。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| type | string | 是 | 取消订阅的事件类型,支持的事件为'rdbDataChange',表示rdb数据的变更事件。 | +| uris | Array<string> | 是 | 要操作的数据的路径。 | +| templateId | [TemplateId](#templateid10) | 是 | 处理回调的templateId。 | +| callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | 否 | 回调函数。表示指定取消订阅的callback通知,如果为空,则取消订阅该uri下所有的通知事件。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Array<[OperationResult](#operationresult10)> | 返回操作结果。| + +**示例:** + +```ts +let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); +let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; +let result:Array = dataShareHelper.off("rdbDataChange", [uri], templateId); +``` + +### on('publishedDataChange')10+ + +on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> + +订阅已发布数据的数据变更通知。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------| ---- | ------------------------------------------------------------ | +| type | string | 是 | 订阅的事件类型,支持的事件为'publishedDataChange',表示已发布数据的变更事件。 | +| uris | Array<string> | 是 | 要操作的数据的路径。 | +| subscriberId | string | 是 | 指定处理回调的用户ID。 | +| callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | 是 | 回调函数。当触发变更通知时调用,err为undefined,node为订阅数据变更结果;否则不被触发或为错误对象。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Array<[OperationResult](#operationresult10)> | 返回操作结果。| + +**示例:** + +```ts +import rpc from '@ohos.rpc'; + +function onPublishCallback(err, node:dataShare.PublishedDataChangeNode) { + console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName)); + console.info("onPublishCallback node data size" + node.data.length); + for (let i = 0; i < node.data.length; i++) { + console.info("onPublishCallback node " + typeof node.data[i].data); + if (typeof node.data[i].data != 'string') { + let ash:rpc.Ashmem = node.data[i].data; + ash.mapReadonlyAshmem(); + console.info("onPublishCallback " + JSON.stringify(ash.readAshmem(ash.getAshmemSize()/4, 0))); + ash.closeAshmem(); + } + console.info("onPublishCallback data " + i + " " + JSON.stringify(node.data[i])); + } +} +let uris:Array = ['city', 'datashareproxy://com.acts.ohos.data.datasharetest/appInfo', 'key2']; +let subscriberId = '11'; +let result: Array = dataShareHelper.on('publishedDataChange', uris, subscriberId, onPublishCallback); +``` + +### off('publishedDataChange')10+ + +off(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback?: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> + +取消订阅已发布数据的数据变更通知。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| type | string | 是 | 取消订阅的事件类型,支持的事件为'publishedDataChange',表示已发布数据的变更事件。| +| uris | Array<string> | 是 | 要操作的数据的路径。 | +| subscriberId | string | 是 | 指定处理回调的用户ID。 | +| callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | 否 | 回调函数。表示指定取消订阅的callback通知,如果为空,则取消订阅该uri下所有的通知事件。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Array<[OperationResult](#operationresult10)> | 返回操作结果。| + +**示例:** + +```ts +function offCallback(err, node:dataShare.PublishedDataChangeNode) { + console.info("**** Observer off callback ****"); +} +let uris:Array = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"]; +let subscriberId = '11'; +let result: Array = dataShareHelper.off("publishedDataChange", uris, subscriberId, offCallback); +``` + +### publish10+ + +publish(data: Array<PublishedItem>, bundleName: string, version: number, callback: AsyncCallback<Array<OperationResult>>): void + +发布数据,将数据数据更新至数据库。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | -------------------------------------------------| ---- | ------------------- | +| data | Array<[PublishedItem](#publisheditem10)> | 是 | 指示要发布的数据。 | +| bundleName | string | 是 | 表示要发布数据所属的APP,对发布的私有数据生效,仅该app可以读取数据。 | +| version | number | 是 | 指示要发布的数据版本,越大表示数据版本越新。如果发布的版本号小于数据库中的记录,则更新失败。 | +| callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | 是 | 回调函数。当发布数据时调用,err为undefined,result为发布数据结果;否则不被触发或为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 15700012 | The data area is not exist.| + +**示例:** + +```ts +import rpc from '@ohos.rpc'; + +let ashmem = null; +let subscriberId = '11'; +let version = 1; +let data : Array = [ + {key:"city", subscriberId:"11", data:"xian"}, + {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, + {key:"empty", subscriberId:"11", data:"nobody sub"}]; +let nums:number[] = [1,2,3]; +function publishCallback(err, result: Array) { + console.log("publishCallback " + JSON.stringify(result)); + ashmem.closeAshmem(); +} +try { + ashmem = rpc.Ashmem.create("ashmem", (nums.length) * 4); + ashmem.mapReadWriteAshmem(); + ashmem.writeAshmem(nums, nums.length, 0); + data.push({ + "key" : "key2", + "data" : ashmem, + "subscriberId" : "11", + }); + console.log("data length is:", data.length); + dataShareHelper.publish(data, "com.acts.ohos.data.datasharetest", version, publishCallback); +} catch (e) { + console.log("publish error " + JSON.stringify(e)); +} +``` + +### publish10+ + +publish(data: Array<PublishedItem>, bundleName: string, callback: AsyncCallback<Array<OperationResult>>): void + +发布数据,将数据数据更新至数据库。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | ---------------------------------- | +| data | Array<[PublishedItem](#publisheditem10)> | 是 | 指示要发布的数据。 | +| bundleName | string | 是 | 表示要发布数据所属的APP,对发布的私有数据生效,仅该app可以读取数据。 | +| callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | 是 | 回调函数。当发布数据时调用,err为undefined,result为发布数据结果;否则不被触发或为错误对象。 | + +**示例:** + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 15700012 | The data area is not exist.| + +```ts +function publishCallback(err, result: Array) { + console.log("publishCallback " + JSON.stringify(result)); +} +let data : Array = [ + {key:"city", subscriberId:"11", data:"xian"}, + {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, + {key:"empty", subscriberId:"11", data:"nobody sub"}]; +dataShareHelper.publish(data, "com.acts.ohos.data.datasharetest", publishCallback); +``` + +### publish10+ + +publish(data: Array<PublishedItem>, bundleName: string, version?: number): Promise<Array<OperationResult>> + +发布数据,将数据数据更新至数据库。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------- | ---- | ------------------------------ | +| data | Array<[PublishedItem](#publisheditem10)> | 是 | 指示要发布的数据。| +| bundleName | string | 是 | 表示要发布数据所属的APP,对发布的私有数据生效,仅该app可以读取数据。 | +| version | number | 否 | 指示要发布的数据版本,越大表示数据版本越新。如果发布的版本号小于数据库中的记录,则更新失败。
如果不检查要发布的数据版本,则不填。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Promise<Array<[OperationResult](#operationresult10)>> | 发布数据结果。| + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 15700012 | The data area is not exist.| + +**示例:** + +```ts +let data : Array = [ + {key:"city", subscriberId:"11", data:"xian"}, + {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, + {key:"empty", subscriberId:"11", data:"nobody sub"}]; +let result: Array = dataShareHelper.publish(data, "com.acts.ohos.data.datasharetest"); +``` + +### getPublishedData10+ + +getPublishedData(bundleName: string, callback: AsyncCallback<Array<PublishedItem>>): void + +获取给定的APP和模板指定的数据。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------| ---- | ----------------------------- | +| bundleName | string | 是 | 表示数据所属的APP。 | +| callback | AsyncCallback<Array<[PublishedItem](#publisheditem10)>> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 15700012 | The data area is not exist.| + +**示例:** + +```ts +function publishCallback(err, data: Array) { + console.info("**** Observer publish callback ****"); +} +dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest", publishCallback); +``` + +### getPublishedData10+ + +getPublishedData(bundleName: string): Promise<Array<PublishedItem>> + +获取给定的APP和模板指定的数据。 + +**系统能力:** SystemCapability.DistributedDataManager.DataShare.Consumer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------| ---- | -------------------------------------- | +| bundleName | string | 是 | 表示数据所属的APP。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Promise<Array<[PublishedItem](#publisheditem10)>> | Promise对象。返回给定的APP和模板指定的数据。| + +**错误码:** + +以下错误码的详细介绍请参见[数据共享错误码](../errorcodes/errorcode-datashare.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 15700012 | The data area is not exist.| + +**示例:** + +```ts +let publishedData:Array = dataShareHelper.getPublishedData("com.acts.ohos.data.datasharetest"); +``` + ### insert insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void @@ -221,8 +774,6 @@ insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose", @@ -231,7 +782,7 @@ const valueBucket = { } try { dataShareHelper.insert(uri, valueBucket, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.error(`insert error: code: ${err.code}, message: ${err.message} `); return; } @@ -266,8 +817,6 @@ insert(uri: string, value: ValuesBucket): Promise<number> **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose1", @@ -304,7 +853,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callbac **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -312,7 +860,7 @@ let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); try { dataShareHelper.delete(uri, da, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.error(`delete error: code: ${err.code}, message: ${err.message} `); return; } @@ -347,7 +895,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promis **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -384,7 +931,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -393,7 +939,7 @@ let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); try { dataShareHelper.query(uri, da, columns, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.error(`query error: code: ${err.code}, message: ${err.message} `); return; } @@ -429,7 +975,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -467,7 +1012,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -481,7 +1025,7 @@ const va = { } try { dataShareHelper.update(uri, da, va, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.error(`update error: code: ${err.code}, message: ${err.message} `); return; } @@ -517,7 +1061,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -559,15 +1102,13 @@ batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallb **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) try { dataShareHelper.batchInsert(uri, vbs, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); return; } @@ -602,8 +1143,6 @@ batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number&g **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, @@ -637,11 +1176,9 @@ normalizeUri(uri: string, callback: AsyncCallback<string>): void **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.log("normalizeUri failed, error message : " + err); }else{ console.log("normalizeUri = " + data); @@ -672,8 +1209,6 @@ normalizeUri(uri: string): Promise<string> **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri).then((data) => { console.log("normalizeUri = " + data); @@ -700,11 +1235,9 @@ denormalizeUri(uri: string, callback: AsyncCallback<string>): void **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { - if (err != undefined) { + if (err !== undefined) { console.log("denormalizeUri failed, error message : " + err); }else{ console.log("denormalizeUri = " + data); @@ -735,8 +1268,6 @@ denormalizeUri(uri: string): Promise<string> **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri).then((data) => { console.log("denormalizeUri = " + data); @@ -763,8 +1294,6 @@ notifyChange(uri: string, callback: AsyncCallback<void>): void **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.log("***** notifyChange *****"); @@ -794,8 +1323,6 @@ notifyChange(uri: string): Promise<void> **示例:** ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-udmf.md b/zh-cn/application-dev/reference/apis/js-apis-data-udmf.md new file mode 100644 index 0000000000000000000000000000000000000000..74674bc05fac5195e2c371881775a84198bdfce0 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-data-udmf.md @@ -0,0 +1,465 @@ +# @ohos.data.UDMF(统一数据管理框架) + +本模块提供数据统一管理的能力,包括对文本、图片等数据类型的标准化定义。通过调用对应数据类型的接口,应用程序可将各种数据封装为统一数据对象。 + +> **说明:** +> +> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import UDMF from '@ohos.data.UDMF'; +``` + +## UnifiedDataType + +[统一数据对象](#unifieddata)中各[数据记录](#unifiedrecord)的数据类型。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 值 | 说明 | +|----------------------------|------------------------------|-----------| +| TEXT | 'Text' | 文本类型。 | +| PLAIN_TEXT | 'Text.PlainText' | 纯文本类型。 | +| HYPERLINK | 'Text.Hyperlink' | 超链接类型。 | +| HTML | 'Text.HTML' | 富文本类型。 | +| FILE | 'File' | 文件类型。 | +| IMAGE | 'File.Media.Image' | 图片类型。 | +| VIDEO | 'File.Media.Video' | 视频类型。 | +| FOLDER | 'File.Folder' | 文件夹类型。 | +| SYSTEM_DEFINED_RECORD | 'SystemDefinedType' | 系统服务数据类型。 | +| SYSTEM_DEFINED_FORM | 'SystemDefinedType.Form' | 卡片类型。 | +| SYSTEM_DEFINED_APP_ITEM | 'SystemDefinedType.AppItem' | 图标类型。 | +| SYSTEM_DEFINED_PIXEL_MAP | 'SystemDefinedType.PixelMap' | 二进制图片类型。 | +| APPLICATION_DEFINED_RECORD | 'ApplicationDefinedType' | 应用自定义类型。 | + +## UnifiedData + +表示UDMF统一数据对象,提供封装一组数据记录的方法。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +### constructor + +constructor(record: UnifiedRecord) + +用于创建带有一条数据记录的统一数据对象。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------- | ---- |-----------------------------------------| +| record | [UnifiedRecord](#unifiedrecord) | 是 | 要添加到统一数据对象中的数据记录,该记录为UnifiedRecord子类对象。 | + +**示例:** + +```js +let text = new UDMF.PlainText(); +text.textContent = 'this is textContent of text'; +let unifiedData = new UDMF.UnifiedData(text); +``` + +### addRecord + +addRecord(record: UnifiedRecord): void + +在当前统一数据对象中添加一条数据记录。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------- | ---- |---------------------------------------------| +| record | [UnifiedRecord](#unifiedrecord) | 是 | 要添加到统一数据对象中的数据记录,该记录为UnifiedRecord子类对象。| + +**示例:** + +```js +let text1 = new UDMF.PlainText(); +text1.textContent = 'this is textContent of text1'; +let unifiedData = new UDMF.UnifiedData(text1); + +let text2 = new UDMF.PlainText(); +text2.textContent = 'this is textContent of text2'; +unifiedData.addRecord(text2); +``` + +### getRecords + +getRecords(): Array\ + +将当前统一数据对象中的所有数据记录取出。通过本接口取出的数据为UnifiedRecord类型,需通过[getType](#gettype)获取数据类型后转为子类再使用。 + +**系统能力** :SystemCapability.DistributedDataManager.UDMF.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- |-------------------------| +| Array\<[UnifiedRecord](#unifiedrecord)\> | 当前统一数据对象内所添加的记录。 | + +**示例:** + +```js +let text = new UDMF.PlainText(); +text.textContent = 'this is textContent of text'; +let unifiedData = new UDMF.UnifiedData(text); + +let link = new UDMF.HyperLink(); +link.url = 'www.XXX.com'; +unifiedData.addRecord(link); + +let records = unifiedData.getRecords(); +for (let i = 0; i < records.length; i++) { + let record = records[i]; + if (record.getType() == UDMF.UnifiedDataType.PLAIN_TEXT) { + let plainText = (record); + console.info(`textContent: ${plainText.textContent}`); + } else if (record.getType() == UDMF.UnifiedDataType.HYPERLINK) { + let hyperLink = (record); + console.info(`linkUrl: ${hyperLink.url}`); + } +} +``` + +## Summary + +描述某一统一数据对象的数据摘要,包括所含数据类型及大小,当前暂不支持。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ------------------------- | ---- | ---- |-----------------------------------------------------------------------------------| +| summary | { [key: string]: number } | 是 | 否 | 是一个字典类型对象,key表示数据类型(见[UnifiedDataType](#unifieddatatype)),value为统一数据对象中该类型记录大小总和(单位:Byte)。 | +| totalSize | number | 是 | 否 | 统一数据对象内记录总大小(单位:Byte)。 | + +## UnifiedRecord + +对UDMF支持的数据内容的抽象定义,称为数据记录。一个统一数据对象内包含一条或多条数据记录,例如一条文本记录、一条图片记录、一条HTML记录等。 + +UnifiedRecord是一个抽象父类,无法保存具体数据内容,应用在使用时,不能将其添加到统一数据对象中,而应该创建带有数据内容的具体子类,如Text、Image等。 + +### getType + +getType(): string + +获取当前数据记录的类型。由于从统一数据对象中调用[getRecords](#getrecords)所取出的数据是UnifiedRecord对象,因此需要通过本接口查询此记录的具体类型,再将该UnifiedRecord对象转换为其子类,调用子类接口。 + +**系统能力** :SystemCapability.DistributedDataManager.UDMF.Core + +**返回值:** + +| 类型 | 说明 | +| ------ |------------------------------------------------------| +| string | 当前数据记录对应的具体数据类型,见[UnifiedDataType](#UnifiedDataType)。| + +**示例:** + +```js +let text = new UDMF.PlainText(); +text.textContent = 'this is textContent of text'; +let unifiedData = new UDMF.UnifiedData(text); + +let records = unifiedData.getRecords(); +if (records[0].getType() == UDMF.UnifiedDataType.PLAIN_TEXT) { + let plainText = (records[0]); + console.info(`textContent: ${plainText.textContent}`); +} +``` + +## Text + +文本类型数据,是[UnifiedRecord](#unifiedrecord)的子类,也是文本类型数据的基类,用于描述文本类数据,推荐开发者优先使用Text的子类描述数据,如[PlainText](#plaintext)、[HyperLink](#hyperlink)、[HTML](#html)等具体子类。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------- | ------------------------- | ---- | ---- |-----------------------------------------------------------------------------------------------------------------------------------------------------| +| details | { [key: string]: string } | 是 | 是 | 是一个字典类型对象,key和value都是string类型,用于描述文本内容。例如,可生成一个details内容为
{
"title":"标题",
"content":"内容"
}
的数据对象,用于描述一篇文章。非必填字段,默认值为空字典对象。 | + +**示例:** + +```js +let text = new UDMF.Text(); +text.details = { + title: 'MyTitle', + content: 'this is content', +}; +let unifiedData = new UDMF.UnifiedData(text); +``` + +## PlainText + +纯文本类型数据,是[Text](#text)的子类,用于描述纯文本类数据。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------ | ---- | ---- |-----------------------| +| textContent | string | 是 | 是 | 纯文本内容。 | +| abstract | string | 是 | 是 | 纯文本摘要,非必填字段,默认值为空字符串。 | + +**示例:** + +```js +let text = new UDMF.PlainText(); +text.textContent = 'this is textContent'; +text.abstract = 'this is abstract'; +``` + +## HyperLink + +超链接类型数据,是[Text](#text)的子类,用于描述超链接类型数据。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------ | ---- | ---- |--------------| +| url | string | 是 | 是 | 链接url。 | +| description | string | 是 | 是 | 链接内容描述,非必填字段,默认值为空字符串。 | + +**示例:** + +```js +let link = new UDMF.HyperLink(); +link.url = 'www.XXX.com'; +link.description = 'this is description'; +``` + +## HTML + +HTML类型数据,是[Text](#text)的子类,用于描述超文本标记语言数据。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------ | ------ | ---- | ---- |-----------------------| +| htmlContent | string | 是 | 是 | html格式内容。 | +| plainContent | string | 是 | 是 | 去除html标签后的纯文本内容,非必填字段,默认值为空字符串。 | + +**示例:** + +```js +let html = new UDMF.HTML(); +html.htmlContent = '

标题

'; +html.plainContent = 'this is plainContent'; +``` + +## File + +File类型数据,是[UnifiedRecord](#unifiedrecord)的子类,也是文件类型数据的基类,用于描述文件类型数据,推荐开发者优先使用File的子类描述数据,如[Image](#image)、[Video](#video)、[Folder](#folder)等具体子类。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +|---------|---------------------------| ---- | ---- |------------------------------------------------------------------------------------------------------------------------------------------------------| +| details | { [key: string]: string } | 是 | 是 | 是一个字典类型对象,key和value都是string类型,用于描述文件相关信息。例如,可生成一个details内容为
{
"name":"文件名",
"type":"文件类型"
}
的数据对象,用于描述一个文件。非必填字段,默认值为空字典对象。 | +| uri | string | 是 | 是 | 文件数据uri。 | + +**示例:** + +```js +let file = new UDMF.File(); +file.details = { + name: 'test', + type: 'txt', +}; +file.uri = 'schema://com.samples.test/files/test.txt'; +``` + +## Image + +图片类型数据,是[File](#file)的子类,用于描述图片文件。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- |----------| +| imageUri | string | 是 | 是 | 图片数据uri。 | + +**示例:** + +```js +let image = new UDMF.Image(); +image.imageUri = 'schema://com.samples.test/files/test.jpg'; +``` + +## Video + +视频类型数据,是[File](#file)的子类,用于描述视频文件。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- |----------| +| videoUri | string | 是 | 是 | 视频数据uri。 | + +**示例:** + +```js +let video = new UDMF.Video(); +video.videoUri = 'schema://com.samples.test/files/test.mp4'; +``` + +## Folder + +文件夹类型数据,是[File](#file)的子类,用于描述文件夹。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- |---------| +| folderUri | string | 是 | 是 | 文件夹uri。 | + +**示例:** + +```js +let folder = new UDMF.Folder(); +folder.folderUri = 'schema://com.samples.test/files/folder/'; +``` + +## SystemDefinedRecord + +SystemDefinedRecord是[UnifiedRecord](#unifiedrecord)的子类,也是OpenHarmony系统特有数据类型的基类,用于描述仅在OpenHarmony系统范围内流通的特有数据类型,推荐开发者优先使用SystemDefinedRecord的子类描述数据,如[SystemDefinedForm](#systemdefinedform)、[SystemDefinedAppItem](#systemdefinedappitem)、[SystemDefinedPixelMap](#systemdefinedpixelmap)等具体子类。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------- |--------------------------| ---- | ---- | ------------------------------------------------------------ | +| details | { [key: string]: number \| string \| Uint8Array } | 是 | 是 | 是一个字典类型对象,key是string类型,value可以写入number(数值类型)、string(字符串类型)、Uint8Array(二进制字节数组)类型数据。非必填字段,默认值为空字典对象。| + +**示例:** + +```js +let sdr = new UDMF.SystenDefinedReocrd(); +let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +sdr.details = { + title: 'recordTitle', + version: 1, + content: u8Array, +}; +let unifiedData = new UDMF.UnifiedData(sdr); +``` + +## SystemDefinedForm + +卡片类型数据,是[SystemDefinedRecord](#systemdefinedrecord)的子类。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------ | ---- | ---- |----------------| +| formId | number | 是 | 是 | 卡片id。 | +| formName | string | 是 | 是 | 卡片名称。 | +| bundleName | string | 是 | 是 | 卡片所属的bundle名。 | +| abilityName | string | 是 | 是 | 卡片对应的ability名。 | +| module | string | 是 | 是 | 卡片所属的module名。 | + +**示例:** + +```js +let form = new UDMF.SystemDefinedForm(); +form.formId = 123456; +form.formName = 'MyFormName'; +form.bundleName = 'MyBundleName'; +form.abilityName = 'MyAbilityName'; +form.module = 'MyModule'; +let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +form.details = { + formKey1: 123, + formKey2: 'formValue', + formKey3: u8Array, +}; +let unifiedData = new UDMF.UnifiedData(form); +``` + +## SystemDefinedAppItem + +图标类型数据,是[SystemDefinedRecord](#systemdefinedrecord)的子类。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------ | ---- | ---- |-----------------| +| appId | string | 是 | 是 | 图标对应的应用id。 | +| appName | string | 是 | 是 | 图标对应的应用名。 | +| appIconId | string | 是 | 是 | 图标的图片id。 | +| appLabelId | string | 是 | 是 | 图标名称对应的标签id。 | +| bundleName | string | 是 | 是 | 图标对应的应用bundle名。 | +| abilityName | string | 是 | 是 | 图标对应的应用ability名。 | + +**示例:** + +```js +let appItem = new UDMF.SystemDefinedAppItem(); +appItem.appId = 'MyAppId'; +appItem.appName = 'MyAppName'; +appItem.appIconId = 'MyAppIconId'; +appItem.appLabelId = 'MyAppLabelId'; +appItem.bundleName = 'MyBundleName'; +appItem.abilityName = 'MyAbilityName'; +let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +appItem.details = { + appItemKey1: 123, + appItemKey2: 'appItemValue', + appItemKey3: u8Array, +}; +let unifiedData = new UDMF.UnifiedData(appItem); +``` + +## SystemDefinedPixelMap + +与系统侧定义的[PixelMap](js-apis-image.md#pixelmap7)数据类型对应的图片数据类型,是[SystemDefinedRecord](#systemdefinedrecord)的子类,仅保存PixelMap的二进制数据。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------- | ---------- | ---- | ---- |-------------------| +| rawData | Uint8Array | 是 | 是 | PixelMap对象的二进制数据。 | + +**示例:** + +```js +import image from '@ohos.multimedia.image'; // PixelMap类定义所在模块 + +const color = new ArrayBuffer(96); // 创建pixelmap对象 +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (error, pixelmap) => { + if(error) { + console.log('Failed to create pixelmap.'); + } else { + console.log('Succeeded in creating pixelmap.'); + let arrayBuf = new ArrayBuffer(pixelmap.getPixelBytesNumber()); + pixelmap.readPixelsToBuffer(arrayBuf); + let u8Array = new Uint8Array(arrayBuf); + let sdpixel = new UDMF.SystemDefinedPixelMap(); + sdpixel.rawData = u8Array; + let unifiedData = new UDMF.UnifiedData(sdpixel); + } +}) +``` + +## ApplicationDefinedRecord + +ApplicationDefinedRecord是[UnifiedRecord](#unifiedrecord)的子类,也是应用自定义数据类型的基类,用于描述仅在应用生态内部流通的自定义数据类型,应用可基于此类进行自定义数据类型的扩展。 + +**系统能力**:SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +|------------------------|------------| ---- | ---- |---------------------------------------| +| applicationDefinedType | string | 是 | 是 | 应用自定义类型标识符,必须以'ApplicationDefined'开头。 | +| rawData | Uint8Array | 是 | 是 | 应用自定义数据类型的二进制数据。 | + +**示例:** + +```js +let record = new UDMF.ApplicationDefinedRecord(); +let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +record.applicationDefinedType = 'ApplicationDefinedType'; +record.rawData = u8Array; +let unifiedData = new UDMF.UnifiedData(record); +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-http.md b/zh-cn/application-dev/reference/apis/js-apis-http.md index bf34a19c164df7be8f46b16ccb2d098e7d6be575..516f58d1977bce818c3d0987cf1b5deff8650c7e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-http.md +++ b/zh-cn/application-dev/reference/apis/js-apis-http.md @@ -55,6 +55,8 @@ httpRequest.request( // data.header为HTTP响应头,可根据业务需要进行解析 console.info('header:' + JSON.stringify(data.header)); console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ + // 当该请求使用完毕时,调用destroy方法主动销毁 + httpRequest.destroy(); } else { console.info('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件 diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 083085edba4d8c32b28c5ba19c822918642ffbf5..d2c9e1e07f40c3545cea3b752e17ec9a3b2b729d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -865,8 +865,8 @@ call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCa | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | method | string | 是 | 指示被调用的方法名。 | | arg | string | 是 | 指示需传入的参数。 | -| extras | [PacMap](js-apis-inner-application-pacMap.md) | 是 | 指示扩展的键值对参数。 | -| callback | AsyncCallback\<[PacMap](js-apis-inner-application-pacMap.md)> | 是 | 指示数据操作的回调方法,返回操作结果。 | +| extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | 是 | 指示扩展的键值对参数。 | +| callback | AsyncCallback\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | 是 | 指示数据操作的回调方法,返回操作结果。 | **示例:** @@ -901,13 +901,13 @@ call(uri: string, method: string, arg: string, extras: PacMap): Promise\ | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | method | string | 是 | 指示被调用的方法名。 | | arg | string | 是 | 指示需传入的参数。 | -| extras | [PacMap](js-apis-inner-application-pacMap.md) | 是 | 指示扩展的键值对参数。 | +| extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | 是 | 指示扩展的键值对参数。 | **返回值:** | 类型 | 说明 | |------ | ------- | -|Promise\<[PacMap](js-apis-inner-application-pacMap.md)> | 返回操作结果。 | +|Promise\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | 返回操作结果。 | **示例:** @@ -997,4 +997,14 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi console.error('executeBatch failed, error: ${error}'); }); -``` \ No newline at end of file +``` + +## PacMap + +[key: string]: number | string | boolean | Array\ | null; + +**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel + +| 参数名 | 参数类型 | 必填 | 说明 | +| ------ | ------ | ------ | ------ | +| [key: string] | number \| string \| boolean \| Array\ \| null | Yes| 数据存储在键值对中。| \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md index 5f0bb262f96daf1711bf7d55e9614be799194df5..97f8b12c1060d0a2ac1983c43e562666d2866fc2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -72,6 +72,6 @@ import Want from '@ohos.app.ability.Want'; // ... ``` -- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want +- 更多详细说明和示例请参见: [应用模型](../../application-models/application-model-composition.md)的信息传递载体Want \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index 301daa43f3a1c251a201d7c6393d9b80ed604d6c..16948647fc00fa4e2c6ebcec719f80da2dc4aa6f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -610,7 +610,7 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.BarrierFree.Accessibility.Core -## attributeNames +### attributeNames attributeNames\(): Promise\>; @@ -636,7 +636,7 @@ rootElement.attributeNames().then((data) => { console.log('failed to get attribute names, because ${JSON.stringify(err)}'); }); ``` -## attributeNames +### attributeNames attributeNames\(callback: AsyncCallback\>): void; @@ -664,7 +664,7 @@ rootElement.attributeNames((err, data) => { console.info('get attribute names success'); }); ``` -## AccessibilityElement.attributeValue +### attributeValue attributeValue\(attributeName: T): Promise\; @@ -709,7 +709,7 @@ try { console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` -## AccessibilityElement.attributeValue +### attributeValue attributeValue\(attributeName: T, callback: AsyncCallback\): void; @@ -752,7 +752,7 @@ try { console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` -## actionNames +### actionNames actionNames(): Promise\>; @@ -778,7 +778,7 @@ rootElement.actionNames().then((data) => { console.error('failed to get action names because ${JSON.stringify(err)}'); }); ``` -## actionNames +### actionNames actionNames(callback: AsyncCallback\>): void; @@ -806,7 +806,7 @@ rootElement.actionNames((err, data) => { console.info('get action names success'); }); ``` -## performAction +### performAction performAction(actionName: string, parameters?: object): Promise\; @@ -849,7 +849,7 @@ try { console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` -## performAction +### performAction performAction(actionName: string, callback: AsyncCallback\): void; @@ -888,7 +888,7 @@ try { console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` -## performAction +### performAction performAction(actionName: string, parameters: object, callback: AsyncCallback\): void; @@ -932,7 +932,7 @@ try { console.error('failed to perform action, because ${JSON.stringify(exception)}'); } ``` -## findElement('content') +### findElement('content') findElement(type: 'content', condition: string): Promise\>; @@ -971,7 +971,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('content') +### findElement('content') findElement(type: 'content', condition: string, callback: AsyncCallback\>): void; @@ -1007,7 +1007,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusType') +### findElement('focusType') findElement(type: 'focusType', condition: FocusType): Promise\; @@ -1046,7 +1046,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusType') +### findElement('focusType') findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\): void; @@ -1082,7 +1082,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusDirection') +### findElement('focusDirection') findElement(type: 'focusDirection', condition: FocusDirection): Promise\; @@ -1121,7 +1121,7 @@ try { console.error('failed to find element, because ${JSON.stringify(exception)}'); } ``` -## findElement('focusDirection') +### findElement('focusDirection') findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\): void; diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index f26db7ba6695bd6f97a3c9abc4be306b52f97cac..dc49d568e50613a19cf36428932e51871a9fde1a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -43,5 +43,5 @@ let applicationStateObserver = { console.log('onProcessStateChanged onProcessStateChanged: ${JSON.stringify(processData)}'); } }; -let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); +let observerCode = appManager.on('applicationState', applicationStateObserver); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-multimedia-ringtonePlayer.md b/zh-cn/application-dev/reference/apis/js-apis-inner-multimedia-ringtonePlayer.md new file mode 100644 index 0000000000000000000000000000000000000000..bae009565a896fb3add165e9a5f1721ac5c54d75 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-multimedia-ringtonePlayer.md @@ -0,0 +1,471 @@ +# ringtonePlayer (铃声播放器) + +铃声播放器提供了系统铃声的播放、配置、获取信息等功能。 + +ringtonePlayer需要和[@ohos.multimedia.systemSoundManager](js-apis-systemSoundManager.md)配合使用,才能完成管理系统铃声的功能。 + +> **说明:** +> +> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 本模块接口为系统接口。 + +## 导入模块 + +```js +import systemSoundManager from '@ohos.multimedia.systemSoundManager'; +``` + +## RingtoneOptions + +铃声参数选项。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +| 名称 | 类型 |必填 | 说明 | +| --------- | -------------- | ---- | --------------------------------- | +| volume | number | 是 | 指定的相对音量大小,取值范围为[0.00, 1.00],1表示最大音量,即100%。 | +| loop | boolean | 是 | 是否开启循环播放,true表示开启循环播放,false表示不开启循环播放。 | + +## RingtonePlayer + +系统铃声播放器,提供系统铃声的参数设置、参数获取、播放、停止等功能。在调用RingtonePlayer的接口前,需要先通过[getSystemRingtonePlayer](js-apis-systemSoundManager.md#getsystemringtoneplayer)创建实例。 + +### 属性 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | -------------------------- | ---- | ---- | ------------------ | +| state | [media.AVPlayerState](js-apis-media.md#avplayerstate9) | 是 | 否 | 音频渲染器的状态。 | + +**示例:** + +```js +let state = systemRingtonePlayer.state; +``` + +### getTitle + +getTitle(callback: AsyncCallback<string>): void + +获取铃声标题,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<string> | 是 | 回调返回获取的铃声标题。 | + +**示例:** + +```js +systemRingtonePlayer.getTitle((err, value) => { + if (err) { + console.error(`Failed to get system ringtone title. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the system ringtone title is obtained ${value}.`); +}); +``` + +### getTitle + +getTitle(): Promise<string> + +获取铃声标题,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------- | -------------------------------- | +| Promise<string> | Promise回调返回获取的系统铃声标题。 | + +**示例:** + +```js +systemRingtonePlayer.getTitle().then((value) => { + console.info(`Promise returned to indicate that the value of the system ringtone title is obtained ${value}.`); +}).catch ((err) => { + console.error(`Failed to get the system ringtone title ${err}`); +}); +``` + +### getAudioRendererInfo + +getAudioRendererInfo(callback: AsyncCallback<audio.AudioRendererInfo>): void + +获取铃声使用的AudioRendererInfo,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<[audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8)> | 是 | 回调返回获取的AudioRendererInfo。 | + +**示例:** + +```js +import audio from '@ohos.multimedia.audio'; + +let audioRendererInfo: audio.AudioRendererInfo = null; + +systemRingtonePlayer.getAudioRendererInfo((err, value) => { + if (err) { + console.error(`Failed to get ringtone AudioRendererInfo. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the ringtone AudioRendererInfo is obtained.`); + audioRendererInfo = value; +}); +``` + +### getAudioRendererInfo + +getAudioRendererInfo(): Promise<audio.AudioRendererInfo> + +获取铃声使用的AudioRendererInfo,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<[audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8)> | Promise回调返回获取的AudioRendererInfo。 | + +**示例:** + +```js +import audio from '@ohos.multimedia.audio'; + +let audioRendererInfo: audio.AudioRendererInfo = null; + +systemRingtonePlayer.getAudioRendererInfo().then((value) => { + console.info(`Promise returned to indicate that the value of the ringtone AudioRendererInfo is obtained ${value}.`); + audioRendererInfo = value; +}).catch ((err) => { + console.error(`Failed to get the ringtone AudioRendererInfo ${err}`); +}); +``` + +### configure + +configure(options: RingtoneOptions, callback: AsyncCallback<void>): void + +配置铃声播放参数,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | ------------------------- | +| options | [RingtoneOptions](#ringtoneoptions) | 是 | 指定铃声参数。 | +| callback | AsyncCallback<void> | 是 | 回调返回配置参数成功或失败。 | + +**示例:** + +```js +let ringtoneOptions = {volume: 0.5, loop: true}; + +systemRingtonePlayer.configure(ringtoneOptions, (err) => { + if (err) { + console.error(`Failed to configure ringtone options. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful setting of ringtone options.`); +}); +``` + +### configure + +configure(options: RingtoneOptions): Promise<void> + +配置铃声播放参数,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | ------------------------- | +| options | [RingtoneOptions](#ringtoneoptions) | 是 | 指定铃声参数。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回配置参数成功或失败。 | + +**示例:** + +```js +let ringtoneOptions = {volume: 0.5, loop: true}; + +systemRingtonePlayer.configure(ringtoneOptions).then(() => { + console.info(`Promise returned to indicate a successful setting of ringtone options.`); +}).catch ((err) => { + console.error(`Failed to configure ringtone options. ${err}`); +}); +``` + +### start + +start(callback: AsyncCallback<void>): void + +开始播放铃声,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<void> | 是 | 回调返回开始播放成功或失败。 | + +**示例:** + +```js +systemRingtonePlayer.start((err) => { + if (err) { + console.error(`Failed to start playing ringtone. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful starting of ringtone.`); +}); +``` + +### start + +start(): Promise<void> + +开始播放铃声,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| Promise<void> | Promise回调返回开始播放成功或失败。 | + +**示例:** + +```js +systemRingtonePlayer.start().then(() => { + console.info(`Promise returned to indicate a successful starting of ringtone.`); +}).catch ((err) => { + console.error(`Failed to start playing ringtone. ${err}`); +}); +``` + +### stop + +stop(callback: AsyncCallback<void>): void + +停止播放铃声,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<void> | 是 | 回调返回停止播放成功或失败。 | + +**示例:** + +```js +systemRingtonePlayer.stop((err) => { + if (err) { + console.error(`Failed to stop playing ringtone. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful stopping of ringtone.`); +}); +``` + +### stop + +stop(): Promise<void> + +停止播放铃声,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| Promise<void> | Promise回调返回停止播放成功或失败。 | + +**示例:** + +```js +systemRingtonePlayer.stop().then(() => { + console.info(`Promise returned to indicate a successful stopping of ringtone.`); +}).catch ((err) => { + console.error(`Failed to stop playing ringtone. ${err}`); +}); +``` + +### release + +release(callback: AsyncCallback<void>): void + +释放铃声播放器,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | ------------------------- | +| callback | AsyncCallback<void> | 是 | 回调返回释放成功或失败。 | + +**示例:** + +```js +systemRingtonePlayer.release((err) => { + if (err) { + console.error(`Failed to release ringtone player. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful releasing of ringtone player.`); +}); +``` + +### release + +release(): Promise<void> + +释放铃声播放器,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回释放成功或失败。 | + +**示例:** + +```js +systemRingtonePlayer.release().then(() => { + console.info(`Promise returned to indicate a successful releasing of ringtone player.`); +}).catch ((err) => { + console.error(`Failed to release ringtone player. ${err}`); +}); +``` + +### on('audioInterrupt') + +on(type: 'audioInterrupt', callback: Callback<audio.InterruptEvent>): void + +监听音频中断事件。使用callback获取中断事件。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------------------------------------------- | +| type | string | 是 | 事件回调类型,支持的事件为:'audioInterrupt'(中断事件被触发,音频渲染被中断)。 | +| callback | Callback<[audio.InterruptEvent](js-apis-audio.md#interruptevent9)> | 是 | 被监听的中断事件的回调。 | + +**错误码:** + +以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。 + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------| +| 401 | if input parameter type or number mismatch | +| 6800101 | if input parameter value error | + +**示例:** + +```js +import audio from '@ohos.multimedia.audio'; + +let isPlaying; // 标识符,表示是否正在渲染 +let isDucked; // 标识符,表示是否被降低音量 + +systemRingtonePlayer.on('audioInterrupt', async(interruptEvent) => { +if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + // 由系统进行操作,强制打断音频渲染,应用需更新自身状态及显示内容等 + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + // 音频流已被暂停,临时失去焦点,待可重获焦点时会收到resume对应的interruptEvent + console.info('Force paused. Update playing status and stop writing'); + isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作 + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + // 音频流已被停止,永久失去焦点,若想恢复渲染,需用户主动触发 + console.info('Force stopped. Update playing status and stop writing'); + isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作 + break; + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + // 音频流已被降低音量渲染 + console.info('Force ducked. Update volume status'); + isDucked = true; // 简化处理,代表应用更新音量状态的若干操作 + break; + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + // 音频流已被恢复正常音量渲染 + console.info('Force ducked. Update volume status'); + isDucked = false; // 简化处理,代表应用更新音量状态的若干操作 + break; + default: + break; + } +} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + // 由应用进行操作,应用可以自主选择响应操作或忽略该事件 + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + // 建议应用继续渲染(说明音频流此前被强制暂停,临时失去焦点,现在可以恢复渲染) + console.info('Resume force paused renderer or ignore'); + // 若选择继续渲染,需在此处主动执行开始渲染的若干操作 + break; + default: + break; + } +} +}); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md index 4a4221f926e124eaf199c3562229881d0753ee0d..21a1a1b7c0f3e295e1103253faaf4558779b88f5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -953,7 +953,7 @@ setUiContent(path: string, storage: LocalStorage, callback: AsyncCallback\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | -------- | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。| +| storage | [LocalStorage](../arkui-ts/ts-state-management.md#localstorage9) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。| | callback | AsyncCallback\ | 是 | 回调函数。当面板页面内容加载成功,err为undefined,否则err为错误对象。 | **示例:** @@ -987,7 +987,7 @@ setUiContent(path: string, storage: LocalStorage): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | -------- | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。| +| storage | [LocalStorage](../arkui-ts/ts-state-management.md#localstorage9) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。| **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-logs.md b/zh-cn/application-dev/reference/apis/js-apis-logs.md index 8dea3732ed6db1e3bdc49af9232c15e7089d8b37..58fa874d7e940498489de44706779a09fa43742e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-logs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-logs.md @@ -19,9 +19,10 @@ debug(message: string, ...arguments: any[]): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ----------- | | message | string | 是 | 表示要打印的文本信息。 | -| arguments | any | 否 | 表示其余要打印的信息或message的替换值。 | +| arguments | any[] | 否 | 表示其余要打印的信息或message的替换值。 | **示例:** + ```js const number = 5; console.debug('count: %d', number); // 格式化输出替换message中的文本。 @@ -45,9 +46,10 @@ log(message: string, ...arguments: any[]): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ----------- | | message | string | 是 | 表示要打印的文本信息。 | -| arguments | any | 否 |表示其余要打印的信息或message的替换值。 | +| arguments | any[] | 否 |表示其余要打印的信息或message的替换值。 | **示例:** + ```js const number = 5; console.log('count: %d', number); // 格式化输出替换message中的文本。 @@ -71,9 +73,10 @@ info(message: string, ...arguments: any[]): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ----------- | | message | string | 是 | 表示要打印的文本信息。 | -| arguments | any | 否 | 表示其余要打印的信息或message的替换值。 | +| arguments | any[] | 否 | 表示其余要打印的信息或message的替换值。 | **示例:** + ```js const number = 5; console.info('count: %d', number); // 格式化输出替换message中的文本。 @@ -97,9 +100,10 @@ warn(message: string, ...arguments: any[]): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ----------- | | message | string | 是 | 表示要打印的警告信息。 | -| arguments | any | 否 | 表示其余要打印的信息或message的替换值。 | +| arguments | any[] | 否 | 表示其余要打印的信息或message的替换值。 | **示例:** + ```js const str = "name should be string"; console.warn('warn: %d', str); // 格式化输出替换message中的文本。 @@ -123,10 +127,11 @@ error(message: string, ...arguments: any[]): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ----------- | | message | string | 是 | 表示要打印的错误信息。 | -| arguments | any | 否 | 表示其余要打印的信息或message的替换值。 | +| arguments | any[] | 否 | 表示其余要打印的信息或message的替换值。 | **示例:** + ```js const str = "value is not defined"; console.error('error: %d', str); // 格式化输出替换message中的文本。 @@ -153,6 +158,7 @@ assert(value?: Object, ...arguments: Object[]): void | arguments | Object | 否 | value为假(false)的后续错误消息打印。省略则不打印。| **示例:** + ```js console.assert(true, 'does nothing'); // 表达式结果值为true, 无打印。 console.assert(2 % 1 == 0, 'does nothing'); // 表达式结果值为true, 无打印。 @@ -180,6 +186,7 @@ count(label?: string): void **示例:** + ```js console.count() // default: 1 @@ -210,6 +217,7 @@ countReset(label?: string): void | label | string | 否 | 计数器标签名。默认值为'default'。| **示例:** + ```js console.count('abc'); // abc: 1 @@ -234,6 +242,7 @@ dir(dir?: Object): void **示例:** + ```js let a = { foo: { bar: { baz: true } }}; console.dir(a); @@ -258,6 +267,7 @@ dirxml(...arguments: Object[]): void | arguments | Object | 是 | 要打印的信息。 | **示例:** + ```js const number = 5; console.dirxml('count: %d', number); @@ -284,6 +294,7 @@ group(...arguments: Object[]): void | arguments | Object | 否 | 要打印的信息。 | **示例:** + ```js console.log("outter"); // outter @@ -313,6 +324,7 @@ groupCollapsed(...arguments: Object[]): void **示例:** + ```js console.groupCollapsed("outter"); // outter @@ -335,6 +347,7 @@ groupEnd(): void **示例:** + ```js console.log("outter"); // outter @@ -362,6 +375,7 @@ table(tableData?: Object): void | tableData | Object | 否 | 要打印为表格形式的对象。省略则无任何打印。 | **示例:** + ```js console.table([1, 2, 3]); // ┌─────────┬────────┐ @@ -382,6 +396,7 @@ console.table({ a: [1, 2, 3, 4, 5], b: 5, c: { e: 5 } }); // │ c │ │ │ │ │ │ 5 │ │ // └─────────┴───┴───┴───┴───┴───┴───┴────────┘ ``` + ## console.time10+ time(label?: string): void @@ -397,6 +412,7 @@ time(label?: string): void | label | string | 否 | 计时器标识。默认值为'default'。 | **示例:** + ```js console.time('abc'); ``` @@ -416,6 +432,7 @@ timeEnd(label?: string): void | label | string | 否 | 计时器标识。默认值为'default' | **示例:** + ```js console.time('abc'); console.timeEnd('abc'); @@ -438,6 +455,7 @@ timeLog(label?: string, ...arguments: Object[]): void | arguments | Object | 否 | 需要打印的其他日志。 | **示例:** + ```js console.time('timer1'); console.timeLog('timer1', 17); @@ -461,6 +479,7 @@ trace(...arguments: Object[]): void | arguments | Object | 否 | 需要打印的其他日志。省略则仅打印堆栈信息。| **示例:** + ```js console.trace(); // Trace: diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index 23c7178e3472d55228a76b70fbcd20fd70166316..a0464c42c0ff9a00722a388d8e93f6780caa6206 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -318,7 +318,7 @@ Codec MIME类型枚举。 | MD_KEY_BITRATE | 'bitrate' | 表示比特率,其对应键值类型为number,单位为比特率(bps)。 | | MD_KEY_WIDTH | 'width' | 表示视频宽度,其对应键值类型为number,单位为像素(px)。 | | MD_KEY_HEIGHT | 'height' | 表示视频高度,其对应键值类型为number,单位为像素(px)。 | -| MD_KEY_FRAME_RATE | 'frame_rate' | 表示视频帧率,其对应键值类型为number,单位为帧每秒(fps)。 | +| MD_KEY_FRAME_RATE | 'frame_rate' | 表示视频帧率,其对应键值类型为number,单位为100帧每秒(100fps)。 | | MD_KEY_AUD_CHANNEL_COUNT | 'channel_count' | 表示声道数,其对应键值类型为number。 | | MD_KEY_AUD_SAMPLE_RATE | 'sample_rate' | 表示采样率,其对应键值类型为number,单位为赫兹(Hz)。 | @@ -358,9 +358,9 @@ Audio/Video播放demo可参考:[音频播放开发指导](../../media/using-av | 名称 | 类型 | 可读 | 可写 | 说明 | | --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| url9+ | string | 是 | 是 | 媒体URL,只允许在**idle**状态下设置,静态属性。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav)。
**支持路径示例**:
1. fd类型播放:fd://xx。
![](figures/zh-cn_image_url.png)
2. http网络播放: http://xx。
3. https网络播放: https://xx。
4. hls网络播放路径:http://xx或者https://xx。 | -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 媒体文件描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用中的媒体资源被连续存储在同一个文件中。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav)。
**使用示例**:
假设一个连续存储的媒体文件:
视频1(地址偏移:0,字节长度:100);
视频2(地址偏移:101,字节长度:50);
视频3(地址偏移:151,字节长度:150);
1. 播放视频1:AVFileDescriptor { fd = 资源句柄; offset = 0; length = 100; }。
2. 播放视频2:AVFileDescriptor { fd = 资源句柄; offset = 101; length = 50; }。
3. 播放视频3:AVFileDescriptor { fd = 资源句柄; offset = 151; length = 150; }。
假设是一个独立的媒体文件: 请使用src=fd://xx。 | -| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | 是 | 是 | 流式媒体资源描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用播放从远端下载到本地的文件,在应用未下载完整音视频资源时,提前播放已获取的资源文件。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav)。
**使用示例**:
假设用户正在从远端服务器获取音视频媒体文件,希望下载到本地的同时播放已经下载好的部分:
1.用户需要获取媒体文件的总大小size(单位为字节),获取不到时设置为-1。
2.用户需要实现回调函数func用于填写数据,如果size = -1,则func形式为:func(buffer: ArrayBuffer, length: number),此时播放器只会按照顺序获取数据;否则func形式为:func(buffer: ArrayBuffer, length: number, pos: number),播放器会按需跳转并获取数据。
3.用户设置AVDataSrcDescriptor {fileSize = size, callback = func}。
**注意事项**:
如果播放的是mp4/m4a格式用户需要保证moov字段(媒体信息字段)在mdat字段(媒体数据字段)之前,或者moov之前的字段小于10M,否则会导致解析失败无法播放。 | +| url9+ | string | 是 | 是 | 媒体URL,只允许在**idle**状态下设置,静态属性。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。
**支持路径示例**:
1. fd类型播放:fd://xx。
![](figures/zh-cn_image_url.png)
2. http网络播放: http://xx。
3. https网络播放: https://xx。
4. hls网络播放路径:http://xx或者https://xx。 | +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 媒体文件描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用中的媒体资源被连续存储在同一个文件中。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。
**使用示例**:
假设一个连续存储的媒体文件:
视频1(地址偏移:0,字节长度:100);
视频2(地址偏移:101,字节长度:50);
视频3(地址偏移:151,字节长度:150);
1. 播放视频1:AVFileDescriptor { fd = 资源句柄; offset = 0; length = 100; }。
2. 播放视频2:AVFileDescriptor { fd = 资源句柄; offset = 101; length = 50; }。
3. 播放视频3:AVFileDescriptor { fd = 资源句柄; offset = 151; length = 150; }。
假设是一个独立的媒体文件: 请使用src=fd://xx。 | +| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | 是 | 是 | 流式媒体资源描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用播放从远端下载到本地的文件,在应用未下载完整音视频资源时,提前播放已获取的资源文件。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。
**使用示例**:
假设用户正在从远端服务器获取音视频媒体文件,希望下载到本地的同时播放已经下载好的部分:
1.用户需要获取媒体文件的总大小size(单位为字节),获取不到时设置为-1。
2.用户需要实现回调函数func用于填写数据,如果size = -1,则func形式为:func(buffer: ArrayBuffer, length: number),此时播放器只会按照顺序获取数据;否则func形式为:func(buffer: ArrayBuffer, length: number, pos: number),播放器会按需跳转并获取数据。
3.用户设置AVDataSrcDescriptor {fileSize = size, callback = func}。
**注意事项**:
如果播放的是mp4/m4a格式用户需要保证moov字段(媒体信息字段)在mdat字段(媒体数据字段)之前,或者moov之前的字段小于10M,否则会导致解析失败无法播放。 | | surfaceId9+ | string | 是 | 是 | 视频窗口ID,默认无窗口,只允许在**initialized**状态下设置,静态属性。
使用场景:视频播放的窗口渲染,纯音频播放不用设置。
**使用示例**:
[通过Xcomponent创建surfaceId](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid)。 | | loop9+ | boolean | 是 | 是 | 视频循环播放属性,默认'false',设置为'true'表示循环播放,动态属性。
只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。
直播场景不支持loop设置。 | | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式,默认VIDEO_SCALE_TYPE_FIT_CROP,动态属性。
只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md b/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md index 5244b2c693a4c372a6cdf2e0e5a2272f9b36cd67..44a24be4f6bed086ce2a089b45b752f3b537035d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md +++ b/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @@ -5,6 +5,8 @@ > **说明:** > > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)中使用。 ## 导入模块 diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md index c8ea47c3362685912a7ad6988523f9e3092d8733..b65f72de56095cce9f97b7cf9be04af2c439938e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @@ -767,7 +767,7 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 | uid9+ | number[] | 是 | 否 | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。 | | technology9+ | number[] | 是 | 否 | 支持的技术类型,每个number值表示所支持技术类型的常量值。 | | supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#tagtaginfo)替代。 | -| extrasData9+ | [PacMap](js-apis-inner-application-pacMap.md)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。 | +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。 | | tagRfDiscId9+ | number | 是 | 否 | 标签发现时分配的ID值。
**系统接口:** 此接口为系统接口。 | | remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | 是 | 否 | NFC服务进程的远端对象,用于客户端和服务之间的接口通信。
**系统接口:** 此接口为系统接口。 | ## NdefRecord9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md index 98aae969e6c7dfda52cb14cc76beada258be5378..0163d488caf265565ac25d3684a7f2d95071469d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-promptAction.md +++ b/zh-cn/application-dev/reference/apis/js-apis-promptAction.md @@ -5,6 +5,8 @@ > **说明:** > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 该模块不支持在[UIAbility](./js-apis-app-ability-uiAbility.md)中使用。 ## 导入模块 diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md index 8a4cd0b5111672f6bb0790ad98ee05d4204d132e..aff26fccbdebbf790a49c8498e4cf18f29d8a9d4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @@ -20,25 +20,23 @@ import reminderAgent from'@ohos.reminderAgent'; ## reminderAgent.publishReminder(deprecated) -```ts publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void -``` 发布一个后台代理提醒,使用回调的方式实现异步调用,该方法需要申请通知弹窗权限[Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8)后才能调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.publishReminder](js-apis-reminderAgentManager.md#reminderagentmanagerpublishreminder)替代。 -**需要权限**: `ohos.permission.PUBLISH_AGENT_REMINDER` +**需要权限**: ohos.permission.PUBLISH_AGENT_REMINDER -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | 是 | 需要发布的提醒实例。 | - | callback | AsyncCallback\ | 是 | 异步回调,返回当前发布的提醒的id。 | + | callback | AsyncCallback\ | 是 | 异步回调,返回当前发布的提醒的id。 | **示例**: ```ts @@ -55,18 +53,16 @@ publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): ## reminderAgent.publishReminder(deprecated) -```ts publishReminder(reminderReq: ReminderRequest): Promise\ -``` 发布一个后台代理提醒,使用Promise方式实现异步调用,该方法需要申请通知弹窗权限[Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8)后才能调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.publishReminder](js-apis-reminderAgentManager.md#reminderagentmanagerpublishreminder-1)替代。 -**需要权限**: `ohos.permission.PUBLISH_AGENT_REMINDER` +**需要权限**: ohos.permission.PUBLISH_AGENT_REMINDER -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -76,7 +72,7 @@ publishReminder(reminderReq: ReminderRequest): Promise\ **返回值**: | 类型 | 说明 | | -------- | -------- | - | Promise\ | 返回提醒的Id。 | + | Promise\ | 返回提醒的Id。 | **示例**: ```ts @@ -93,23 +89,21 @@ publishReminder(reminderReq: ReminderRequest): Promise\ ## reminderAgent.cancelReminder(deprecated) -```ts cancelReminder(reminderId: number, callback: AsyncCallback\): void -``` 取消指定id的提醒,使用回调的方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.cancelReminder](js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | reminderId | number | 是 | 目标reminder的id号,[publishReminder](#reminderagentpublishreminder)方法调用成功后获得。 | -| callback | AsyncCallback\ | 是 | 异步回调。 | +| callback | AsyncCallback\ | 是 | 异步回调。 | **示例**: @@ -122,16 +116,14 @@ reminderAgent.cancelReminder(1, (err, data) => { ## reminderAgent.cancelReminder(deprecated) -```ts cancelReminder(reminderId: number): Promise\ -``` 取消指定id的提醒,使用Promise方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.cancelReminder](js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder-1)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: @@ -143,7 +135,7 @@ cancelReminder(reminderId: number): Promise\ | 类型 | 说明 | | -------- | -------- | -| Promise\ | Promise类型异步回调。 | +| Promise\ | Promise类型异步回调。 | **示例**: @@ -155,22 +147,20 @@ reminderAgent.cancelReminder(1).then(() => { ## reminderAgent.getValidReminders(deprecated) -```ts getValidReminders(callback: AsyncCallback\>): void -``` 获取当前应用已设置的所有有效(未过期)的提醒,使用回调的方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.getValidReminders](js-apis-reminderAgentManager.md#reminderagentmanagergetvalidreminders)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\\> | 是 | 异步回调,返回当前应用已设置的所有有效(未过期)的提醒。 | +| callback | AsyncCallback\> | 是 | 异步回调,返回当前应用已设置的所有有效(未过期)的提醒。 | **示例**: @@ -204,22 +194,20 @@ reminderAgent.getValidReminders((err, reminders) => { ## reminderAgent.getValidReminders(deprecated) -```ts getValidReminders(): Promise\> -``` 获取当前应用已设置的所有有效(未过期)的提醒,使用Promise方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.getValidReminders](js-apis-reminderAgentManager.md#reminderagentmanagergetvalidreminders-1)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **返回值**: | 类型 | 说明 | | -------- | -------- | -| Promise\\> | 返回当前应用已设置的所有有效(未过期)的提醒。 | +| Promise\> | 返回当前应用已设置的所有有效(未过期)的提醒。 | **示例**: @@ -253,22 +241,20 @@ reminderAgent.getValidReminders().then((reminders) => { ## reminderAgent.cancelAllReminders(deprecated) -```ts cancelAllReminders(callback: AsyncCallback\): void -``` 取消当前应用所有的提醒,使用回调的方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.cancelAllReminders](js-apis-reminderAgentManager.md#reminderagentmanagercancelallreminders)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\ | 是 | 异步回调。 | +| callback | AsyncCallback\ | 是 | 异步回调。 | **示例**: @@ -281,22 +267,20 @@ reminderAgent.cancelAllReminders((err, data) =>{ ## reminderAgent.cancelAllReminders(deprecated) -```ts cancelAllReminders(): Promise\ -``` 取消当前应用所有的提醒,使用Promise方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.cancelAllReminders](js-apis-reminderAgentManager.md#reminderagentmanagercancelallreminders-1)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **返回值**: | 类型 | 说明 | | -------- | -------- | -| Promise\ | Promise类型异步回调。 | +| Promise\ | Promise类型异步回调。 | **示例**: @@ -308,23 +292,21 @@ reminderAgent.cancelAllReminders().then(() => { ## reminderAgent.addNotificationSlot(deprecated) -```ts addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): void -``` 添加一个NotificationSlot,使用回调的方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.addNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanageraddnotificationslot)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | 是 | notification\.slot实例,仅支持设置其type属性。 | -| callback | AsyncCallback\ | 是 | 异步回调。 | +| callback | AsyncCallback\ | 是 | 异步回调。 | **示例**: @@ -342,16 +324,14 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ## reminderAgent.addNotificationSlot(deprecated) -```ts addNotificationSlot(slot: NotificationSlot): Promise\ -``` 添加一个NotificationSlot,使用Promise方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.addNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanageraddnotificationslot-1)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: @@ -363,7 +343,7 @@ addNotificationSlot(slot: NotificationSlot): Promise\ | 类型 | 说明 | | -------- | -------- | -| Promise\ | Promise类型异步回调。 | +| Promise\ | Promise类型异步回调。 | **示例**: @@ -381,23 +361,21 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ## reminderAgent.removeNotificationSlot(deprecated) -```ts removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void -``` 删除目标NotificationSlot,使用callback方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.removeNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanagerremovenotificationslot)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | 是 | 目标notification\.slot的类型。 | -| callback | AsyncCallback\ | 是 | 异步回调。 | +| callback | AsyncCallback\ | 是 | 异步回调。 | **示例**: @@ -412,16 +390,14 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ## reminderAgent.removeNotificationSlot(deprecated) -```ts removeNotificationSlot(slotType: notification.SlotType): Promise -``` 删除目标NotificationSlot,使用Promise方式实现异步调用。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.removeNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanagerremovenotificationslot-1)替代。 -**系统能力**: `SystemCapability.Notification.ReminderAgent` +**系统能力**: SystemCapability.Notification.ReminderAgent **参数**: @@ -433,7 +409,7 @@ removeNotificationSlot(slotType: notification.SlotType): Promise | 类型 | 说明 | | -------- | -------- | -| Promise\ | Promise类型异步回调。 | +| Promise\ | Promise类型异步回调。 | **示例**: @@ -453,7 +429,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.ActionButtonType](js-apis-reminderAgentManager.md#ActionButtonType)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 值 | 说明 | | -------- | -------- | -------- | @@ -468,7 +444,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.ReminderType](js-apis-reminderAgentManager.md#ReminderType)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 值 | 说明 | | -------- | -------- | -------- | @@ -484,7 +460,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.ActionButton](js-apis-reminderAgentManager.md#ActionButton)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -499,7 +475,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.WantAgent](js-apis-reminderAgentManager.md#WantAgent)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -514,7 +490,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.MaxScreenWantAgent](js-apis-reminderAgentManager.md#MaxScreenWantAgent)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -529,7 +505,7 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.ReminderRequest](js-apis-reminderAgentManager.md#ReminderRequest)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**`SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -550,50 +526,46 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). ## ReminderRequestCalendar(deprecated) -ReminderRequestCalendar extends ReminderRequest 日历实例对象,用于设置提醒的时间。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.ReminderRequestCalendar](js-apis-reminderAgentManager.md#ReminderRequestCalendar)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | 是 | 指明提醒的目标时间。 | -| repeatMonths | Array\ | 否 | 指明重复提醒的月份。 | -| repeatDays | Array\ | 否 | 指明重复提醒的日期。 | +| repeatMonths | Array\ | 否 | 指明重复提醒的月份。 | +| repeatDays | Array\ | 否 | 指明重复提醒的日期。 | ## ReminderRequestAlarm(deprecated) -ReminderRequestAlarm extends ReminderRequest 闹钟实例对象,用于设置提醒的时间。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.ReminderRequestAlarm](js-apis-reminderAgentManager.md#ReminderRequestAlarm)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | hour | number | 是 | 指明提醒的目标时刻。 | | minute | number | 是 | 指明提醒的目标分钟。 | -| daysOfWeek | Array\ | 否 | 指明每周哪几天需要重复提醒。范围为周一到周末,对应数字为1到7。 | +| daysOfWeek | Array\ | 否 | 指明每周哪几天需要重复提醒。范围为周一到周末,对应数字为1到7。 | ## ReminderRequestTimer(deprecated) -ReminderRequestTimer extends ReminderRequest - 倒计时实例对象,用于设置提醒的时间。 > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.ReminderRequestTimer](js-apis-reminderAgentManager.md#ReminderRequestTimer)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -607,7 +579,7 @@ ReminderRequestTimer extends ReminderRequest > **说明:** > 从 API version 7开始支持,从API version 9开始废弃。建议使用[reminderAgentManager.LocalDateTime](js-apis-reminderAgentManager.md#LocalDateTime)替代。 -**系统能力**:`SystemCapability.Notification.ReminderAgent` +**系统能力**:SystemCapability.Notification.ReminderAgent | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md index 8a06421c1de1b3fe0df129fc464bafad636dd50e..72124f105bfbd151c0d8d2af68305b94fbecd2dd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -170,7 +170,7 @@ cancelReminder(reminderId: number): Promise\ | 类型 | 说明 | | -------- | -------- | -| PPromise\ | Promise类型异步回调。 | +| Promise\ | Promise类型异步回调。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-syscap.md b/zh-cn/application-dev/reference/apis/js-apis-syscap.md new file mode 100644 index 0000000000000000000000000000000000000000..18d5bd486c8d35ffd0eac4f31dc95bbb5e7aed32 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-syscap.md @@ -0,0 +1,42 @@ +# SysCap (系统能力) + +系统能力(SystemCapability,简称SysCap),指操作系统中每一个相对独立的特性。不同的设备对应不同的系统能力集,每个系统能力对应一个或多个API。开发者可根据系统能力来判断是否可以使用某接口。 + +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## canIUse + +canIUse(syscap: string): boolean + +查询系统是否具备某个系统能力。 + +**系统能力:** SystemCapability.ArkUI.ArkUI.Full + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| syscap | string | 是 | 待查询的系统能力名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 系统能力查询结果,true表示系统具备该能力,false表示系统不具备。 | + +**示例:** + + ```js +import geolocation from '@ohos.geolocation' + +const isLocationAvailable = canIUse('SystemCapability.Location.Location'); +if (isLocationAvailable) { + geolocation.getCurrentLocation((location) => { + console.log(location.latitude, location.longitue); + }); +} else { + console.log('Location not by this device.'); +} + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md b/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md old mode 100644 new mode 100755 index 42ea974f6325622c1b44fb1b9f4b5a469cc022f7..e2fe390eef26ca29d90b2a04229b64f43b16d6ae --- a/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @@ -158,7 +158,7 @@ getCurrentTime(isNano?: boolean): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ---- | ------------------------- | -| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
默认值为false。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** @@ -253,7 +253,7 @@ getRealActiveTime(isNano?: boolean): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ---- | ----------------------------------- | -| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
默认值为false。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** @@ -348,7 +348,7 @@ getRealTime(isNano?: boolean): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ---- | ------------------------------- | -| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
默认值为false。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-time.md b/zh-cn/application-dev/reference/apis/js-apis-system-time.md old mode 100644 new mode 100755 index 04383c4b5596704dffda9318f89a357ac69cd565..f2259063030ba2c82b0dc451c4e05fe74deebe23 --- a/zh-cn/application-dev/reference/apis/js-apis-system-time.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-time.md @@ -191,7 +191,7 @@ getCurrentTime(isNano?: boolean): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ---- | ------------------------- | -| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
默认值为false。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** @@ -310,7 +310,7 @@ getRealActiveTime(isNano?: boolean): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ---- | ----------------------------------- | -| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
默认值为false。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** @@ -429,7 +429,7 @@ getRealTime(isNano?: boolean): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ---- | ------------------------------- | -| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
默认值为false。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-systemSoundManager.md b/zh-cn/application-dev/reference/apis/js-apis-systemSoundManager.md new file mode 100644 index 0000000000000000000000000000000000000000..9f99cc005596cfea2ab9dfd3f7acedf2348f42c2 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-systemSoundManager.md @@ -0,0 +1,268 @@ +# @ohos.multimedia.systemSoundManager (系统声音管理) + +系统声音管理提供管理系统声音的一些基础能力,包括对系统铃声的资源设置与读取、获取系统铃声播放器等。 + +> **说明:** +> +> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 本模块接口为系统接口。 + +## 导入模块 + +```js +import systemSoundManager from '@ohos.multimedia.systemSoundManager'; +``` + +## RingtoneType + +枚举,铃声类型。 + +**系统接口:** 该接口为系统接口。 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +| 名称 | 值 | 说明 | +| ------------------------------- | ------ | -------------------------------------------- | +| RINGTONE_TYPE_DEFAULT | 0 | 默认铃声类型。 | +| RINGTONE_TYPE_MULTISIM | 1 | 多SIM卡铃声类型。 | + +## systemSoundManager.getSystemSoundManager + +getSystemSoundManager(): SystemSoundManager + +获取系统声音管理器。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**返回值:** + +| 类型 | 说明 | +| ----------------------------- | ------------ | +| [SystemSoundManager](#systemsoundmanager) | 系统声音管理类。 | + +**示例:** +```js +let systemSoundManagerInstance = systemSoundManager.getSystemSoundManager(); +``` + +## SystemSoundManager + +管理系统声音。在调用SystemSoundManager的接口前,需要先通过[getSystemSoundManager](#systemsoundmanagergetsystemsoundmanager)创建实例。 + +### setSystemRingtoneUri + +setSystemRingtoneUri(context: Context, uri: string, type: RingtoneType, callback: AsyncCallback<void>): void + +设置系统铃声uri,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | 是 | 当前应用的上下文。 | +| uri | string | 是 | 被设置的系统铃声的uri,资源支持可参考[media.AVPlayer](js-apis-media.md#avplayer9)。 | +| type | [RingtoneType](#ringtonetype) | 是 | 被设置的系统铃声的类型。 | +| callback | AsyncCallback<void> | 是 | 回调返回设置成功或失败。 | + +**示例:** + +```js +let context = this.context; +let uri = 'file://data/test.wav'; // 需更改为目标铃声文件的uri +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.setSystemRingtoneUri(context, uri, type, (err) => { + if (err) { + console.error(`Failed to set system ringtone uri. ${err}`); + return; + } + console.info(`Callback invoked to indicate a successful setting of the system ringtone uri.`); +}); +``` + +### setSystemRingtoneUri + +setSystemRingtoneUri(context: Context, uri: string, type: RingtoneType): Promise<void> + +设置系统铃声uri,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | 是 | 当前应用的上下文。 | +| uri | string | 是 | 被设置的系统铃声的uri,资源支持可参考[media.AVPlayer](js-apis-media.md#avplayer9)。 | +| type | [RingtoneType](#ringtonetype) | 是 | 被设置的系统铃声的类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<void> | Promise回调返回设置成功或失败。 | + +**示例:** + +```js +let context = this.context; +let uri = 'file://data/test.wav'; // 需更改为目标铃声文件的uri +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.setSystemRingtoneUri(context, uri, type).then(() => { + console.info(`Promise returned to indicate a successful setting of the system ringtone uri.`); +}).catch ((err) => { + console.error(`Failed to set the system ringtone uri ${err}`); +}); +``` + +### getSystemRingtoneUri + +getSystemRingtoneUri(context: Context, type: RingtoneType, callback: AsyncCallback<string>): void + +获取系统铃声uri,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | 是 | 当前应用的上下文。 | +| type | [RingtoneType](#ringtonetype) | 是 | 待获取的系统铃声的类型。 | +| callback | AsyncCallback<string> | 是 | 回调返回获取的系统铃声uri。 | + +**示例:** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.getSystemRingtoneUri(context, type, (err, value) => { + if (err) { + console.error(`Failed to get system ringtone uri. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the system ringtone uri is obtained ${value}.`); +}); +``` + +### getSystemRingtoneUri + +getSystemRingtoneUri(context: Context, type: RingtoneType): Promise<string> + +获取系统铃声uri,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| context | Context | 是 | 当前应用的上下文。 | +| type | [RingtoneType](#ringtonetype) | 是 | 被设置的系统铃声的类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ---------------------------------- | +| Promise<string> | Promise回调返回获取的系统铃声uri。 | + +**示例:** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; + +systemSoundManagerInstance.getSystemRingtoneUri(context, type).then((value) => { + console.info(`Promise returned to indicate that the value of the system ringtone uri is obtained ${value}.`); +}).catch ((err) => { + console.error(`Failed to get the system ringtone uri ${err}`); +}); +``` + +### getSystemRingtonePlayer + +getSystemRingtonePlayer(context: Context, type: RingtoneType, callback: AsyncCallback<RingtonePlayer>): void + +获取系统铃声播放器,使用callback方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | --------------------------- | +| context | Context | 是 | 当前应用的上下文。 | +| type | [RingtoneType](#ringtonetype) | 是 | 待获取播放器的系统铃声的类型。 | +| callback | AsyncCallback<[RingtonePlayer](js-apis-inner-multimedia-ringtonePlayer.md#ringtoneplayer)> | 是 | 回调返回获取的系统铃声播放器。 | + +**示例:** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; +let systemRingtonePlayer = null; + +systemSoundManagerInstance.getSystemRingtonePlayer(context, type, (err, value) => { + if (err) { + console.error(`Failed to get system ringtone player. ${err}`); + return; + } + console.info(`Callback invoked to indicate the value of the system ringtone player is obtained.`); + systemRingtonePlayer = value; +}); +``` + +### getSystemRingtonePlayer + +getSystemRingtonePlayer(context: Context, type: RingtoneType): Promise<RingtonePlayer> + +获取系统铃声播放器,使用Promise方式异步返回结果。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.SystemSound.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -----------------------------------------| ---- | --------------------------- | +| context | Context | 是 | 当前应用的上下文。 | +| type | [RingtoneType](#ringtonetype) | 是 | 待获取播放器的系统铃声的类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------- | +| Promise<[RingtonePlayer](js-apis-inner-multimedia-ringtonePlayer.md#ringtoneplayer)> | Promise回调返回获取的系统铃声播放器。 | + +**示例:** + +```js +let context = this.context; +let type = systemSoundManager.RingtoneType.RINGTONE_TYPE_DEFAULT; +let systemRingtonePlayer = null; + +systemSoundManagerInstance.getSystemRingtonePlayer(context, type).then((value) => { + console.info(`Promise returned to indicate that the value of the system ringtone player is obtained.`); + systemRingtonePlayer = value; +}).catch ((err) => { + console.error(`Failed to get the system ringtone player ${err}`); +}); +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md index 5c1e76e9c42c58ac845df4cdc16264eb238aa6c1..c1806da517eef94093f34922214f794dd3a3227f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md +++ b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md @@ -2,9 +2,9 @@ 任务池(taskpool)作用是为应用程序提供一个多线程的运行环境,降低整体资源的消耗、提高系统的整体性能,且您无需关心线程实例的生命周期。您可以使用任务池API创建后台任务(Task),并对所创建的任务进行如任务执行、任务取消的操作。理论上您可以使用任务池API创建数量不受限制的任务,但是出于内存因素不建议您这样做。此外,不建议您在任务中执行阻塞操作,特别是无限期阻塞操作,长时间的阻塞操作占据工作线程,可能会阻塞其他任务调度,影响您的应用性能。 -您所创建的同一优先级任务的执行顺序可以由您决定,任务真实执行的顺序与您调用任务池API提供的任务执行接口顺序一致。任务默认优先级是MEDIUM。(任务优先级机制暂未支持) +您所创建的同一优先级任务的执行顺序可以由您决定,任务真实执行的顺序与您调用任务池API提供的任务执行接口顺序一致。任务默认优先级是MEDIUM。 -当同一时间待执行的任务数量大于任务池工作线程数量,任务池会根据负载均衡机制进行扩容,增加工作线程数量,减少整体等待时长。同样,当执行的任务数量减少,工作线程数量大于执行任务数量,部分工作线程处于空闲状态,任务池会根据负载均衡机制进行缩容,减少工作线程数量。(负载均衡机制暂未支持) +当同一时间待执行的任务数量大于任务池工作线程数量,任务池会根据负载均衡机制进行扩容,增加工作线程数量,减少整体等待时长。同样,当执行的任务数量减少,工作线程数量大于执行任务数量,部分工作线程处于空闲状态,任务池会根据负载均衡机制进行缩容,减少工作线程数量。 任务池API以数字形式返回错误码。有关各个错误码的更多信息,请参阅文档[语言基础类库错误码](../errorcodes/errorcode-utils.md)。 @@ -32,13 +32,13 @@ import taskpool from '@ohos.taskpool'; **示例:** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolPriority() { + let task = new taskpool.Task(printArgs, 100); let highCount = 0; let mediumCount = 0; @@ -65,7 +65,7 @@ async function taskpoolTest() { }) } } -taskpoolTest(); +taskpoolPriority(); ``` ## Task @@ -99,12 +99,12 @@ Task的构造函数。 ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -let task = new taskpool.Task(func, "this is my first Task"); +let task = new taskpool.Task(printArgs, "this is my first Task"); ``` ### 属性 @@ -151,17 +151,17 @@ execute(func: Function, ...args: unknown[]): Promise\ ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let value = await taskpool.execute(func, 100); +async function taskpoolExecute() { + let value = await taskpool.execute(printArgs, 100); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.execute @@ -199,18 +199,18 @@ execute(task: Task, priority?: Priority): Promise\ ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolExecute() { + let task = new taskpool.Task(printArgs, 100); let value = await taskpool.execute(task); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.cancel @@ -239,14 +239,14 @@ cancel(task: Task): void **任务取消成功示例:** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); taskpool.execute(task); try { taskpool.cancel(task); @@ -255,20 +255,20 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` **已执行的任务取消失败示例:** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); let value = taskpool.execute(task); let start = new Date().getTime(); while (new Date().getTime() - start < 1000) { // 延时1s,确保任务已执行 @@ -282,25 +282,25 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` **正在执行的任务取消失败示例:** ```ts -function func(args) { - "use concurrent"; - console.log("func: " + args); +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task1 = new taskpool.Task(func, 100); - let task2 = new taskpool.Task(func, 200); - let task3 = new taskpool.Task(func, 300); - let task4 = new taskpool.Task(func, 400); - let task5 = new taskpool.Task(func, 500); - let task6 = new taskpool.Task(func, 600); +async function taskpoolCancel() { + let task1 = new taskpool.Task(printArgs, 100); + let task2 = new taskpool.Task(printArgs, 200); + let task3 = new taskpool.Task(printArgs, 300); + let task4 = new taskpool.Task(printArgs, 400); + let task5 = new taskpool.Task(printArgs, 500); + let task6 = new taskpool.Task(printArgs, 600); let res1 = taskpool.execute(task1); let res2 = taskpool.execute(task2); @@ -315,7 +315,7 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); ``` ## 其他说明 @@ -327,7 +327,7 @@ taskpoolTest(); - 仅支持在Stage模型且module的compileMode为esmodule的project中使用taskpool api。确认module的compileMode方法:查看当前module的build-profile.json5,在buildOption中补充"compileMode": "esmodule"。 - taskpool任务只支持引用入参传递或者import的变量,不支持使用闭包变量,使用装饰器@Concurrent进行拦截。 - taskpool任务只支持普通函数或者async函数,不支持类成员函数或者匿名函数,使用装饰器@Concurrent进行拦截。 -- 装饰器@Concurrent仅支持在ets文件使用,在ts文件中创建taskpool任务需使用"use concurrent"。 +- 装饰器@Concurrent仅支持在ets文件使用。 ### 简单使用 @@ -336,23 +336,23 @@ taskpoolTest(); ```ts // 支持普通函数、引用入参传递 @Concurrent -function func(args) { +function printArgs(args) { console.log("func: " + args); return args; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(func, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); // taskpool.execute(function) - let val2 = await taskpool.execute(func, "execute task by func"); + let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **示例二** @@ -367,24 +367,24 @@ export var c = 2000; import { c } from "./b"; @Concurrent -function test(a) { +function printArgs(a) { console.log(a); console.log(c); return a; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(test, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); // taskpool.execute(function) - let val2 = await taskpool.execute(test, "execute task by func"); + let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **示例三** @@ -392,57 +392,52 @@ taskpoolTest(); ```ts // 支持async函数 @Concurrent -async function task() { +async function delayExcute() { let ret = await Promise.all([ new Promise(resolve => setTimeout(resolve, 1000, "resolved")) ]); return ret; } -async function taskpoolTest() { - taskpool.execute(task).then((result) => { +async function taskpoolExecute() { + taskpool.execute(delayExcute).then((result) => { console.log("TaskPoolTest task result: " + result); }); } -taskpoolTest(); +taskpoolExecute(); ``` **示例四** ```ts -// 在ts文件中创建taskpool任务需使用"use concurrent" -// c.ts -function test1(n) { - "use concurrent" - return n; +// c.ets +@Concurrent +function strSort(inPutArr) { + let newArr = inPutArr.sort(); + return newArr; } -export async function taskpoolTest1() { - console.log("taskpoolTest1 start"); - var task = new taskpool.Task(test1, 100); +export async function func1() { + console.log("taskpoolTest start"); + let strArray = ['c test string', 'b test string', 'a test string']; + var task = new taskpool.Task(strSort, strArray); var result = await taskpool.execute(task); - console.log("taskpoolTest1 result:" + result); + console.log("func1 result:" + result); } -async function test2() { - "use concurrent" - var ret = await Promise.all([ - new Promise(resolve => setTimeout(resolve, 1000, "resolved")) - ]); - return ret; -} -export async function taskpoolTest2() { +export async function func2() { console.log("taskpoolTest2 start"); - taskpool.execute(test2).then((result) => { - console.log("TaskPoolTest2 result: " + result); + let strArray = ['c test string', 'b test string', 'a test string']; + taskpool.execute(strSort, strArray).then((result) => { + console.log("func2 result: " + result); }); } ``` ```ts -// a.ets(与c.ts在同一目录中) +// a.ets(与c.ets在同一目录中) import { taskpoolTest1, taskpoolTest2 } from "./c"; -taskpoolTest1(); -taskpoolTest2(); +func1(); +func2(); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-timer.md b/zh-cn/application-dev/reference/apis/js-apis-timer.md index 669a26623435c1d03bf87456c31506d0df8699e4..bdf2ef921ee4b63d3218d82ed1a47efaa2ac2065 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-timer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-timer.md @@ -20,7 +20,7 @@ setTimeout(handler: Function | string, delay?: number, ...arguments: any[]): num | -------- | -------- | -------- | -------- | | handler | Function \| string | 是 | 定时器到期后执行函数。类型为string则打印Error信息,不进行其他处理。 | | delay | number | 否 | 延迟的毫秒数,函数的调用会在该延迟之后发生。如果省略该参数,delay取默认值0,意味着“马上”执行,或尽快执行。 | -| ...arguments | Array<any> | 否 | 附加参数,一旦定时器到期,它们会作为参数传递给handler。 | +| ...arguments | any[] | 否 | 附加参数,一旦定时器到期,它们会作为参数传递给handler。 | **返回值:** @@ -41,7 +41,7 @@ setTimeout(handler: Function | string, delay?: number, ...arguments: any[]): num clearTimeout(timeoutID?: number): void -取消了先前通过调用setTimeout()建立的定时器。 +可取消通过调用setTimeout()建立的定时器。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full @@ -75,7 +75,7 @@ setInterval(handler: Function | string, delay: number, ...arguments: any[]): num | -------- | -------- | -------- | -------- | | handler | Function \| string | 是 | 要重复调用的函数。类型为string则打印Error信息,不进行其他处理。| | delay | number | 是 | 延迟的毫秒数,函数的调用会在该延迟之后发生。 | -| ...arguments | Array<any> | 否 | 附加参数,一旦定时器到期,他们会作为参数传递给handler。 | +| ...arguments | any[] | 否 | 附加参数,一旦定时器到期,他们会作为参数传递给handler。 | **返回值:** @@ -96,7 +96,7 @@ setInterval(handler: Function | string, delay: number, ...arguments: any[]): num clearInterval(intervalID?: number): void -可取消先前通过setInterval()设置的重复定时任务。 +可取消通过setInterval()设置的重复定时任务。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full diff --git a/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md index d4630b1829c4d6ca578ea92d806b9a92e118c534..ae8806ed12ec5773db63a96fc7926fb2ec6d8d85 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @@ -19,7 +19,7 @@ getUserFileMgr(context: Context): UserFileManager 获取用户数据管理模块的实例,用于访问和修改用户等用户公共媒体数据信息(如音频、视频、图片、文档等)。 -**模型约束:** 此接口仅可在Stage模型下使用。 +**模型约束**: 此接口仅可在Stage模型下使用。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -27,13 +27,13 @@ getUserFileMgr(context: Context): UserFileManager | 参数名 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | -------------------------- | -| context | [Context](js-apis-inner-app-context.md) | 是 | 传入Ability实例的Context | +| context | [Context](js-apis-inner-app-context.md) | 是 | 传入Ability实例的Context。 | **返回值:** | 类型 | 说明 | | ----------------------------- | :---- | -| [UserFileManager](#userfilemanager) | 媒体库实例 | +| [UserFileManager](#userfilemanager) | 媒体库实例。 | **示例:** @@ -59,8 +59,8 @@ getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项 | -| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回图片和视频检索结果集 | +| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback返回图片和视频检索结果集。 | **示例:** @@ -80,7 +80,7 @@ async function example() { console.info('fetchResult success'); let fileAsset = await fetchResult.getFirstObject(); if (fileAsset != undefined) { - console.info("fileAsset.displayName : " + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); } } else { console.error('fetchResult fail' + err); @@ -103,13 +103,13 @@ getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------- | ---- | ---------------- | -| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项 | +| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项。 | **返回值:** | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 图片和视频数据结果集 | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise对象,返回图片和视频数据结果集。 | **示例:** @@ -129,7 +129,7 @@ async function example() { console.info('fetchResult success'); let fileAsset = await fetchResult.getFirstObject(); if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); + console.info('fileAsset.displayName :' + fileAsset.displayName); } } } catch (err) { @@ -137,12 +137,11 @@ async function example() { } } ``` - ### createPhotoAsset createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback<FileAsset>): void; -创建图片或视频资源,使用callback方式返回结果。 +指定待创建的图片或者视频的文件名和所在相册的uri,创建图片或视频资源,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -152,9 +151,9 @@ createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| displayName | string | 是 | 创建的图片或者视频文件名 | -| albumUri | string | 是 | 创建的图片或者视频所在相册的uri | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback 返回创建的图片和视频结果 | +| displayName | string | 是 | 创建的图片或者视频文件名。 | +| albumUri | string | 是 | 创建的图片或者视频所在相册的uri。 | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback返回创建的图片和视频结果。 | **示例:** @@ -169,7 +168,7 @@ async function example() { }; let albums = await mgr.getPhotoAlbums(fetchOptions); let album = await albums.getFirstObject(); - let testFileName = "testFile" + Date.now() + ".jpg"; + let testFileName = 'testFile' + Date.now() + '.jpg'; mgr.createPhotoAsset(testFileName, album.albumUri, (err, fileAsset) => { if (fileAsset != undefined) { console.info('createPhotoAsset file displayName' + fileAsset.displayName); @@ -185,7 +184,7 @@ async function example() { createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): void; -创建图片或视频资源,使用callback方式返回结果。 +指定待创建的图片或者视频的文件名,创建图片或视频资源,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -195,15 +194,15 @@ createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| displayName | string | 是 | 创建的图片或者视频文件名 | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback 返回创建的图片和视频结果 | +| displayName | string | 是 | 创建的图片或者视频文件名。 | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback返回创建的图片和视频结果。 | **示例:** ```ts async function example() { console.info('createPhotoAssetDemo'); - let testFileName = "testFile" + Date.now() + ".jpg"; + let testFileName = 'testFile' + Date.now() + '.jpg'; mgr.createPhotoAsset(testFileName, (err, fileAsset) => { if (fileAsset != undefined) { console.info('createPhotoAsset file displayName' + fileAsset.displayName); @@ -219,7 +218,7 @@ async function example() { createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset>; -创建图片或视频资源,使用Promise方式返回结果。 +指定待创建的图片或者视频的文件名和所在相册的uri,创建图片或视频资源,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -229,14 +228,14 @@ createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| displayName | string | 是 | 创建的图片或者视频文件名 | -| albumUri | string | 否 | 创建的图片或者视频所在相册的uri | +| displayName | string | 是 | 创建的图片或者视频文件名。 | +| albumUri | string | 否 | 创建的图片或者视频所在相册的uri。 | **返回值:** | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FileAsset](#fileasset)> | 返回创建的图片和视频结果 | +| Promise<[FileAsset](#fileasset)> | Promise对象,返回创建的图片和视频结果。 | **示例:** @@ -244,7 +243,7 @@ createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset&g async function example() { console.info('createPhotoAssetDemo'); try { - let testFileName = "testFile" + Date.now() + ".jpg"; + let testFileName = 'testFile' + Date.now() + '.jpg'; let fileAsset = await mgr.createPhotoAsset(testFileName); console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); @@ -254,10 +253,163 @@ async function example() { } ``` +### createPhotoAsset + +createPhotoAsset(displayName: string, createOption: PhotoCreateOptions, callback: AsyncCallback<FileAsset>): void; + +指定待创建的图片或者视频的文件名和创建选项,创建图片或视频资源,使用callback方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的图片或者视频文件名。 | +| createOption | [PhotoCreateOptions](#photocreateoptions10) | 是 | 图片或视频的创建选项。 | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback返回创建的图片和视频结果。 | + +**示例:** + +```ts +async function example() { + console.info('createPhotoAssetDemo'); + let testFileName = 'testFile' + Date.now() + '.jpg'; + let createOption = { + subType: userFileManager.PhotoSubType.DEFAULT + } + mgr.createPhotoAsset(testFileName, createOption, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.error('createPhotoAsset failed, message = ', err); + } + }); +} +``` + +### createPhotoAsset + +createPhotoAsset(displayName: string, createOption: PhotoCreateOptions): Promise<FileAsset>; + +指定待创建的图片或者视频的文件名和创建选项,创建图片或视频资源,使用Promise方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的图片或者视频文件名。 | +| createOption | [PhotoCreateOptions](#photocreateoptions10) | 是 | 图片或视频的创建选项。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FileAsset](#fileasset)> | Promise对象,返回创建的图片和视频结果。 | + +**示例:** + +```ts +async function example() { + console.info('createPhotoAssetDemo'); + try { + let testFileName = 'testFile' + Date.now() + '.jpg'; + let createOption = { + subType: userFileManager.PhotoSubType.DEFAULT + } + let fileAsset = await mgr.createPhotoAsset(testFileName, createOption); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.error('createPhotoAsset failed, message = ', err); + } +} +``` + +### createAudioAsset10+ + +createAudioAsset(displayName: string, callback: AsyncCallback<FileAsset>): void; + +创建音频文件资源,使用callback方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的音频文件名。 | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback返回创建的音频资源结果。 | + +**示例:** + +```ts +async function example() { + console.info('createAudioAssetDemo'); + let testFileName = 'testFile' + Date.now() + '.mp3'; + mgr.createAudioAsset(testFileName, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createAudioAsset file displayName' + fileAsset.displayName); + console.info('createAudioAsset successfully'); + } else { + console.error('createAudioAsset failed, message = ', err); + } + }); +} +``` + +### createAudioAsset10+ + +createAudioAsset(displayName: string): Promise<FileAsset>; + +创建音频文件资源,使用Promise方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的音频文件名。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FileAsset](#fileasset)> | Promise对象,返回创建的音频资源结果。 | + +**示例:** + +```ts +async function example() { + console.info('createAudioAssetDemo'); + try { + let testFileName = 'testFile' + Date.now() + '.mp3'; + let fileAsset = await mgr.createAudioAsset(testFileName); + console.info('createAudioAsset file displayName' + fileAsset.displayName); + console.info('createAudioAsset successfully'); + } catch (err) { + console.error('createAudioAsset failed, message = ', err); + } +} +``` + ### getPhotoAlbums getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; + 获取相册,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -268,8 +420,8 @@ getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResul | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项 | -| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | 是 | callback 返回相册检索结果 | +| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | 是 | callback返回相册检索结果。 | **示例:** @@ -314,13 +466,13 @@ getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项 | +| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项。 | **返回值:** | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FetchResult](#fetchresult)<[Album](#album)>> | Promise 返回相册检索结果 | +| Promise<[FetchResult](#fetchresult)<[Album](#album)>> | Promise对象,返回相册检索结果。 | **示例:** @@ -344,259 +496,574 @@ async function example() { } ``` -### getPrivateAlbum +### createAlbum10+ -getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; +createAlbum(name: string, callback: AsyncCallback<Album>): void; -获取系统相册,使用 callback 方式返回系统相册的数组。 +创建相册,使用callback方式返回结果。 + +待创建的相册名参数规格为: +- 相册名字符串长度为1~255。 +- 不允许出现的非法英文字符,包括:
. .. \ / : * ? " ' ` < > | { } [ ] +- 英文字符大小写不敏感。 +- 相册名不允许重名。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型 | -| callback | AsyncCallback<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | 是 | callback 返回相册检索结果 | +| name | string | 是 | 待创建相册的相册名。 | +| callback | AsyncCallback<[Album](#album)> | 是 | callback返回创建的相册实例。 | **示例:** ```ts async function example() { - console.info('getPrivateAlbumDemo'); - mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => { - if (fetchResult != undefined) { - let trashAlbum = await fetchResult.getFirstObject(); - console.info('first album.albumName = ' + trashAlbum.albumName); - } else { - console.error('getPrivateAlbum failed. message = ', err); + console.info('createAlbumDemo'); + let albumName = 'newAlbumName' + new Date().getTime(); + mgr.createAlbum(albumName, (err, album) => { + if (err) { + console.error('createAlbumCallback failed with err: ' + err); + return; } + console.info('createAlbumCallback successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); }); } ``` -### getPrivateAlbum +### createAlbum10+ -getPrivateAlbum(type: PrivateAlbumType): Promise<FetchResult<PrivateAlbum>>; +createAlbum(name: string): Promise<Album>; +创建相册,使用Promise方式返回结果。 -获取系统相册,使用Promise方式返回结果。 +待创建的相册名参数规格为: +- 相册名字符串长度为1~255。 +- 不允许出现的非法英文字符,包括:
. .. \ / : * ? " ' ` < > | { } [ ] +- 英文字符大小写不敏感。 +- 相册名不允许重名。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型 | +| name | string | 是 | 待创建相册的相册名。 | **返回值:** | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Promise 返回相册检索结果 | +| Promise<[Album](#album)> | Promise对象,返回创建的相册实例。 | **示例:** ```ts async function example() { - console.info('getPrivateAlbumDemo'); - try { - let fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); - let trashAlbum = await fetchResult.getFirstObject(); - console.info('first album.albumName = ' + trashAlbum.albumName); - } catch (err) { - console.error('getPrivateAlbum failed. message = ', err); - } + console.info('createAlbumDemo'); + let albumName = 'newAlbumName' + new Date().getTime(); + mgr.createAlbum(albumName).then((album) => { + console.info('createAlbumPromise successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); + }).catch((err) => { + console.error('createAlbumPromise failed with err: ' + err); + }); } ``` -### getAudioAssets +### deleteAlbums10+ -getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; +deleteAlbums(albums: Array<Album>, callback: AsyncCallback<void>): void; -获取音频文件,使用callback方式返回结果。 +删除相册,使用callback方式返回结果。 + +删除相册前需先确保相册存在,只能删除用户相册。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_AUDIO +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | -| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回音频检索结果 | +| albums | Array<[Album](#album)> | 是 | 待删除相册的数组。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | **示例:** ```ts -import dataSharePredicates from '@ohos.data.dataSharePredicates'; - async function example() { - console.info('getAudioAssets'); + // 示例代码为删除名称包含newAlbumName的第一个相册。 + console.info('deleteAlbumsDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.like('album_name', '%newAlbumName%'); let fetchOptions = { fetchColumns: [], predicates: predicates }; - - mgr.getAudioAssets(fetchOptions, async (err, fetchResult) => { - if (fetchResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - } - } else { - console.error('fetchFileResult fail' + err); + let fetchResult = await mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); + mgr.deleteAlbums([album], (err) => { + if (err) { + console.error('deletePhotoAlbumsCallback failed with err: ' + err); + return; } + console.info('deletePhotoAlbumsCallback successfully'); }); + fetchResult.close(); } ``` -### getAudioAssets +### deleteAlbums10+ -getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; +deleteAlbums(albums: Array<Album>): Promise<void>; -获取音频文件,使用callback方式返回结果。 +删除相册,使用Promise方式返回结果。 + +删除相册前需先确保相册存在,只能删除用户相册。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_AUDIO +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| albums | Array<[Album](#album)> | 是 | 待删除相册的数组。 | **返回值:** | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise 返回音频检索结果 | +| Promise<void> | Promise对象,返回void。 | **示例:** ```ts -import dataSharePredicates from '@ohos.data.dataSharePredicates'; - async function example() { - console.info('getAudioAssets'); + // 示例代码为删除名称包含newAlbumName的第一个相册。 + console.info('deleteAlbumsDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.like('album_name', '%newAlbumName%'); let fetchOptions = { fetchColumns: [], predicates: predicates }; - try { - var fetchResult = await mgr.getAudioAssets(fetchOptions); - } catch (err) { - console.error('getAudioAssets failed, message = ', err); - } - - if (fetchResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - } - } + let fetchResult = await mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC, fetchOptions); + let album = await fetchResult.getFirstObject(); + mgr.deleteAlbums([album]).then(() => { + console.info('deletePhotoAlbumsPromise successfully'); + }).catch((err) => { + console.error('deletePhotoAlbumsPromise failed with err: ' + err); + }); + fetchResult.close(); } ``` -### delete +### getAlbums10+ -delete(uri: string, callback: AsyncCallback<void>): void; +getAlbums(type: AlbumType, subType: AlbumSubType, options: FetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; -删除媒体文件,删除的文件进入到回收站。 +根据检索选项和相册类型获取相册,使用callback方式返回结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO +获取相册前需先保证相册存在。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**需要权限**:ohos.permission.READ_IMAGEVIDEO -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ---------- | -| uri | string | 是 | 媒体文件uri | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [AlbumType](#albumtype10) | 是 | 相册类型。 | +| subType | [AlbumSubType](#albumsubtype10) | 是 | 相册子类型。 | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | 是 | callback返回获取相册的结果集。 | -**示例**: +**示例:** ```ts -import dataSharePredicates from '@ohos.data.dataSharePredicates'; - async function example() { - console.info('deleteAssetDemo'); + // 示例代码中为获取相册名中包含newAlbumName的第一个相册。 + console.info('getAlbumsDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.like('album_name', '%newAlbumName%'); let fetchOptions = { fetchColumns: [], predicates: predicates }; - try { - const fetchResult = await mgr.getPhotoAssets(fetchOptions); - var asset = await fetchResult.getFirstObject(); - } catch (err) { - console.info('fetch failed, message =', err); - } + mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC, fetchOptions, async (err, fetchResult) => { + if (err) { + console.error('getAlbumsCallback failed with err: ' + err); + return; + } + if (fetchResult == undefined) { + console.error('getAlbumsCallback fetchResult is undefined'); + return; + } + let album = await fetchResult.getFirstObject(); + console.info('getAlbumsCallback successfully, albumName: ' + album.albumName); + fetchResult.close(); + }); +} +``` - if (asset == undefined) { - console.error('asset not exist'); - return; - } - mgr.delete(asset.uri, (err) => { - if (err == undefined) { - console.info("delete successfully"); - } else { - console.error("delete failed with error: " + err); +### getAlbums10+ + +getAlbums(type: AlbumType, subType: AlbumSubType, callback: AsyncCallback<FetchResult<Album>>): void; + +根据相册类型获取相册,使用callback方式返回结果。 + +获取相册前需先保证相册存在。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.READ_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [AlbumType](#albumtype10) | 是 | 相册类型。 | +| subType | [AlbumSubType](#albumsubtype10) | 是 | 相册子类型。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | 是 | callback返回获取相册的结果集。 | + +**示例:** + +```ts +async function example() { + // 示例代码中为获取统相册VIDEO,默认已预置。 + console.info('getAlbumsDemo'); + mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.VIDEO, async (err, fetchResult) => { + if (err) { + console.error('getAlbumsCallback failed with err: ' + err); + return; } + if (fetchResult == undefined) { + console.error('getAlbumsCallback fetchResult is undefined'); + return; + } + let album = await fetchResult.getFirstObject(); + console.info('getAlbumsCallback successfully, albumUri: ' + album.albumUri); + fetchResult.close(); }); } ``` -### delete +### getAlbums10+ -delete(uri: string): Promise<void>; +getAlbums(type: AlbumType, subType: AlbumSubType, options?: FetchOptions): Promise<FetchResult<Album>>; -删除媒体文件,删除的文件进入到回收站。 +根据检索选项和相册类型获取相册,使用Promise方式返回结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO +获取相册前需先保证相册存在。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**需要权限**:ohos.permission.READ_IMAGEVIDEO -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ---------- | -| uri | string | 是 | 媒体文件uri | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [AlbumType](#albumtype10) | 是 | 相册类型。 | +| subType | [AlbumSubType](#albumsubtype10) | 是 | 相册子类型。 | +| options | [FetchOptions](#fetchoptions) | 否 | 检索选项,不填时默认根据相册类型检索。 | **返回值:** -| 类型 | 说明 | -| --------------------------------------- | ----------------- | -| Promise<void>| 回调返回空 | +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[Album](#album)>> | Promise对象,返回获取相册的结果集。 | -**示例**: +**示例:** ```ts -import dataSharePredicates from '@ohos.data.dataSharePredicates'; - async function example() { - console.info('deleteDemo'); + // 示例代码中为获取相册名中包含newAlbumName的第一个相册。 + console.info('getAlbumsDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.like('album_name', '%newAlbumName%'); let fetchOptions = { fetchColumns: [], predicates: predicates }; - try { - const fetchResult = await mgr.getPhotoAssets(fetchOptions); - var asset = await fetchResult.getFirstObject(); - } catch (err) { + mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC, fetchOptions).then( async (fetchResult) => { + if (fetchResult == undefined) { + console.error('getAlbumsPromise fetchResult is undefined'); + return; + } + let album = await fetchResult.getFirstObject(); + console.info('getAlbumsPromise successfully, albumName: ' + album.albumName); + fetchResult.close(); + }).catch((err) => { + console.error('getAlbumsPromise failed with err: ' + err); + }); +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; + +获取系统相册,使用 callback 方式返回系统相册的数组。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.READ_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | 是 | callback返回相册检索结果。 | + +**示例:** + +```ts +async function example() { + console.info('getPrivateAlbumDemo'); + mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => { + if (fetchResult != undefined) { + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } else { + console.error('getPrivateAlbum failed. message = ', err); + } + }); +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: PrivateAlbumType): Promise<FetchResult<PrivateAlbum>>; + +获取系统相册,使用Promise方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.READ_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Promise对象,返回相册检索结果。 | + +**示例:** + +```ts +async function example() { + console.info('getPrivateAlbumDemo'); + try { + let fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } catch (err) { + console.error('getPrivateAlbum failed. message = ', err); + } +} +``` + +### getAudioAssets + +getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +获取音频文件,使用callback方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.READ_AUDIO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback返回音频检索结果。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getAudioAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info('fileAsset.displayName :' + fileAsset.displayName); + } + } else { + console.error('fetchFileResult fail' + err); + } + }); +} +``` + +### getAudioAssets + +getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + + +获取音频文件,使用callback方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.READ_AUDIO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise对象,返回音频检索结果。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getAudioAssets(fetchOptions); + } catch (err) { + console.error('getAudioAssets failed, message = ', err); + } + + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info('fileAsset.displayName :' + fileAsset.displayName); + } + } +} +``` + +### delete + +delete(uri: string, callback: AsyncCallback<void>): void; + +删除媒体文件,删除的文件进入到回收站。 + +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 媒体文件uri。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('deleteAssetDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err); + } + + if (asset == undefined) { + console.error('asset not exist'); + return; + } + mgr.delete(asset.uri, (err) => { + if (err == undefined) { + console.info('delete successfully'); + } else { + console.error('delete failed with error: ' + err); + } + }); +} +``` + +### delete + +delete(uri: string): Promise<void>; + +删除媒体文件,删除的文件进入到回收站。 + +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 媒体文件uri。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<void>| Promise对象,返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('deleteDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { console.info('fetch failed, message =', err); } @@ -606,9 +1073,9 @@ async function example() { } try { await mgr.delete(asset.uri); - console.info("delete successfully"); + console.info('delete successfully'); } catch (err) { - console.error("delete failed with error: " + err); + console.error('delete failed with error: ' + err); } } ``` @@ -626,7 +1093,7 @@ on(type: ChangeEvent, callback: Callback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ------------------------------------------------------------ | | type | [ChangeEvent](#changeevent) | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | Callback<void> | 是 | 回调返回空 | +| callback | Callback<void> | 是 | callback返回void | **示例:** @@ -639,7 +1106,7 @@ async function example() { // image file had changed, do something }); try { - let testFileName = "testFile" + Date.now() + ".jpg"; + let testFileName = 'testFile' + Date.now() + '.jpg'; let fileAsset = await mgr.createPhotoAsset(testFileName); console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); @@ -648,9 +1115,9 @@ async function example() { } //sleep 1s if (count > 0) { - console.info("onDemo success"); + console.info('onDemo success'); } else { - console.error("onDemo fail"); + console.error('onDemo fail'); } mgr.off('imageChange', () => { // stop listening success @@ -670,8 +1137,8 @@ off(type: ChangeEvent, callback?: Callback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | [ChangeEvent](#changeevent) | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | Callback<void> | 否 | 回调返回空 | +| type | [ChangeEvent](#changeevent) | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'remoteFileChange': 注册设备上文件变更。 | +| callback | Callback<void> | 否 | callback返回void。 | **示例:** @@ -689,7 +1156,7 @@ async function example() { }); try { - let testFileName = "testFile" + Date.now() + ".jpg"; + let testFileName = 'testFile' + Date.now() + '.jpg'; let fileAsset = await mgr.createPhotoAsset(testFileName); console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); @@ -698,9 +1165,9 @@ async function example() { } //sleep 1s if (count == 0) { - console.info("offDemo success"); + console.info('offDemo success'); } else { - console.error("offDemo fail"); + console.error('offDemo fail'); } } ``` @@ -717,7 +1184,7 @@ getActivePeers(callback: AsyncCallback<Array<PeerInfo>>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表 | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表。 | **示例:** @@ -749,7 +1216,7 @@ getActivePeers(): Promise<Array<PeerInfo>>; | 类型 | 说明 | | --------------------------- | ----------------------------- | -| Promise<Array<[PeerInfo](#peerinfo)>> | Promise实例,返回在线设备列表 | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise对象,返回在线设备列表。 | **示例:** @@ -784,7 +1251,7 @@ getAllPeers(callback: AsyncCallback<Array<PeerInfo>>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表 | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表。 | **示例:** @@ -816,7 +1283,7 @@ getAllPeers(): Promise<Array<PeerInfo>>; | 类型 | 说明 | | --------------------------- | ----------------------------- | -| Promise<Array<[PeerInfo](#peerinfo)>> | Promise实例,返回所有设备列表 | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise对象,返回所有设备列表。 | **示例:** @@ -852,7 +1319,7 @@ release(callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | -------------------- | -| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败 | +| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败。 | **示例:** @@ -882,7 +1349,7 @@ release(): Promise<void> | 类型 | 说明 | | ------------------- | --------------------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果 | +| Promise<void> | Promise对象,返回void。 | **示例:** @@ -904,14 +1371,13 @@ async function example() { ### 属性 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | -| uri | string | 是 | 否 | 文件资源uri(如:dataability:///media/image/2) | +| uri | string | 是 | 否 | 文件资源uri(如:file://media/image/2)。 | | fileType | [FileType](#filetype) | 是 | 否 | 媒体文件类型 | -| displayName | string | 是 | 是 | 显示文件名,包含后缀名 | - +| displayName | string | 是 | 是 | 显示文件名,包含后缀名。 | ### get @@ -925,7 +1391,7 @@ get(member: string): MemberType; | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----- | -| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI | +| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI。 | **示例:** @@ -937,7 +1403,7 @@ async function example() { try { let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { - fetchColumns: [], + fetchColumns: ['title'], predicates: predicates }; let fetchResult = await mgr.getPhotoAssets(fetchOption); @@ -963,8 +1429,8 @@ set(member: string, value: string): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----- | -| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI | -| value | string | 是 | 设置成员参数名称,只能修改ImageVideoKey.TITLE的值 | +| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI。 | +| value | string | 是 | 设置成员参数名称,只能修改ImageVideoKey.DISPLAY_NAME的值。 | **示例:** @@ -981,8 +1447,8 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - let title = userFileManager.ImageVideoKey.TITLE; - fileAsset.set(title.toString(), "newTitle"); + let displayName = userFileManager.ImageVideoKey.DISPLAY_NAME; + fileAsset.set(displayName, 'newDisplayName1'); } catch (err) { console.error('release failed. message = ', err); } @@ -1003,7 +1469,7 @@ commitModify(callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----- | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | **示例:** @@ -1019,14 +1485,14 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - let title = userFileManager.ImageVideoKey.TITLE; - let fileAssetTitle = fileAsset.get(title.toString()); - console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); - fileAsset.set(title.toString(), "newTitle"); + let displayName = userFileManager.ImageVideoKey.DISPLAY_NAME; + let fileAssetDisplayName = fileAsset.get(displayName); + console.info('fileAsset get fileAssetDisplayName = ', fileAssetDisplayName); + fileAsset.set(displayName, 'newDisplayName2'); fileAsset.commitModify((err) => { if (err == undefined) { - let newFileAssetTitle = fileAsset.get(title.toString()); - console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + let newFileAssetDisplayName = fileAsset.get(displayName); + console.info('fileAsset get newFileAssetDisplayName = ', newFileAssetDisplayName); } else { console.error('commitModify failed, message =', err); } @@ -1048,7 +1514,7 @@ commitModify(): Promise<void> | 类型 | 说明 | | ------------------- | ---------- | -| Promise<void> | Promise返回空 | +| Promise<void> | Promise对象,返回void。 | **示例:** @@ -1064,14 +1530,14 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - let title = userFileManager.ImageVideoKey.TITLE; - let fileAssetTitle = fileAsset.get(title.toString()); - console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); - fileAsset.set(title.toString(), "newTitle"); + let displayName = userFileManager.ImageVideoKey.DISPLAY_NAME; + let fileAssetDisplayName = fileAsset.get(displayName); + console.info('fileAsset get fileAssetDisplayName = ', fileAssetDisplayName); + fileAsset.set(displayName, 'newDisplayName3'); try { await fileAsset.commitModify(); - let newFileAssetTitle = fileAsset.get(title.toString()); - console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + let newFileAssetDisplayName = fileAsset.get(displayName); + console.info('fileAsset get newFileAssetDisplayName = ', newFileAssetDisplayName); } catch (err) { console.error('release failed. message = ', err); } @@ -1090,19 +1556,19 @@ open(mode: string, callback: AsyncCallback<number>): void **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数** +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ----------------------------------- | -| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) | -| callback | AsyncCallback<number> | 是 | 回调返回文件描述符 | +| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写)。 | +| callback | AsyncCallback<number> | 是 | callback返回文件描述符。 | **示例:** ```ts async function example() { console.info('openDemo'); - let testFileName = "testFile" + Date.now() + ".jpg"; + let testFileName = 'testFile' + Date.now() + '.jpg'; const fileAsset = await mgr.createPhotoAsset(testFileName); fileAsset.open('rw', (err, fd) => { if (fd != undefined) { @@ -1131,13 +1597,13 @@ open(mode: string): Promise<number> | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------------------------------- | -| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) | +| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写)。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------- | -| Promise<number> | Promise返回文件描述符 | +| Promise<number> | Promise对象,返回文件描述符。 | **示例:** @@ -1145,7 +1611,7 @@ open(mode: string): Promise<number> async function example() { console.info('openDemo'); try { - let testFileName = "testFile" + Date.now() + ".jpg"; + let testFileName = 'testFile' + Date.now() + '.jpg'; const fileAsset = await mgr.createPhotoAsset(testFileName); let fd = await fileAsset.open('rw'); if (fd != undefined) { @@ -1172,8 +1638,8 @@ close(fd: number, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----- | -| fd | number | 是 | 文件描述符 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| fd | number | 是 | 文件描述符。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | **示例:** @@ -1217,13 +1683,13 @@ close(fd: number): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----- | -| fd | number | 是 | 文件描述符 | +| fd | number | 是 | 文件描述符。 | **返回值:** | 类型 | 说明 | | ------------------- | ---------- | -| Promise<void> | Promise返回空 | +| Promise<void> | Promise对象,返回void。 | **示例:** @@ -1264,7 +1730,7 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | callback返回缩略图的PixelMap。 | **示例:** @@ -1305,8 +1771,8 @@ getThumbnail(size: image.Size, callback: AsyncCallback<image.PixelMap>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------- | -| size | [image.Size](js-apis-image.md#size) | 是 | 缩略图尺寸 | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | +| size | [image.Size](js-apis-image.md#size) | 是 | 缩略图尺寸。 | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | callback返回缩略图的PixelMap。 | **示例:** @@ -1348,13 +1814,13 @@ getThumbnail(size?: image.Size): Promise<image.PixelMap> | 参数名 | 类型 | 必填 | 说明 | | ---- | -------------- | ---- | ----- | -| size | [image.Size](js-apis-image.md#size) | 否 | 缩略图尺寸 | +| size | [image.Size](js-apis-image.md#size) | 否 | 缩略图尺寸。 | **返回值:** | 类型 | 说明 | | ----------------------------- | --------------------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise返回缩略图的PixelMap | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise对象,返回缩略图的PixelMap。 | **示例:** @@ -1394,8 +1860,8 @@ favorite(isFavorite: boolean, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ---------------------------------- | -| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | **示例:** @@ -1413,9 +1879,9 @@ async function example() { const asset = await fetchResult.getFirstObject(); asset.favorite(true, (err) => { if (err == undefined) { - console.info("favorite successfully"); + console.info('favorite successfully'); } else { - console.error("favorite failed with error:" + err); + console.error('favorite failed with error:' + err); } }); } @@ -1435,13 +1901,13 @@ favorite(isFavorite: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------- | ---- | ---------------------------------- | -| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | +| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏。 | **返回值:** | 类型 | 说明 | | ------------------- | ---------- | -| Promise<void> | Promise返回空 | +| Promise<void> | Promise对象,返回void。 | **示例:** @@ -1458,32 +1924,124 @@ async function example() { let fetchResult = await mgr.getPhotoAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.favorite(true).then(function () { - console.info("favorite successfully"); + console.info('favorite successfully'); }).catch(function (err) { - console.error("favorite failed with error:" + err); + console.error('favorite failed with error:' + err); }); } ``` -## FetchResult +### setHidden10+ -文件检索结果集。 +setHidden(hiddenState: boolean, callback: AsyncCallback<void>): void -### getCount +将文件设置为隐私文件,使用callback方式返回异步结果。 -getCount(): number +隐私文件存在隐私相册中,对三方应用不开放,用户通过隐私相册去获取隐私文件后可以通过设置hiddenState为false来从隐私相册中移除。 -获取文件检索结果中的文件总数。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**返回值:** +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ---------------------------------- | +| hiddenState | boolean | 是 | 是否设置为隐藏文件,true:将文件资产放入隐藏相册;false:从隐藏相册中恢复。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('setHiddenDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.setHidden(true, (err) => { + if (err == undefined) { + console.info('setHidden successfully'); + } else { + console.error('setHidden failed with error:' + err); + } + }); +} +``` + +### setHidden10+ + +setHidden(hiddenState: boolean): Promise<void> + +将文件设置为隐私文件,使用promise方式返回异步结果。 + +隐私文件存在隐私相册中,对三方应用不开放,用户通过隐私相册去获取隐私文件后可以通过设置hiddenState为false来从隐私相册中移除。 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------- | ---- | ---------------------------------- | +| hiddenState | boolean | 是 | 是否设置为隐藏文件,true:将文件资产放入隐藏相册;false:从隐藏相册中恢复。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ---------- | +| Promise<void> | Promise对象,返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + // 示例代码为将文件从隐藏相册中恢复,需要先在隐藏相册预置资源 + console.info('setHiddenDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumList = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.HIDDEN); + const album = await albumList.getFirstObject(); + let fetchResult = await album.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.setHidden(false).then(() => { + console.info('setHidden successfully'); + }).catch((err) => { + console.error('setHidden failed with error:' + err); + }); +} +``` + +## FetchResult + +文件检索结果集。 + +### getCount + +getCount(): number + +获取文件检索结果中的文件总数。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**返回值:** | 类型 | 说明 | | ------ | -------- | -| number | 检索到的文件总数 | +| number | 检索到的文件总数。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1515,7 +2073,7 @@ isAfterLast(): boolean | ------- | ---------------------------------- | | boolean | 当读到最后一条记录后,后续没有记录返回true,否则返回false。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1546,7 +2104,7 @@ close(): void **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1576,13 +2134,13 @@ getFirstObject(callback: AsyncCallback<T>): void **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | ------------------------------------------- | -| callback | AsyncCallback<T> | 是 | 异步获取结果集中的第一个完成后的回调 | +| callback | AsyncCallback<T> | 是 | 异步获取结果集中的第一个完成后的回调。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1599,7 +2157,7 @@ async function example() { if (fileAsset != undefined) { console.info('fileAsset displayName: ', fileAsset.displayName); } else { - console.error("fileAsset failed with err:" + err); + console.error('fileAsset failed with err:' + err); } }); } @@ -1617,9 +2175,9 @@ getFirstObject(): Promise<T> | 类型 | 说明 | | --------------------------------------- | -------------------------- | -| Promise<T> | Promise方式返回 | +| Promise<T> | Promise对象,返回结果集中第一个对象。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1645,13 +2203,13 @@ async function example() { **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------------------------- | ---- | ----------------------------------------- | -| callbacke | AsyncCallback<T> | 是 | 异步返回结果集中下一个之后的回调 | +| callbacke | AsyncCallback<T> | 是 | 异步返回结果集中下一个之后的回调。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1670,7 +2228,7 @@ async function example() { if (fileAsset != undefined) { console.info('fileAsset displayName: ', fileAsset.displayName); } else { - console.error("fileAsset failed with err: " + err); + console.error('fileAsset failed with err: ' + err); } }); } @@ -1689,9 +2247,9 @@ async function example() { | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<T> | 返回结果集中下一个对象 | +| Promise<T> | Promise对象,返回结果集中下一个对象。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1720,13 +2278,13 @@ getLastObject(callback: AsyncCallback<T>): void **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | --------------------------- | -| callback | AsyncCallback<T> | 是 | 异步返回结果集中最后一个的回调 | +| callback | AsyncCallback<T> | 是 | 异步返回结果集中最后一个的回调。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1743,7 +2301,7 @@ async function example() { if (fileAsset != undefined) { console.info('fileAsset displayName: ', fileAsset.displayName); } else { - console.error("fileAsset failed with err: " + err); + console.error('fileAsset failed with err: ' + err); } }); } @@ -1761,9 +2319,9 @@ getLastObject(): Promise<T> | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<T> | 返回结果集中最后一个对象 | +| Promise<T> | Promise对象,返回结果集中最后一个对象。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -1789,257 +2347,724 @@ getPositionObject(index: number, callback: AsyncCallback<T>): void **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------ | +| index | number | 是 | 要获取的文件的索引,从0开始。 | +| callback | AsyncCallback<T> | 是 | 异步返回指定索引的文件资产的回调。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPositionObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getPositionObject(0, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.error('fileAsset failed with err: ' + err); + } + }); +} +``` + +### getPositionObject + +getPositionObject(index: number): Promise<T> + +获取文件检索结果中具有指定索引的文件资产。此方法使用Promise形式返回文件Asset。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | -------------- | +| index | number | 是 | 要获取的文件的索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<T> | Promise对象,返回结果集中指定索引的一个对象。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPositionObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getPositionObject(0); + console.info('fileAsset displayName: ', fileAsset.displayName); +} +``` + +### getAllObject10+ + +getAllObject(callback: AsyncCallback<Array<T>>): void + +获取文件检索结果中的所有文件资产。此方法使用callback形式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------- | ---- | ------------------------------------------- | +| callback | AsyncCallback<Array<T>> | 是 | 异步获取结果集中的所有文件资产完成后的回调。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getAllObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getAllObject((err, fileAssetList) => { + if (fileAssetList != undefined) { + console.info('fileAssetList length: ', fileAssetList.length); + } else { + console.error('fileAssetList failed with err:' + err); + } + }); +} +``` + +### getAllObject10+ + +getAllObject(): Promise<Array<T>> + +获取文件检索结果中的所有文件资产。此方法使用promise方式来异步返回。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------- | -------------------------- | +| Promise<Array<T>> | Promise对象,返回结果集中所有文件资产数组。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getAllObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAssetList = await fetchResult.getAllObject(); + console.info('fileAssetList length: ', fileAssetList.length); +} +``` + +## Album + +实体相册 + +### 属性 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------ | ------ | ---- | ---- | ------- | +| albumType8+ | [AlbumType]( #albumtype10) | 是 | 否 | 相册类型。 | +| albumSubType8+ | [AlbumSubType]( #albumsubtype10) | 是 | 否 | 相册子类型。 | +| albumName | string | 是 | 用户相册可写,预置相册不可写 | 相册名称。 | +| albumUri | string | 是 | 否 | 相册Uri。 | +| count | number | 是 | 否 | 相册中文件数量。 | +| coverUri | string | 是 | 用户相册可写,预置相册不可写 | 封面文件Uri。 | + +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +获取相册中的文件。该方法使用callback形式来返回文件。 + +**需要权限**:ohos.permission.READ_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback返回图片和视频数据结果集。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumGetFileAssetsDemoCallback'); + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption, (err, albumFetchResult) => { + if (albumFetchResult != undefined) { + console.info('album getPhotoAssets successfully, getCount: ' + albumFetchResult.getCount()); + } else { + console.error('album getPhotoAssets failed with error: ' + err); + } + }); +} +``` + +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + +获取相册中的文件。该方法使用Promise来返回文件。 + +**需要权限**:ohos.permission.READ_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise对象,返回图片和视频数据结果集。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumGetFileAssetsDemoPromise'); + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption).then((albumFetchResult) => { + console.info('album getFileAssets successfully, getCount: ' + albumFetchResult.getCount()); + }).catch((err) => { + console.error('album getFileAssets failed with error: ' + err); + }); +} +``` + +### commitModify + +commitModify(callback: AsyncCallback<void>): void; + +更新相册属性修改到数据库中。该方法使用callback形式来返回结果。 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | 是 | callback返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumCommitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify((err) => { + if (err != undefined) { + console.error('commitModify failed with error: ' + err); + } else { + console.info('commitModify successfully'); + } + }); +} +``` + +### commitModify + +commitModify(): Promise<void>; + +更新相册属性修改到数据库中。该方法使用Promise来返回结果。 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------ | +| Promise<void> | Promise对象,返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumCommitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + var albumList = await mgr.getPhotoAlbums(albumFetchOptions); + } catch (err) { + console.error('getPhotoAlbums failed. message = ', err); + } + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info('commitModify successfully'); + }).catch((err) => { + console.error('commitModify failed with error: ' + err); + }); +} +``` + +### addPhotoAssets10+ + +addPhotoAssets(assets: Array<FileAsset>, callback: AsyncCallback<void>): void; + +往相册中添加图片或者视频,需要先预置相册和文件资源。该方法使用callback形式来返回结果。 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| assets | Array<[FileAsset](#fileasset)> | 是 | 待添加到相册中的图片或视频数组。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + try { + console.info('addPhotoAssetsDemoCallback'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.addPhotoAssets([asset], (err) => { + if (err === undefined) { + console.info('album addPhotoAssets successfully'); + } else { + console.error('album addPhotoAssets failed with error: ' + err); + } + }); + } catch (err) { + console.error('addPhotoAssetsDemoCallback failed with error: ' + err); + } +} +``` + +### addPhotoAssets10+ + +addPhotoAssets(assets: Array<FileAsset>): Promise<void>; + +往相册中添加图片或者视频,需要先预置相册和文件资源。该方法使用Promise来返回结果。 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| assets | Array<[FileAsset](#fileasset)> | 是 | 待添加到相册中的图片或视频数组。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +|Promise<void> | Promise对象,返回void。 | + +**示例:** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + try { + console.info('addPhotoAssetsDemoPromise'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.addPhotoAssets([asset]).then(() => { + console.info('album addPhotoAssets successfully'); + }).catch((err) => { + console.error('album addPhotoAssets failed with error: ' + err); + }); + } catch (err) { + console.error('addPhotoAssetsDemoPromise failed with error: ' + err); + } +} +``` + +### removePhotoAssets10+ + +removePhotoAssets(assets: Array<FileAsset>, callback: AsyncCallback<void>): void; + +从相册中移除图片或者视频,需要先预置相册和文件资源。该方法使用callback形式来返回结果。 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ------------------ | -| index | number | 是 | 要获取的文件的索引,从0开始 | -| callback | AsyncCallback<T> | 是 | 异步返回指定索引的文件资产的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| assets | Array<[FileAsset](#fileasset)> | 是 | 相册中待移除的图片或视频数组。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPositionObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { - fetchColumns: [], - predicates: predicates - }; - let fetchResult = await mgr.getPhotoAssets(fetchOption); - fetchResult.getPositionObject(0, (err, fileAsset) => { - if (fileAsset != undefined) { - console.info('fileAsset displayName: ', fileAsset.displayName); - } else { - console.error("fileAsset failed with err: " + err); - } - }); + try { + console.info('removePhotoAssetsDemoCallback'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.removePhotoAssets([asset], (err) => { + if (err === undefined) { + console.info('album removePhotoAssets successfully'); + } else { + console.error('album removePhotoAssets failed with error: ' + err); + } + }); + } catch (err) { + console.error('removePhotoAssetsDemoCallback failed with error: ' + err); + } } ``` -### getPositionObject +### removePhotoAssets10+ -getPositionObject(index: number): Promise<T> +removePhotoAssets(assets: Array<FileAsset>): Promise<void>; -获取文件检索结果中具有指定索引的文件资产。此方法使用Promise形式返回文件Asset。 +从相册中移除图片或者视频,需要先预置相册和文件资源。该方法使用Promise来返回结果。 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | -------------- | -| index | number | 是 | 要获取的文件的索引,从0开始 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| assets | Array<[FileAsset](#fileasset)> | 是 | 相册中待移除的图片或视频数组。 | **返回值:** | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<T> | 返回指定索引的文件资产的对象 | +|Promise<void> | Promise对象,返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPositionObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { - fetchColumns: [], - predicates: predicates - }; - let fetchResult = await mgr.getPhotoAssets(fetchOption); - let fileAsset = await fetchResult.getPositionObject(0); - console.info('fileAsset displayName: ', fileAsset.displayName); + try { + console.info('removePhotoAssetsDemoPromise'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.USER, userFileManager.AlbumSubType.USER_GENERIC); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.removePhotoAssets([asset]).then(() => { + console.info('album removePhotoAssets successfully'); + }).catch((err) => { + console.error('album removePhotoAssets failed with error: ' + err); + }); + } catch (err) { + console.error('removePhotoAssetsDemoPromise failed with error: ' + err); + } } ``` -## Album - -实体相册 - -### 属性 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------------ | ------ | ---- | ---- | ------- | -| albumName | string | 是 | 是 | 相册名称 | -| albumUri | string | 是 | 否 | 相册Uri | -| dateModified | number | 是 | 否 | 修改日期 | -| count | number | 是 | 否 | 相册中文件数量 | -| coverUri | string | 是 | 否 | 封面文件Uri - -### getPhotoAssets +### recoverPhotoAssets10+ -getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; +recoverPhotoAssets(assets: Array<FileAsset>, callback: AsyncCallback<void>): void; -获取相册中的文件。该方法使用callback形式来返回文件。 +从回收站中恢复图片或者视频,需要先在回收站中预置文件资源。该方法使用callback形式来返回结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | -| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回图片和视频数据结果集| +| assets | Array<[FileAsset](#fileasset)> | 是 | 回收站中待恢复图片或者视频数组。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumGetFileAssetsDemoCallback'); - - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { - predicates: predicates - }; - let fetchOption = { - fetchColumns: [], - predicates: predicates - }; - const albumList = await mgr.getPhotoAlbums(albumFetchOptions); - const album = await albumList.getFirstObject(); - album.getPhotoAssets(fetchOption, (err, albumFetchResult) => { - if (albumFetchResult != undefined) { - console.info("album getPhotoAssets successfully, getCount: " + albumFetchResult.getCount()); - } else { - console.error("album getPhotoAssets failed with error: " + err); - } - }); + try { + console.info('recoverPhotoAssetsDemoCallback'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.recoverPhotoAssets([asset], (err) => { + if (err === undefined) { + console.info('album recoverPhotoAssets successfully'); + } else { + console.error('album recoverPhotoAssets failed with error: ' + err); + } + }); + } catch (err) { + console.error('recoverPhotoAssetsDemoCallback failed with error: ' + err); + } } ``` -### getPhotoAssets +### recoverPhotoAssets10+ -getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; +recoverPhotoAssets(assets: Array<FileAsset>): Promise<void>; -获取相册中的文件。该方法使用Promise来返回文件。 +从回收站中恢复图片或者视频,需要先在回收站中预置文件资源。该方法使用Promise来返回结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | -| Promise | [FetchResult](#fetchresult)<[FileAsset](#fileasset)> | 是 | 图片和视频数据结果集 | +| assets | Array<[FileAsset](#fileasset)> | 是 | 回收站中待恢复图片或者视频数组。 | + +**返回值:** -**示例**: +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +|Promise<void> | Promise对象,返回void。 | + +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumGetFileAssetsDemoPromise'); - - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { - predicates: predicates - }; - let fetchOption = { - fetchColumns: [], - predicates: predicates - }; - const albumList = await mgr.getPhotoAlbums(albumFetchOptions); - const album = await albumList.getFirstObject(); - album.getPhotoAssets(fetchOption).then((albumFetchResult) => { - console.info("album getFileAssets successfully, getCount: " + albumFetchResult.getCount()); - }).catch((err) => { - console.error("album getFileAssets failed with error: " + err); - }); + try { + console.info('recoverPhotoAssetsDemoPromise'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.recoverPhotoAssets([asset]).then(() => { + console.info('album recoverPhotoAssets successfully'); + }).catch((err) => { + console.error('album recoverPhotoAssets failed with error: ' + err); + }); + } catch (err) { + console.error('recoverPhotoAssetsDemoPromise failed with error: ' + err); + } } ``` -### commitModify +### deletePhotoAssets10+ -commitModify(callback: AsyncCallback<void>): void; +deletePhotoAssets(assets: Array<FileAsset>, callback: AsyncCallback<void>): void; -更新相册属性修改到数据库中。 +从回收站中彻底删除图片或者视频,需要先在回收站中预置文件资源。该方法使用callback形式来返回结果。 + +**注意**:此操作不可逆,执行此操作后文件资源将彻底删除,请谨慎操作。 **需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| assets | Array<[FileAsset](#fileasset)> | 是 | 回收站中待彻底删除图片或者视频数组。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumCommitModifyDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { - predicates: predicates - }; - const albumList = await mgr.getPhotoAlbums(albumFetchOptions); - const album = await albumList.getFirstObject(); - album.albumName = 'hello'; - album.commitModify((err) => { - if (err != undefined) { - console.error("commitModify failed with error: " + err); - } else { - console.info("commitModify successfully"); - } - }); + try { + console.info('deletePhotoAssetsDemoCallback'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.deletePhotoAssets([asset], (err) => { + if (err === undefined) { + console.info('album deletePhotoAssets successfully'); + } else { + console.error('album deletePhotoAssets failed with error: ' + err); + } + }); + } catch (err) { + console.error('deletePhotoAssetsDemoCallback failed with error: ' + err); + } } ``` -### commitModify +### deletePhotoAssets10+ -commitModify(): Promise<void>; +deletePhotoAssets(assets: Array<FileAsset>): Promise<void>; + +从回收站中彻底删除图片或者视频,需要先在回收站中预置文件资源。该方法使用Promise来返回结果。 -更新相册属性修改到数据库中。 +**注意**:此操作不可逆,执行此操作后文件资源将彻底删除,请谨慎操作。 **需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| assets | Array<[FileAsset](#fileasset)> | 是 | 回收站中待彻底删除图片或者视频数组。 | + **返回值:** -| 类型 | 说明 | -| ------------------- | ------------ | -| Promise<void> | Promise调用返回空 | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +|Promise<void> | Promise对象,返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumCommitModifyDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { - predicates: predicates - }; try { - var albumList = await mgr.getPhotoAlbums(albumFetchOptions); + console.info('deletePhotoAssetsDemoPromise'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let albumFetchResult = await mgr.getAlbums(userFileManager.AlbumType.SYSTEM, userFileManager.AlbumSubType.TRASH); + let album = await albumFetchResult.getFirstObject(); + let fetchResult = await album.getPhotoAssets(fetchOption); + let asset = await fetchResult.getFirstObject(); + album.deletePhotoAssets([asset]).then(() => { + console.info('album deletePhotoAssets successfully'); + }).catch((err) => { + console.error('album deletePhotoAssets failed with error: ' + err); + }); } catch (err) { - console.error('getPhotoAlbums failed. message = ', err); + console.error('deletePhotoAssetsDemoPromise failed with error: ' + err); } - const album = await albumList.getFirstObject(); - album.albumName = 'hello'; - album.commitModify().then(() => { - console.info("commitModify successfully"); - }).catch((err) => { - console.error("commitModify failed with error: " + err); - }); } ``` @@ -2049,15 +3074,15 @@ async function example() { ### 属性 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------ | ------ | ---- | ---- | ------- | -| albumName | string | 是 | 是 | 相册名称 | -| albumUri | string | 是 | 否 | 相册Uri | -| dateModified | number | 是 | 否 | 修改日期 | -| count | number | 是 | 否 | 相册中文件数量 | -| coverUri | string | 是 | 否 | 封面文件Uri +| albumName | string | 是 | 是 | 相册名称。 | +| albumUri | string | 是 | 否 | 相册Uri。 | +| dateModified | number | 是 | 否 | 修改日期。 | +| count | number | 是 | 否 | 相册中文件数量。 | +| coverUri | string | 是 | 否 | 封面文件Uri。 | ### getPhotoAssets @@ -2069,14 +3094,14 @@ getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | -| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback返回图片和视频数据结果集 | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项。 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback返回图片和视频数据结果集。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -2112,19 +3137,19 @@ getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项。 | **返回值:** | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise:[FetchResult](#fetchresult)<[FileAsset](#fileasset)>| 图片和视频数据结果集 | +| Promise:[FetchResult](#fetchresult)<[FileAsset](#fileasset)>| Promise对象,返回图片和视频数据结果集。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -2154,14 +3179,14 @@ delete(uri: string, callback: AsyncCallback<void>): void; **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| uri | string | 是 | 相册uri | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| uri | string | 是 | 相册uri。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -2198,19 +3223,19 @@ delete(uri: string): Promise<void>; **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| uri | string | 是 | 相册uri | +| uri | string | 是 | 相册uri。 | **返回值:** | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<void>| 回调返回空 | +| Promise<void>| Promise对象,返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -2245,14 +3270,14 @@ recover(uri: string, callback: AsyncCallback<void>): void; **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| uri | string | 是 | 相册uri | -| callback | AsyncCallback<void> | 是 | 回调返回空 | +| uri | string | 是 | 相册uri。 | +| callback | AsyncCallback<void> | 是 | callback返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -2289,19 +3314,19 @@ recover(uri: string): Promise<void>; **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数**: +**参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | -| uri | string | 是 | 相册uri | +| uri | string | 是 | 相册uri。 | **返回值:** | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<void>| 回调返回空 | +| Promise<void>| Promise对象,返回void。 | -**示例**: +**示例:** ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -2330,134 +3355,199 @@ async function example() { 成员类型。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ----- | ---- | ---- | ---- | ---- | -| number | number | 是 | 是 | number类型 | -| string | string | 是 | 是 | string类型 | -| boolean | boolean | 是 | 是 | boolean类型 | +| number | number | 是 | 是 | number类型。 | +| string | string | 是 | 是 | string类型。| +| boolean | boolean | 是 | 是 | boolean类型。 | ## ChangeEvent 变更监听的媒体文件类型。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ----- | ---- | ---- | ---- | ---- | -| deviceChange | string | 是 | 是 | 设备 | -| albumChange | string | 是 | 是 | 相册 | -| imageChange | string | 是 | 是 | 图片 | -| audioChange | string | 是 | 是 | 音频 | -| videoChange | string | 是 | 是 | 视频 | -| remoteFileChange | string | 是 | 是 | 远程文件 | +| deviceChange | string | 是 | 是 | 设备。 | +| albumChange | string | 是 | 是 | 相册。 | +| imageChange | string | 是 | 是 | 图片。 | +| audioChange | string | 是 | 是 | 音频。 | +| videoChange | string | 是 | 是 | 视频。 | +| remoteFileChange | string | 是 | 是 | 远程文件。 | ## PeerInfo 注册设备的信息。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore +**系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------- | -------------------------- | ---- | ---- | ---------------- | -| deviceName | string | 是 | 否 | 注册设备的名称 | -| networkId | string | 是 | 否 | 注册设备的网络ID | -| isOnline | boolean | 是 | 否 | 是否在线 | +| deviceName | string | 是 | 否 | 注册设备的名称。 | +| networkId | string | 是 | 否 | 注册设备的网络ID。 | +| isOnline | boolean | 是 | 否 | 是否在线。 | ## FileType 枚举,媒体文件类型。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 值 | 说明 | +| ----- | ---- | ---- | +| IMAGE | 1 | 图片。 | +| VIDEO | 2 | 视频。 | +| AUDIO | 3 | 音频。 | + +## PhotoSubType10+ + +枚举,不同[FileAsset](#fileasset)的类型。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 值 | 说明 | +| ----- | ---- | ---- | +| DEFAULT | 0 | 默认照片类型。 | +| SCREENSHOT | 1 | 截屏录屏文件类型。 | +| CAMERA | 2 | 相机拍摄的照片和视频类型。 | + +## PositionType10+ + +枚举,文件位置,表示文件在本地或云端。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 值 | 说明 | +| ----- | ---- | ---- | +| LOCAL | 1 | 文件只存在于本端设备。 | +| CLOUD | 2 | 文件只存在于云端。 | +| BOTH | 3 | 文件在本地和云中都存在。 | + +## AlbumType10+ + +枚举,相册类型,表示是用户相册还是系统预置相册。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 值 | 说明 | +| ----- | ---- | ---- | +| USER | 0 | 用户相册。 | +| SYSTEM | 1024 | 系统预置相册。 | + +## AlbumSubType10+ + +枚举,相册子类型,表示具体的相册类型。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 值 | 说明 | | ----- | ---- | ---- | -| IMAGE | 1 | 图片 | -| VIDEO | 2 | 视频 | -| AUDIO | 3 | 音频 | +| USER_GENERIC | 1 | 用户相册。 | +| FAVORITE | 1025 | 收藏夹。 | +| VIDEO | 1026 | 视频相册。 | +| HIDDEN | 1027 | 隐藏相册。 | +| TRASH | 1028 | 回收站。 | +| SCREENSHOT | 1029 | 截屏和录屏相册。 | +| CAMERA | 1030 | 相机拍摄的照片和视频相册。 | +| ANY | 2147483647 | 任意相册。 | ## PrivateAlbumType 枚举,系统相册类型。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 值 | 说明 | | ----- | ---- | ---- | -| TYPE_FAVORITE | 0 | 收藏夹相册 | -| TYPE_TRASH | 1 | 回收站相册 | +| TYPE_FAVORITE | 0 | 收藏夹相册。 | +| TYPE_TRASH | 1 | 回收站相册。 | ## AudioKey 枚举,音频文件关键信息。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | 文件uri | -| DISPLAY_NAME | display_name | 显示名字 | -| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | -| TITLE | title | 文件标题 | -| ARTIST | artist | 作者 | -| AUDIOALBUM | audio_album | 专辑 | -| DURATION | duration | 持续时间(单位:毫秒) | -| FAVORITE | favorite | 收藏 | +| URI | uri | 文件uri。 | +| DISPLAY_NAME | display_name | 显示名字。 | +| DATE_ADDED | date_added | 添加日期(添加文件时间距1970年1月1日的秒数值)。 | +| DATE_MODIFIED | date_modified | 修改日期(修改文件时间距1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新)。 | +| TITLE | title | 文件标题。 | +| ARTIST | artist | 作者。 | +| AUDIOALBUM | audio_album | 专辑。 | +| DURATION | duration | 持续时间(单位:毫秒)。 | +| FAVORITE | favorite | 收藏。 | ## ImageVideoKey 枚举,图片和视频文件关键信息。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | 文件uri | -| FILE_TYPE | file_type | 媒体文件类型 | -| DISPLAY_NAME | display_name | 显示名字 | -| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | -| TITLE | title | 文件标题 | -| DURATION | duration | 持续时间(单位:毫秒) | -| WIDTH | width | 图片宽度(单位:像素) | -| HEIGHT | height | 图片高度(单位:像素) | -| DATE_TAKEN | date_taken | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) | -| ORIENTATION | orientation | 图片文件的方向 | -| FAVORITE | favorite | 收藏 | +| URI | uri | 文件uri。 | +| FILE_TYPE | file_type | 媒体文件类型。 | +| DISPLAY_NAME | display_name | 显示名字。 | +| DATE_ADDED | date_added | 添加日期(添加文件时间距1970年1月1日的秒数值)。 | +| DATE_MODIFIED | date_modified | 修改日期(修改文件时间距1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新)。 | +| TITLE | title | 文件标题。 | +| DURATION | duration | 持续时间(单位:毫秒)。 | +| WIDTH | width | 图片宽度(单位:像素)。 | +| HEIGHT | height | 图片高度(单位:像素)。 | +| DATE_TAKEN | date_taken | 拍摄日期(文件拍照时间距1970年1月1日的秒数值)。 | +| ORIENTATION | orientation | 图片文件的方向。 | +| FAVORITE | favorite | 收藏。 | +| POSITION10+ | position | 文件位置类型。 | +| DATE_TRASHED10+ | date_trashed | 删除日期(删除文件时间距1970年1月1日的秒数值)。 | +| HIDDEN10+ | hidden | 文件的隐藏状态。 | ## AlbumKey 枚举,相册关键信息。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | 相册uri | -| FILE_TYPE | file_type | 媒体文件类型 | -| ALBUM_NAME | album_name | 相册名字 | -| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | +| URI | uri | 相册uri。 | +| FILE_TYPE | file_type | 媒体文件类型。 | +| ALBUM_NAME | album_name | 相册名字。 | +| DATE_ADDED | date_added | 添加日期(添加文件时间距1970年1月1日的秒数值)。 | +| DATE_MODIFIED | date_modified | 修改日期(修改文件时间距1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新)。 | + +## PhotoCreateOptions10+ + +图片或视频的创建选项。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 类型 | 必填 | 说明 | +| ---------------------- | ------------------- | ---- | ------------------------------------------------ | +| subType | [PhotoSubType](#photosubtype10) | 否 | 图片或者视频的子类型。 | ## FetchOptions 检索条件。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ | -| fetchColumns | Array<string> | 是 | 是 | 检索条件,指定列名查询,如果该参数为空时默认查询uri、name、fileType。示例:
fetchColumns: "uri"| -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | 是 | 是 | 谓词查询,显示过滤条件 | +| fetchColumns | Array<string> | 是 | 是 | 检索条件,指定列名查询,如果该参数为空时默认查询uri、name、fileType(具体字段名称以检索对象定义为准)。示例:
fetchColumns: ['uri', 'title']。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | 是 | 是 | 谓词查询,显示过滤条件。 | ## AlbumFetchOptions 相册检索条件。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | 是 | 是 | 谓词查询,显示过滤条件 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | 是 | 是 | 谓词查询,显示过滤条件。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifi.md b/zh-cn/application-dev/reference/apis/js-apis-wifi.md index 6fceb9cc33fedadf690bf98388308890e4ce04bf..f9e36545ae735bcbf902e255006fd74eb85f3175 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifi.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifi.md @@ -33,14 +33,14 @@ enableWifi(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.enableWifi(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.enableWifi(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disableWifi @@ -63,14 +63,15 @@ disableWifi(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; + +try { + wifi.disableWifi(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} - try { - wifi.disableWifi(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } ``` ## wifi.isWifiActive @@ -91,15 +92,15 @@ isWifiActive(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let isActivate = wifi.isActivate(); - console.info("isActivate:" + isActivate); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let isActivate = wifi.isActivate(); + console.info("isActivate:" + isActivate); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.scan @@ -120,14 +121,14 @@ scan(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.scan(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.scan(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getScanInfos @@ -164,46 +165,47 @@ getScanInfos(callback: AsyncCallback<Array<WifiScanInfo>>): void | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | 是 | 回调函数。当成功时,err为0,data为扫描到的热点;否则err为非0值,data为空。 | **示例:** - ```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); - } - }); - ``` + +```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 @@ -282,24 +284,24 @@ addDeviceConfig(config: WifiDeviceConfig): Promise<number> | **类型** | **说明** | | -------- | -------- | | Promise<number> | Promise对象。返回添加的网络配置ID,如果值为-1表示添加失败。 | - + **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addDeviceConfig(config).then(result => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } + wifi.addDeviceConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## WifiDeviceConfig @@ -378,21 +380,21 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>) **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addDeviceConfig(config,(error,result) => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } + wifi.addDeviceConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.addUntrustedConfig7+ @@ -415,23 +417,24 @@ addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> | **类型** | **说明** | | -------- | -------- | | Promise<boolean> | Promise对象。表示操作结果,true: 成功, false: 失败。 | + **示例:** -````` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addUntrustedConfig(config).then(result => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } -````` + wifi.addUntrustedConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.addUntrustedConfig7+ @@ -451,22 +454,22 @@ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean& | callback | AsyncCallback<boolean> | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | **示例:** -````` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addUntrustedConfig(config,(error,result) => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } -````` + wifi.addUntrustedConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.removeUntrustedConfig7+ @@ -489,18 +492,20 @@ removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> | **类型** | **说明** | | -------- | -------- | | Promise<boolean> | Promise对象。表示操作结果,true: 成功, false: 失败。 | - - ``` - import wifi from '@ohos.wifi'; - - try { - let networkId = 0; - wifi.removeUntrustedConfig(networkId).then(result => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } + +**示例:** + +```js +import wifi from '@ohos.wifi'; + +try { + let networkId = 0; + wifi.removeUntrustedConfig(networkId).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -522,17 +527,17 @@ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boole | callback | AsyncCallback<boolean> | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let networkId = 0; - wifi.removeUntrustedConfig(networkId,(error,result) => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let networkId = 0; + wifi.removeUntrustedConfig(networkId,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.connectToNetwork @@ -561,15 +566,15 @@ connectToNetwork(networkId: number): boolean **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let networkId = 0; - wifi.connectToNetwork(networkId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +```js +import wifi from '@ohos.wifi'; + +try { + let networkId = 0; + wifi.connectToNetwork(networkId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.connectToDevice @@ -598,20 +603,20 @@ connectToDevice(config: WifiDeviceConfig): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 3 - } - wifi.connectToDevice(config); - - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 } + wifi.connectToDevice(config); + +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disconnect @@ -634,14 +639,14 @@ disconnect(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.disconnect(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.disconnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getSignalLevel @@ -668,17 +673,17 @@ getSignalLevel(rssi: number, band: number): number | number | 信号强度,取值范围为[0, 4]。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let rssi = 0; - let band = 0; - let level = wifi.getSignalLevel(rssi,band); - console.info("lelvel:" + JSON.stringify(lelvel)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +```js +import wifi from '@ohos.wifi'; + +try { + let rssi = 0; + let band = 0; + let level = wifi.getSignalLevel(rssi,band); + console.info("lelvel:" + JSON.stringify(lelvel)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -716,23 +721,23 @@ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | 是 | 回调函数。当获取成功时,err为0,data表示WLAN连接信息。如果error为非0,表示处理出现错误。 | **示例:** - ```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"); - }); - ``` +```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 @@ -877,16 +882,16 @@ isFeatureSupported(featureId: number): boolean | boolean | true:支持, false:不支持。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let featureId = 0; - let ret = wifi.isFeatureSupported(featureId); - console.info("isFeatureSupported:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +```js +import wifi from '@ohos.wifi'; + +try { + let featureId = 0; + let ret = wifi.isFeatureSupported(featureId); + console.info("isFeatureSupported:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -909,15 +914,15 @@ getDeviceMacAddress(): string[] | string[] | MAC地址。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let ret = wifi.getDeviceMacAddress(); - console.info("deviceMacAddress:" + JSON.stringify(ret)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let ret = wifi.getDeviceMacAddress(); + console.info("deviceMacAddress:" + JSON.stringify(ret)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -938,15 +943,15 @@ getIpInfo(): IpInfo | [IpInfo](#ipinfo7) | IP信息。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let info = wifi.getIpInfo(); - console.info("info:" + JSON.stringify(info)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let info = wifi.getIpInfo(); + console.info("info:" + JSON.stringify(info)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## IpInfo7+ @@ -983,15 +988,15 @@ getCountryCode(): string | string | 国家码。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let code = wifi.getCountryCode(); - console.info("code:" + code); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let code = wifi.getCountryCode(); + console.info("code:" + code); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.reassociate7+ @@ -1013,14 +1018,14 @@ reassociate(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.reassociate(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.reassociate(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.reconnect7+ @@ -1042,14 +1047,14 @@ reconnect(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.reconnect(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.reconnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getDeviceConfigs7+ @@ -1071,15 +1076,15 @@ getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> |  Array<[WifiDeviceConfig](#wifideviceconfig)> | 网络配置信息的数组。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let configs = wifi.getDeviceConfigs(); - console.info("configs:" + JSON.stringify(configs)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let configs = wifi.getDeviceConfigs(); + console.info("configs:" + JSON.stringify(configs)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.updateNetwork7+ @@ -1107,20 +1112,20 @@ updateNetwork(config: WifiDeviceConfig): number | number | 返回更新的网络配置ID,如果值为-1表示更新失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 3 - } - let ret = wifi.updateNetwork(config); - console.error("ret:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 } + let ret = wifi.updateNetwork(config); + console.error("ret:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disableNetwork7+ @@ -1148,15 +1153,15 @@ disableNetwork(netId: number): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let netId = 0; - wifi.disableNetwork(netId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let netId = 0; + wifi.disableNetwork(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.removeAllNetwork7+ @@ -1178,14 +1183,14 @@ removeAllNetwork(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.removeAllNetwork(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.removeAllNetwork(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.removeDevice7+ @@ -1213,15 +1218,15 @@ removeDevice(id: number): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let id = 0; - wifi.removeDevice(id); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let id = 0; + wifi.removeDevice(id); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.enableHotspot7+ @@ -1243,14 +1248,14 @@ enableHotspot(): boolean | boolean | true:操作成功, false:操作失败。| **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.enableHotspot(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.enableHotspot(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disableHotspot7+ @@ -1272,14 +1277,14 @@ disableHotspot(): boolean | boolean | true:操作成功, false:操作失败。| **示例:** -``` - import wifi from '@ohos.wifiManager'; +```js +import wifi from '@ohos.wifiManager'; - try { - wifiManager.disableHotspot(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifiManager.disableHotspot(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.isHotspotDualBandSupported7+ @@ -1301,15 +1306,15 @@ isHotspotDualBandSupported(): boolean | boolean | true:支持, false:不支持。| **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let ret = wifi.isHotspotDualBandSupported(); - console.info("result:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let ret = wifi.isHotspotDualBandSupported(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.isHotspotActive7+ @@ -1331,15 +1336,15 @@ isHotspotActive(): boolean | boolean | true:已使能, false:未使能。| **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let ret = wifi.isHotspotActive(); - console.info("result:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let ret = wifi.isHotspotActive(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.setHotspotConfig7+ @@ -1367,23 +1372,23 @@ setHotspotConfig(config: HotspotConfig): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid: "****", - securityType: 3, - band: 0, - channel: 0, - preSharedKey: "****", - maxConn: 0 - } - let ret = wifi.setHotspotConfig(); - console.info("result:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid: "****", + securityType: 3, + band: 0, + channel: 0, + preSharedKey: "****", + maxConn: 0 } + let ret = wifi.setHotspotConfig(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## HotspotConfig7+ @@ -1422,15 +1427,15 @@ getHotspotConfig(): HotspotConfig | [HotspotConfig](#hotspotconfig7) | 热点的配置信息。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let config = wifi.getHotspotConfig(); - console.info("result:" + JSON.stringify(config)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let config = wifi.getHotspotConfig(); + console.info("result:" + JSON.stringify(config)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getStations7+ @@ -1452,15 +1457,15 @@ getStations():  Array<[StationInfo](#stationinfo7)> |  Array<[StationInfo](#stationinfo7)> | 连接的设备数组。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let stations = wifi.getStations(); - console.info("result:" + JSON.stringify(stations)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let stations = wifi.getStations(); + console.info("result:" + JSON.stringify(stations)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## StationInfo7+ @@ -1538,20 +1543,20 @@ getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 是 | 回调函数。当操作成功时,err为0,data表示P2P连接信息。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - wifi.getP2pLinkedInfo((err, data) => { - if (err) { - console.error("get p2p linked info error"); - return; - } - console.info("get wifi p2p linked info: " + JSON.stringify(data)); - }); +wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error("get p2p linked info error"); + return; + } + console.info("get wifi p2p linked info: " + JSON.stringify(data)); +}); - wifi.getP2pLinkedInfo().then(data => { - console.info("get wifi p2p linked info: " + JSON.stringify(data)); - }); +wifi.getP2pLinkedInfo().then(data => { + console.info("get wifi p2p linked info: " + JSON.stringify(data)); +}); ``` ## wifi.getCurrentGroup8+ @@ -1588,20 +1593,20 @@ getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - wifi.getCurrentGroup((err, data) => { - if (err) { - console.error("get current P2P group error"); - return; - } - console.info("get current P2P group: " + JSON.stringify(data)); - }); +wifi.getCurrentGroup((err, data) => { + if (err) { + console.error("get current P2P group error"); + return; + } + console.info("get current P2P group: " + JSON.stringify(data)); +}); - wifi.getCurrentGroup().then(data => { - console.info("get current P2P group: " + JSON.stringify(data)); - }); +wifi.getCurrentGroup().then(data => { + console.info("get current P2P group: " + JSON.stringify(data)); +}); ``` ## wifi.getP2pPeerDevices8+ @@ -1638,20 +1643,20 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifiManager'; +```js +import wifi from '@ohos.wifiManager'; - wifi.getP2pPeerDevices((err, data) => { - if (err) { - console.error("get P2P peer devices error"); - return; - } - console.info("get P2P peer devices: " + JSON.stringify(data)); - }); +wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error("get P2P peer devices error"); + return; + } + console.info("get P2P peer devices: " + JSON.stringify(data)); +}); - wifi.getP2pPeerDevices().then(data => { - console.info("get P2P peer devices: " + JSON.stringify(data)); - }); +wifi.getP2pPeerDevices().then(data => { + console.info("get P2P peer devices: " + JSON.stringify(data)); +}); ``` ## WifiP2pDevice8+ @@ -1707,22 +1712,22 @@ createGroup(config: WifiP2PConfig): boolean | boolean | true:创建群组操作执行成功, false:创建群组操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - deviceAddress: "****", - netId: 0, - passphrase: "*****", - groupName: "****", - goBand: 0 - } - wifi.createGroup(config); - - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + deviceAddress: "****", + netId: 0, + passphrase: "*****", + groupName: "****", + goBand: 0 } + wifi.createGroup(config); + +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## WifiP2PConfig8+ @@ -1770,14 +1775,14 @@ removeGroup(): boolean | boolean | true:操作执行成功, false:操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.removeGroup(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.removeGroup(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.p2pConnect8+ @@ -1805,71 +1810,71 @@ p2pConnect(config: WifiP2PConfig): boolean **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pConnectionChangeFunc = result => { - console.info("p2p connection change receive event: " + JSON.stringify(result)); - wifi.getP2pLinkedInfo((err, data) => { - if (err) { - console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); - return; - } - console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); - }); - } - wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); - - var recvP2pDeviceChangeFunc = result => { - console.info("p2p device change receive event: " + JSON.stringify(result)); - } - wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); - - var recvP2pPeerDeviceChangeFunc = result => { - console.info("p2p peer device change receive event: " + JSON.stringify(result)); - wifi.getP2pPeerDevices((err, data) => { - if (err) { - console.error('failed to get peer devices: ' + JSON.stringify(err)); - return; - } - console.info("get peer devices: " + JSON.stringify(data)); - var len = Object.keys(data).length; - for (var i = 0; i < len; ++i) { - if (data[i].deviceName === "my_test_device") { - console.info("p2p connect to test device: " + data[i].deviceAddress); - var config = { - "deviceAddress":data[i].deviceAddress, - "netId":-2, - "passphrase":"", - "groupName":"", - "goBand":0, - } - wifi.p2pConnect(config); - } - } - }); - } - wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - - var recvP2pPersistentGroupChangeFunc = () => { - console.info("p2p persistent group change receive event"); - - wifi.getCurrentGroup((err, data) => { - if (err) { - console.error('failed to get current group: ' + JSON.stringify(err)); - return; - } - console.info("get current group: " + JSON.stringify(data)); - }); - } - wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - - setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); - console.info("start discover devices -> " + wifi.startDiscoverDevices()); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); +} +wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + +var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); +} +wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + +var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); +} +wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + +var recvP2pPersistentGroupChangeFunc = () => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); +} +wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); +console.info("start discover devices -> " + wifi.startDiscoverDevices()); +``` ## wifi.p2pCancelConnect8+ @@ -1888,14 +1893,14 @@ p2pCancelConnect(): boolean | boolean | true:操作执行成功, false:操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.p2pCancelConnect(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.p2pCancelConnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.startDiscoverDevices8+ @@ -1915,14 +1920,14 @@ startDiscoverDevices(): boolean | boolean | true:操作执行成功, false:操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.startDiscoverDevices(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.startDiscoverDevices(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.stopDiscoverDevices8+ @@ -1942,14 +1947,14 @@ stopDiscoverDevices(): boolean | boolean | true:操作执行成功,操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.stopDiscoverDevices(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.stopDiscoverDevices(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.deletePersistentGroup8+ @@ -1978,15 +1983,15 @@ deletePersistentGroup(netId: number): boolean | boolean | true:操作执行成功,操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let netId = 0; - wifi.deletePersistentGroup(netId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let netId = 0; + wifi.deletePersistentGroup(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## WifiP2pGroupInfo8+ @@ -2033,15 +2038,15 @@ setDeviceName(devName: string): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let name = "****"; - wifi.setDeviceName(netId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let name = "****"; + wifi.setDeviceName(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.on('wifiStateChange')7+ @@ -2089,19 +2094,19 @@ off(type: "wifiStateChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvPowerNotifyFunc = result => { - console.info("Receive power state change event: " + result); - } - - // Register event - wifi.on("wifiStateChange", recvPowerNotifyFunc); - - // Unregister event - wifi.off("wifiStateChange", recvPowerNotifyFunc); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); +} + +// Register event +wifi.on("wifiStateChange", recvPowerNotifyFunc); + +// Unregister event +wifi.off("wifiStateChange", recvPowerNotifyFunc); +``` ## wifi.on('wifiConnectionChange')7+ @@ -2147,20 +2152,20 @@ off(type: "wifiConnectionChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 连接状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvWifiConnectionChangeFunc = result => { - console.info("Receive wifi connection change event: " + result); - } - - // Register event - wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); - - // Unregister event - wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvWifiConnectionChangeFunc = result => { + console.info("Receive wifi connection change event: " + result); +} + +// Register event +wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); + +// Unregister event +wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); +``` + ## wifi.on('wifiScanStateChange')7+ on(type: "wifiScanStateChange", callback: Callback<number>): void @@ -2204,20 +2209,20 @@ off(type: "wifiScanStateChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvWifiScanStateChangeFunc = result => { - console.info("Receive Wifi scan state change event: " + result); - } - - // Register event - wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); - - // Unregister event - wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvWifiScanStateChangeFunc = result => { + console.info("Receive Wifi scan state change event: " + result); +} + +// Register event +wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); + +// Unregister event +wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); +``` + ## wifi.on('wifiRssiChange')7+ on(type: "wifiRssiChange", callback: Callback<number>): void @@ -2254,20 +2259,19 @@ off(type: "wifiRssiChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvWifiRssiChangeFunc = result => { - console.info("Receive wifi rssi change event: " + result); - } - - // Register event - wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); - - // Unregister event - wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvWifiRssiChangeFunc = result => { + console.info("Receive wifi rssi change event: " + result); +} + +// Register event +wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); + +// Unregister event +wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); +``` ## wifi.on('hotspotStateChange')7+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -2295,20 +2299,19 @@ on(type: "hotspotStateChange", callback: Callback<number>): void | 3 | 去激活中。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvHotspotStateChangeFunc = result => { - console.info("Receive hotspot state change event: " + result); - } - - // Register event - wifi.on("hotspotStateChange", recvHotspotStateChangeFunc); - - // Unregister event - wifi.off("hotspotStateChange", recvHotspotStateChangeFunc); - ``` +```js +import wifi from '@ohos.wifi'; +var recvHotspotStateChangeFunc = result => { + console.info("Receive hotspot state change event: " + result); +} + +// Register event +wifi.on("hotspotStateChange", recvHotspotStateChangeFunc); + +// Unregister event +wifi.off("hotspotStateChange", recvHotspotStateChangeFunc); +``` ## wifi.off('hotspotStateChange')7+ @@ -2371,21 +2374,21 @@ off(type: "p2pStateChange", callback?: Callback<number>): void | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | - + **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pStateChangeFunc = result => { - console.info("Receive p2p state change event: " + result); - } - - // Register event - wifi.on("p2pStateChange", recvP2pStateChangeFunc); - - // Unregister event - wifi.off("p2pStateChange", recvP2pStateChangeFunc); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pStateChangeFunc = result => { + console.info("Receive p2p state change event: " + result); +} + +// Register event +wifi.on("p2pStateChange", recvP2pStateChangeFunc); + +// Unregister event +wifi.off("p2pStateChange", recvP2pStateChangeFunc); +``` ## wifi.on('p2pConnectionChange')8+ @@ -2423,20 +2426,20 @@ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pConnectionChangeFunc = result => { - console.info("Receive p2p connection change event: " + result); - } - - // Register event - wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); - - // Unregister event - wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvP2pConnectionChangeFunc = result => { + console.info("Receive p2p connection change event: " + result); +} + +// Register event +wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + +// Unregister event +wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc); +``` + ## wifi.on('p2pDeviceChange')8+ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void @@ -2473,20 +2476,20 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pDeviceChangeFunc = result => { - console.info("Receive recv p2p device change event: " + result); - } - - // Register event - wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); - - // Unregister event - wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvP2pDeviceChangeFunc = result => { + console.info("Receive recv p2p device change event: " + result); +} + +// Register event +wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + +// Unregister event +wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc); +``` + ## wifi.on('p2pPeerDeviceChange')8+ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void @@ -2523,19 +2526,19 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pPeerDeviceChangeFunc = result => { - console.info("Receive recv p2p peer device change event: " + result); - } - - // Register event - wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - - // Unregister event - wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pPeerDeviceChangeFunc = result => { + console.info("Receive recv p2p peer device change event: " + result); +} + +// Register event +wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + +// Unregister event +wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); +``` ## wifi.on('p2pPersistentGroupChange')8+ @@ -2571,22 +2574,22 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pPersistentGroupChange"字符串。 | | callback | Callback<void> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | - + **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pPersistentGroupChangeFunc = result => { - console.info("Receive recv p2p persistent group change event: " + result); - } - - // Register event - wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - - // Unregister event - wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pPersistentGroupChangeFunc = result => { + console.info("Receive recv p2p persistent group change event: " + result); +} + +// Register event +wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +// Unregister event +wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +``` ## wifi.on('p2pDiscoveryChange')8+ @@ -2631,16 +2634,16 @@ off(type: "p2pDiscoveryChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pDiscoveryChangeFunc = result => { - console.info("Receive recv p2p discovery change event: " + result); - } - - // Register event - wifi.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); - - // Unregister event - wifi.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); - ``` \ No newline at end of file +```js +import wifi from '@ohos.wifi'; + +var recvP2pDiscoveryChangeFunc = result => { + console.info("Receive recv p2p discovery change event: " + result); +} + +// Register event +wifi.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); + +// Unregister event +wifi.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index cd01523cbc9fb15c490ddc3e66249f2b633acc94..bc9fdee8551c7a500f1214b8a45b106d22ee08db 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -82,9 +82,9 @@ import worker from '@ohos.worker'; // worker线程创建 // FA模型-目录同级(entry模块下,workers目录与pages目录同级) -const workerFAModel01 = new worker.ThreadWorker("workers/worker.js", {name:"first worker in FA model"}); +const workerFAModel01 = new worker.ThreadWorker("workers/worker.ts", {name:"first worker in FA model"}); // FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级) -const workerFAModel02 = new worker.ThreadWorker("../workers/worker.js"); +const workerFAModel02 = new worker.ThreadWorker("../workers/worker.ts"); // Stage模型-目录同级(entry模块下,workers目录与pages目录同级) const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); @@ -383,10 +383,10 @@ workerInstance.onexit = function(e) { } //onexit被执行两种方式: -//主线程: +// main thread: workerInstance.terminate(); -//worker线程: +// worker线程: //parentPort.close() ``` @@ -871,13 +871,13 @@ Worker线程向宿主线程发送消息。 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` @@ -919,13 +919,13 @@ Worker线程向宿主线程发送消息。 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` @@ -935,7 +935,7 @@ import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e){ // let data = e.data; - workerPort.postMessage("receive data from main.js"); + workerPort.postMessage("receive data from main thread"); } ``` @@ -959,7 +959,7 @@ close(): void **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` @@ -1001,7 +1001,7 @@ DedicatedWorkerGlobalScope的onmessage属性表示Worker线程收到来自其宿 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -1012,7 +1012,7 @@ workerInstance.postMessage("hello world"); import worker from '@ohos.worker'; const workerPort = worker.workerPort; workerPort.onmessage = function(e) { - console.log("receive main.js message"); + console.log("receive main thread message"); } ``` @@ -1044,7 +1044,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当Worker对象接收到 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` @@ -1054,7 +1054,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); import worker from '@ohos.worker'; const parentPort = worker.workerPort; parentPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror") + console.log("worker.ts onmessageerror") } ``` @@ -1129,7 +1129,7 @@ GlobalScope的onerror属性表示Worker在执行过程中发生异常被调用 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") ``` @@ -1139,7 +1139,7 @@ const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") import worker from '@ohos.worker'; const workerPort = worker.workerPort workerPort.onerror = function(e){ - console.log("worker.js onerror") + console.log("worker.ts onerror") } ``` @@ -1192,9 +1192,9 @@ import worker from '@ohos.worker'; // worker线程创建 // FA模型-目录同级 -const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker in FA model"}); +const workerFAModel01 = new worker.Worker("workers/worker.ts", {name:"first worker in FA model"}); // FA模型-目录不同级(以workers目录放置pages目录前一级为例) -const workerFAModel02 = new worker.Worker("../workers/worker.js"); +const workerFAModel02 = new worker.Worker("../workers/worker.ts"); // Stage模型-目录同级 const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); @@ -1274,7 +1274,7 @@ postMessage(message: Object, transfer: ArrayBuffer[]): void; **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); @@ -1301,7 +1301,7 @@ postMessage(message: Object, options?: PostMessageOptions): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); @@ -1331,7 +1331,7 @@ on(type: string, listener: EventListener): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1359,7 +1359,7 @@ once(type: string, listener: EventListener): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1387,7 +1387,7 @@ off(type: string, listener?: EventListener): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); //使用on接口、once接口或addEventListener接口创建“alert”事件,使用off接口删除事件。 workerInstance.off("alert"); ``` @@ -1407,7 +1407,7 @@ terminate(): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.terminate(); ``` @@ -1432,13 +1432,13 @@ Worker对象的onexit属性表示Worker销毁时被调用的事件处理程序 **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onexit = function(e) { console.log("onexit"); } //onexit被执行两种方式: -//主线程: +//main thread: workerInstance.terminate(); //worker线程: @@ -1466,7 +1466,7 @@ Worker对象的onerror属性表示Worker在执行过程中发生异常被调用 **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onerror = function(e) { console.log("onerror"); } @@ -1493,7 +1493,7 @@ Worker对象的onmessage属性表示宿主线程接收到来自其创建的Worke **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onmessage = function(e) { // e : MessageEvent, 用法如下: // let data = e.data; @@ -1522,7 +1522,7 @@ Worker对象的onmessageerror属性表示当Worker对象接收到一条无法被 **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.onmessageerror= function(e) { console.log("onmessageerror"); } @@ -1554,7 +1554,7 @@ addEventListener(type: string, listener: EventListener): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1582,7 +1582,7 @@ removeEventListener(type: string, callback?: EventListener): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1616,7 +1616,7 @@ dispatchEvent(event: Event): boolean **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未支持。 ``` @@ -1624,7 +1624,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未 分发事件(dispatchEvent)可与监听接口(on、once、addEventListener)搭配使用,示例如下: ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); //用法一: workerInstance.on("alert_on", (e)=>{ @@ -1676,7 +1676,7 @@ removeAllListener(): void **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -1730,17 +1730,17 @@ Worker线程向宿主线程发送消息。 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ @@ -1771,22 +1771,22 @@ Worker线程向宿主线程发送消息。 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { // let data = e.data; - console.log("receive data from worker.js"); + console.log("receive data from worker.ts"); } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ // let data = e.data; - parentPort.postMessage("receive data from main.js"); + parentPort.postMessage("receive data from main thread"); } ``` @@ -1804,12 +1804,12 @@ close(): void **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { @@ -1839,17 +1839,17 @@ DedicatedWorkerGlobalScope的onmessage属性表示Worker线程收到来自其宿 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { - console.log("receive main.js message"); + console.log("receive main thread message"); } ``` @@ -1875,16 +1875,16 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当Worker对象接收到 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror") + console.log("worker.ts onmessageerror") } ``` @@ -1938,7 +1938,7 @@ parentPort.onmessageerror = function(e) { **示例:** ```js -const workerInstance = new worker.Worker("workers/worker.js"); +const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -2008,16 +2008,16 @@ WorkerGlobalScope的onerror属性表示Worker在执行过程中发生异常被 **示例:** ```js -// main.js +// main thread import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") +const workerInstance = new worker.Worker("workers/worker.ts") ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort parentPort.onerror = function(e){ - console.log("worker.js onerror") + console.log("worker.ts onerror") } ``` @@ -2043,17 +2043,17 @@ parentPort.onerror = function(e){ > 以API version 9的FA工程为例。 ```js -// main.js +// main thread import worker from '@ohos.worker'; -const workerInstance = new worker.ThreadWorker("workers/worker.js"); -workerInstance.postMessage("message from main to worker"); +const workerInstance = new worker.ThreadWorker("workers/worker.ts"); +workerInstance.postMessage("message from main thread to worker"); workerInstance.onmessage = function(d) { // 当worker线程传递obj2时,data即为obj2。data没有Init、SetName的方法 let data = d.data; } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; class MyModel { @@ -2063,7 +2063,7 @@ class MyModel { } } workerPort.onmessage = function(d) { - console.log("worker.js onmessage"); + console.log("worker.ts onmessage"); let data = d.data; let func1 = function() { console.log("post message is function"); @@ -2081,10 +2081,10 @@ workerPort.onmessage = function(d) { workerPort.postMessage(obj2); // 传递obj2不会发生序列化错误 } workerPort.onmessageerror = function(e) { - console.log("worker.js onmessageerror"); + console.log("worker.ts onmessageerror"); } workerPort.onerror = function(e) { - console.log("worker.js onerror"); + console.log("worker.ts onerror"); } ``` @@ -2101,7 +2101,7 @@ Actor并发模型的交互原理:各个Actor并发地处理主线程任务, - 自API version 9版本开始,若Worker处于已经销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的BusinessError。 - Worker的创建和销毁耗费性能,建议管理已创建的Worker并重复使用。 - 创建Worker工程时,new worker.Worker构造函数和new worker.ThreadWorker构造函数不能同时使用,否则将导致工程中Worker的功能异常。自API version 9版本开始,建议使用[new worker.ThreadWorker](#constructor9)构造函数,在API version 8及之前的版本,建议使用[new worker.Worker](#constructordeprecated)构造函数。 -- 创建Worker工程时,在Worker线程的文件中(比如本文中worker.ts)不能导入任何有关构建UI的方法(比如ETS文件等),否则会导致Worker的功能失效。排查方式:解压生成的Hap包,在创建Worker线程的文件目录中找到"worker.js",全局搜索"View"关键字。如果存在该关键字,说明在worker.js中打包进去了构建UI的方法,会导致Worker的功能失效,建议在创建Worker线程的文件中修改 "import “xxx” from src"中src的目录层级。 +- 创建Worker工程时,在Worker线程的文件中(比如本文中worker.ts)不能导入任何有关构建UI的方法(比如ets文件等),否则会导致Worker的功能失效。排查方式:解压生成的Hap包,在创建Worker线程的文件目录中找到"worker.js",全局搜索"View"关键字。如果存在该关键字,说明在worker.js中打包进去了构建UI的方法,会导致Worker的功能失效,建议在创建Worker线程的文件中修改 "import “xxx” from src"中src的目录层级。 ## 完整示例 > **说明:**
@@ -2109,15 +2109,10 @@ Actor并发模型的交互原理:各个Actor并发地处理主线程任务, ### FA模型 ```js -// main.js(同级目录为例) +// main thread(同级目录为例) import worker from '@ohos.worker'; // 主线程中创建Worker对象 const workerInstance = new worker.ThreadWorker("workers/worker.ts"); -// 创建js和ts文件都可以 -// const workerInstance = new worker.ThreadWorker("workers/worker.js"); - -// API version 9之前版本,worker对象的构造方法 -// const workerInstance = new worker.Worker("workers/worker.js"); // 主线程向worker线程传递信息 workerInstance.postMessage("123"); @@ -2126,7 +2121,7 @@ workerInstance.postMessage("123"); workerInstance.onmessage = function(e) { // data:worker线程发送的信息 let data = e.data; - console.log("main.js onmessage"); + console.log("main thread onmessage"); // 销毁Worker对象 workerInstance.terminate(); @@ -2134,7 +2129,7 @@ workerInstance.onmessage = function(e) { // 在调用terminate后,执行回调onexit workerInstance.onexit = function() { - console.log("main.js terminate"); + console.log("main thread terminate"); } ``` ```js @@ -2144,9 +2139,6 @@ import worker from '@ohos.worker'; // 创建worker线程中与主线程通信的对象 const workerPort = worker.workerPort -// API version 9之前版本,创建worker线程中与主线程通信的对象 -// const parentPort = worker.parentPort - // worker线程接收主线程信息 workerPort.onmessage = function(e) { // data:主线程发送的信息 @@ -2174,13 +2166,11 @@ build-profile.json5 配置 : ``` ### Stage模型 ```js -// main.js(以不同目录为例) +// main thread(以不同目录为例) import worker from '@ohos.worker'; // 主线程中创建Worker对象 const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts"); -// 创建js和ts文件都可以 -// const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.js"); // 主线程向worker线程传递信息 workerInstance.postMessage("123"); @@ -2189,14 +2179,14 @@ workerInstance.postMessage("123"); workerInstance.onmessage = function(e) { // data:worker线程发送的信息 let data = e.data; - console.log("main.js onmessage"); + console.log("main thread onmessage"); // 销毁Worker对象 workerInstance.terminate(); } // 在调用terminate后,执行onexit workerInstance.onexit = function() { - console.log("main.js terminate"); + console.log("main thread terminate"); } ``` ```js diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index b34b6d946f49a2796f0d49f2ba4827ea6f8f5887..187881a92ce1c274d5018b8f133ca193b41c897e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -148,10 +148,12 @@ - [Shape](ts-drawing-components-shape.md) - 画布组件 - [Canvas](ts-components-canvas-canvas.md) - - [CanvasRenderingContext2D对象](ts-canvasrenderingcontext2d.md) - [CanvasGradient对象](ts-components-canvas-canvasgradient.md) + - [CanvasPattern](ts-components-canvas-canvaspattern.md) + - [CanvasRenderingContext2D对象](ts-canvasrenderingcontext2d.md) - [ImageBitmap对象](ts-components-canvas-imagebitmap.md) - [ImageData对象](ts-components-canvas-imagedata.md) + - [Matrix2D](ts-components-canvas-matrix2d.md) - [OffscreenCanvasRenderingContext2D对象](ts-offscreencanvasrenderingcontext2d.md) - [Path2D对象](ts-components-canvas-path2d.md) - [Lottie](ts-components-canvas-lottie.md) diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/canvas_pattern.gif b/zh-cn/application-dev/reference/arkui-ts/figures/canvas_pattern.gif new file mode 100644 index 0000000000000000000000000000000000000000..98acc8dbefc1e6e93a7679e0787d2be007943668 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/canvas_pattern.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/colorFilter.gif b/zh-cn/application-dev/reference/arkui-ts/figures/colorFilter.gif new file mode 100644 index 0000000000000000000000000000000000000000..e326b328a292ca96b3c2b687128d51cce1106d27 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/colorFilter.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md index b56ae7462ea262d96d87f4b30ab7111bc5748dca..b199a59a9fb33a1c13b61ffd7a1a50d8bcc287ca 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md @@ -46,18 +46,18 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) | 名称 | 参数类型 | 必填 | 描述 | | ------------- | ------- | ---- | -------- | -| closeEffect | boolean | 是 | 关闭数据占比图表旋转动效。
默认值:false | +| closeEffect | boolean | 是 | 关闭数据占比图表旋转动效和投影效果。
默认值:false
**说明:**
若未设置trackShadow属性,则该属性控制投影效果的开关,开启投影的效果为投影的默认效果。
若设置trackShadow属性,则由trackShadow属性值控制投影效果的开关。| | valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10对象说明)> | 是 | 各数据段颜色,ResourceColor为纯色,LinearGradient为渐变色。| | trackBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 是 | 底板颜色。
默认值:'#081824' | | strokeWidth10+ | [Length](ts-types.md#Length) | 是 | 圆环粗细。
默认值:24
单位:vp
**说明:**
设置小于0的值时,按默认值显示。
数据面板的类型为DataPanelType.Line时该属性不生效。 | -| trackShadow10+ | [DataPanelShadowOption](#datapanelshadowoption10对象说明) | 是 | 投影样式,不设置为不开启投影。| +| trackShadow10+ | [DataPanelShadowOption](#datapanelshadowoption10对象说明) | 是 | 投影样式。
**说明:**
设置null为不开启投影。| ## DataPanelShadowOption10+对象说明 | 名称 | 参数类型 | 必填 | 描述 | | ------------- | ------- | ---- | -------- | -| radius | number \| [Resource](ts-types.md#resource类型) | 否 | 阴影模糊半径。
默认值:5
单位:vp | -| colors | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10对象说明)> | 否 | 各数据段阴影的颜色。
默认值:与valueColors值相同 | +| radius | number \| [Resource](ts-types.md#resource类型) | 否 | 投影模糊半径。
默认值:5
单位:vp
**说明:**
设置小于等于0的值时,按默认值显示。| +| colors | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10对象说明)> | 否 | 各数据段投影的颜色。
默认值:与valueColors值相同
**说明:**
若设置的投影颜色的个数少于数据段个数时,则显示的投影颜色的个数和设置的投影颜色个数一致。
若设置的投影颜色的个数多于数据段个数时,则显示的投影颜色的个数和数据段个数一致。| | offsetX | number \| [Resource](ts-types.md#resource类型) | 否 | X轴的偏移量。
默认值:5
单位:vp | | offsetY | number \| [Resource](ts-types.md#resource类型) | 否 | Y轴的偏移量。
默认值:5
单位:vp | @@ -79,7 +79,7 @@ LinearGradient(colorStops: ColorStop[]) | 名称 | 参数类型 | 必填 | 描述 | | ------------- | ------- | ---- | -------- | | color | [ResourceColor](ts-types.md#resourcecolor) | 是 | 颜色值。| -| offset | [Length](ts-types.md#Length) | 是 | 渐变色断点(0~1之间的比例值)。| +| offset | [Length](ts-types.md#Length) | 是 | 渐变色断点(0~1之间的比例值,若数据值小于0则置为0,若数据值大于1则置为1)。| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md index 8f2609ef6a4828d2703f7066e08036266a107ca9..f0cdf20e57b7dba240039a1cb6add8de68ae0959 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-gauge.md @@ -23,9 +23,9 @@ Gauge(options:{value: number, min?: number, max?: number}) | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 量规图的当前数据值,即图中指针指向位置。用于组件创建时量规图初始值的预置。 | +| value | number | 是 | 量规图的当前数据值,即图中指针指向位置。用于组件创建时量规图初始值的预置。
**说明:**
value不在min和max范围内时使用min作为默认值。 | | min | number | 否 | 当前数据段最小值。
默认值:0 | -| max | number | 否 | 当前数据段最大值。
默认值:100 | +| max | number | 否 | 当前数据段最大值。
默认值:100
**说明:**
max小于min时使用默认值0和100。
max和min支持负数。 | ## 属性 @@ -36,8 +36,8 @@ Gauge(options:{value: number, min?: number, max?: number}) | value | number | 设置量规图的数据值,可用于动态修改量规图的数据值。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | startAngle | number | 设置起始角度位置,时钟0点为0度,顺时针方向为正角度。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | endAngle | number | 设置终止角度位置,时钟0点为0度,顺时针方向为正角度。
默认值:360
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| colors | Array<[ColorStop](#colorstop)> | 设置量规图的颜色,支持分段颜色设置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| strokeWidth | Length | 设置环形量规图的环形厚度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| colors | Array<[ColorStop](#colorstop)> | 设置量规图的颜色,支持分段颜色设置。
默认值:Color.Black
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| strokeWidth | Length | 设置环形量规图的环形厚度。
默认值:4
单位:vp
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置小于0的值时,按默认值显示。
不支持百分比。 | ## ColorStop diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index f836f4bd8e1e685867e0d78fb2049e2f56e6c667..d840690c99c798c6d639acbe613b1c2d48287fe7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -413,3 +413,86 @@ struct LoadImageExample { } } ``` + +### 为图片增加滤镜 + +```ts +// xxx.ets +@Entry +@Component +struct colorFilterExample { + @State colorFilterR: number = 0 + @State colorFilterG: number = 0 + @State colorFilterB: number = 0 + @State colorFilterA: number = 0 + + build() { + Row() { + Column() { + Image($r('app.media.sky')) + .width(200) + .height(200) + Image($r('app.media.sky')) + .width(200) + .height(200) + .colorFilter([ + this.colorFilterR, 0, this.colorFilterR, 0, 0, + 0, this.colorFilterG, this.colorFilterG, 0, 0, + this.colorFilterB, 0, this.colorFilterB, 0, 0, + 0, 0, this.colorFilterA, 0, 0 + ]) + + Row() { + Text('R') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueR) => { + this.colorFilterR = valueR + }) + } + + Row() { + Text('G') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueG) => { + this.colorFilterG = valueG + }) + } + + Row() { + Text('B') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueB) => { + this.colorFilterB = valueB + }) + } + + Row() { + Text('A') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueA) => { + this.colorFilterA = valueA + }) + } + }.width('90%').alignItems(HorizontalAlign.Center) + }.height('100%').width('100%').justifyContent(FlexAlign.Center) + } +} +``` + +![colorFilter](figures/colorFilter.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md index 178c95ff9f2f3515d59ae425d5b1a8dfaa131ffa..164d8612e63633f14b0fc749c1d6ce400b5d16d2 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md @@ -17,31 +17,33 @@ ImageAnimator() +从API version 10开始,该接口支持在ArkTS卡片中使用。 + ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: | 参数名称 | 参数类型 |参数描述 | | ---------- | ----------------------- |-------- | -| images | Array<[ImageFrameInfo](#imageframeinfo对象说明)> | 设置图片帧信息集合。每一帧的帧信息(ImageFrameInfo)包含图片路径、图片大小、图片位置和图片播放时长信息,详见ImageFrameInfo属性说明。
默认值:[]
**说明:**
不支持动态更新。 | -| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | 默认为初始状态,用于控制播放状态。
默认值:AnimationStatus.Initial | -| duration | number | 单位为毫秒,默认时长为1000ms;duration为0时,不播放图片;值的改变只会在下一次循环开始时生效;当images中任意一帧图片设置了单独的duration后,该属性设置无效。
默认值:1000 | -| reverse | boolean | 设置播放顺序。false表示从第1张图片播放到最后1张图片; true表示从最后1张图片播放到第1张图片。
默认值:false | -| fixedSize | boolean | 设置图片大小是否固定为组件大小。 true表示图片大小与组件大小一致,此时设置图片的width 、height 、top 和left属性是无效的。false表示每一张图片的width 、height 、top和left属性都要单独设置。
默认值:true | -| preDecode(deprecated) | number | 预解码的图片数量。例如该值设为2,则播放当前页时会提前加载后面两张图片至缓存以提升性能。
从API version9开始废弃。
默认值:0 | -| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | 设置动画开始前和结束后的状态,可选值参见FillMode说明。
默认值:FillMode.Forwards | -| iterations | number | 默认播放一次,设置为-1时表示无限次播放。
默认值:1 | +| images | Array<[ImageFrameInfo](#imageframeinfo对象说明)> | 设置图片帧信息集合。每一帧的帧信息(ImageFrameInfo)包含图片路径、图片大小、图片位置和图片播放时长信息,详见ImageFrameInfo属性说明。
默认值:[]
**说明:**
不支持动态更新。
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | 默认为初始状态,用于控制播放状态。
默认值:AnimationStatus.Initial
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| duration | number | 单位为毫秒,默认时长为1000ms;duration为0时,不播放图片;值的改变只会在下一次循环开始时生效;当images中任意一帧图片设置了单独的duration后,该属性设置无效。
默认值:1000
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| reverse | boolean | 设置播放顺序。false表示从第1张图片播放到最后1张图片; true表示从最后1张图片播放到第1张图片。
默认值:false
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| fixedSize | boolean | 设置图片大小是否固定为组件大小。 true表示图片大小与组件大小一致,此时设置图片的width 、height 、top 和left属性是无效的。false表示每一张图片的width 、height 、top和left属性都要单独设置。
默认值:true
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| preDecode(deprecated) | number | 预解码的图片数量。例如该值设为2,则播放当前页时会提前加载后面两张图片至缓存以提升性能。
从API version9开始废弃。
默认值:0 | +| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | 设置动画开始前和结束后的状态,可选值参见FillMode说明。
默认值:FillMode.Forwards
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| iterations | number | 默认播放一次,设置为-1时表示无限次播放。
默认值:1 | ## ImageFrameInfo对象说明 | 参数名称 | 参数类型 | 必填 | 参数描述 | | -------- | -------------- | -------- | -------- | -| src | string \| [Resource](ts-types.md#resource)9+ | 是 | 图片路径,图片格式为svg,png和jpg,从API Version9开始支持[Resource](ts-types.md#resource)类型的路径。| -| width | number \| string | 否 | 图片宽度。
默认值:0 | -| height | number \| string | 否 | 图片高度。
默认值:0 | -| top | number \| string | 否 | 图片相对于组件左上角的纵向坐标。
默认值:0 | -| left | number \| string | 否 | 图片相对于组件左上角的横向坐标。
默认值:0 | -| duration | number | 否 | 每一帧图片的播放时长,单位毫秒。
默认值:0 | +| src | string \| [Resource](ts-types.md#resource)9+ | 是 | 图片路径,图片格式为svg,png和jpg,从API Version9开始支持[Resource](ts-types.md#resource)类型的路径。
从API version 10开始,该接口支持在ArkTS卡片中使用。| +| width | number \| string | 否 | 图片宽度。
默认值:0
从API version 10开始,该接口支持在ArkTS卡片中使用 | +| height | number \| string | 否 | 图片高度。
默认值:0
从API version 10开始,该接口支持在ArkTS卡片中使用 | +| top | number \| string | 否 | 图片相对于组件左上角的纵向坐标。
默认值:0
从API version 10开始,该接口支持在ArkTS卡片中使用 | +| left | number \| string | 否 | 图片相对于组件左上角的横向坐标。
默认值:0
从API version 10开始,该接口支持在ArkTS卡片中使用 | +| duration | number | 否 | 每一帧图片的播放时长,单位毫秒。
默认值:0 | ## 事件 @@ -49,11 +51,11 @@ ImageAnimator() | 名称 | 功能描述 | | -------- | -------- | -| onStart(event: () => void) | 状态回调,动画开始播放时触发。 | -| onPause(event: () => void) | 状态回调,动画暂停播放时触发。 | -| onRepeat(event: () => void) | 状态回调,动画重复播放时触发。 | -| onCancel(event: () => void) | 状态回调,动画取消播放时触发。 | -| onFinish(event: () => void) | 状态回调,动画播放完成时触发。 | +| onStart(event: () => void) | 状态回调,动画开始播放时触发。
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| onPause(event: () => void) | 状态回调,动画暂停播放时触发。
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| onRepeat(event: () => void) | 状态回调,动画重复播放时触发。 | +| onCancel(event: () => void) | 状态回调,动画取消播放时触发。
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| onFinish(event: () => void) | 状态回调,动画播放完成时触发。
从API version 10开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md index d963978b349fdf7a2891edc57052a4854c180447..b3dc5f38fe32a0158d9cdabe26553ac3f3cd21ed 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -20,7 +20,7 @@ Search(options?: { value?: string; placeholder?: ResourceStr; icon?: string; con | ----------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | value | string | 否 | 设置当前显示的搜索文本内容。
从API version 10开始,该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量。 | | placeholder | [ResourceStr](ts-types.md#resourcestr)10+ | 否 | 设置无输入时的提示文本。 | -| icon | string | 否 | 设置搜索图标路径,默认使用系统搜索图标。
图标所支持的图片类型能力参考[Image](ts-basic-components-image.md)组件。 | +| icon | string | 否 | 设置搜索图标路径,默认使用系统搜索图标。
**说明:**
icon的数据源支持本地图片和网络图片。
- 支持的图片格式包括png、jpg、bmp、svg、gif和pixelmap。
- 支持Base64字符串。格式data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], 其中[base64 data]为Base64字符串数据。 | | controller | SearchController | 否 | 设置Search组件控制器。 | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md index ff77df617e991d7e4fe916fdb69bf85ff72a71cc..88a73673ec288aa1e2593aae85d68cfd09971a3b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -83,7 +83,7 @@ Slier组件滑块形状枚举。 | 名称 | 功能描述 | | -------- | -------- | -| onChange(callback: (value: number, mode: SliderChangeMode) => void) | Slider拖到或点击时触发事件回调。
value:当前滑动进度值。若返回值有小数,可使用number.toFixed()方法将数据处理为预期的精度。
mode:事件触发的相关状态值。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Begin和End状态当手势点击时都会触发,Moving和Click状态当value值发生变换时触发。
当连贯动作为拖动动作时,不触发Click状态。
value值的变化范围为对应步长steps数组。 | +| onChange(callback: (value: number, mode: SliderChangeMode) => void) | Slider拖动或点击时触发事件回调。
value:当前滑动进度值。若返回值有小数,可使用number.toFixed()方法将数据处理为预期的精度。
mode:事件触发的相关状态值。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
Begin和End状态当手势点击时都会触发,Moving和Click状态当value值发生变化时触发。
当连贯动作为拖动动作时,不触发Click状态。
value值的变化范围为对应步长steps数组。 | ## SliderChangeMode枚举说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md index 2dcd381ba8e505f7525ec7a4c7ba38838046aae6..b044077108773c9cdaf2f3623ebd1b78f6fa7131 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -24,7 +24,7 @@ StepperItem() | -------- | -------- | -------- | | prevLabel | string | 设置左侧文本按钮内容,第一页没有左侧文本按钮,当步骤导航器大于一页时,除第一页外默认值都为“返回”。 | | nextLabel | string | 设置右侧文本按钮内容,最后一页默认值为“开始”,其余页默认值为“下一步”。 | -| status | ItemState | 步骤导航器nextLabel的显示状态。
默认值:ItemState.Normal | +| status | [ItemState](#itemstate枚举说明) | 步骤导航器nextLabel的显示状态,参数可选。
默认值:ItemState.Normal | ## ItemState枚举说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md index 8a941ecd6d95717f54bc02d6c7d16f02f8d801ed..2783c0acf161f5da292bce06987bc9a23e477de9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -30,8 +30,8 @@ Text(content?: string | Resource) | 名称 | 参数类型 | 描述 | | ----------------------- | ----------------------------------- | ------------------------------------------- | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式
默认值:TextAlign.Start
说明:
文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
当`overflow`设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。设置TextOverflow.None与TextOverflow.Clip效果一样。当`overflow`设置为TextOverflow.Marquee时,文本在一行内滚动显示,设置`maxLines`属性不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式。
默认值:TextAlign.Start
说明:
文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,即align属性中Alignment.TopStart、Alignment.Top、Alignment.TopEnd效果相同,控制内容在顶部,Alignment.Start、Alignment.Center、Alignment.End效果相同,控制内容垂直居中,Alignment.BottomStart、Alignment.Bottom、Alignment.BottomEnd效果相同,控制内容在底部。结合TextAlign属性可控制内容在水平方向的位置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
当`overflow`设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。设置TextOverflow.None与TextOverflow.Clip效果一样。当`overflow`设置为TextOverflow.Marquee时,文本在一行内滚动显示,设置`maxLines`及`copyOption`属性均不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | maxLines | number | 设置文本的最大行数。
默认值:Infinity
**说明:**
默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 `textOverflow`来指定截断方式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
}
从API version 9开始,该接口支持在ArkTS卡片中使用。| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index 91e7fb0caa0042686270389a8588def380b18d9d..97ed0d015d702a766e05b3241b9362db6e4460c1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -81,14 +81,14 @@ caretPosition(value: number): void setTextSelection(selectionStart: number, selectionEnd: number): void -设置文本选择范围。 +组件在获焦状态下,调用该接口设置文本选择区域并高亮显示,且只有在selectionStart小于selectionEnd时,文字才会被选取、高亮显示。 **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| -------------- | -------- | ---- | ------------------ | -| selectionStart | number | 是 | 选择范围起始位置。 | -| selectionEnd | number | 是 | 选择范围结束位置。 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------------- | -------- | ---- | ------------------------------------------------------------ | +| selectionStart | number | 是 | 文本选择区域起始位置,文本框中文字的起始位置为0。
当selectionStart小于0时、按照0处理;当selectionStart大于文字最大长度时、按照文字最大长度处理。
| +| selectionEnd | number | 是 | 文本选择区域结束位置。
当selectionEnd小于0时、按照0处理;当selectionEnd大于文字最大长度时、按照文字最大长度处理。
| ## 示例 @@ -130,4 +130,4 @@ struct TextAreaExample { } ``` -![textArea](figures/textArea.gif) \ No newline at end of file +![textArea](figures/textArea.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index f389bd0adc81576ba9abebfc79137c182f8d9c4e..0144f1e59af3472a5c005c0f671ed27225dcca33 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -42,7 +42,7 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | showPasswordIcon9+ | boolean | 密码输入模式时,输入框末尾的图标是否显示。
默认值:true | | style9+ | [TextInputStyle](#textinputstyle9枚举说明) | 设置输入框为默认风格或内联输入风格。
默认值:TextInputStyle.Default | | textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | 设置输入文本在输入框中的对齐方式。
默认值:TextAlign.Start | -| selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置文本选中底板颜色。 | +| selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置文本选中底板颜色。
如果未设置透明度,默认为不透明(例如:“0x80000000”为50%透明度黑色)。 | | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | 设置光标风格。 | | caretPosition10+ | number | 设置光标位置。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index 81af8ec72af25f8cfcaa71d91b444a86e222d55a..c24a25c777d6b5b232aa3d5d30151e2c2cb4b2db 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -33,7 +33,7 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) | -------- | ---------------- | | Checkbox | 提供单选框样式。
**说明:**
[通用属性margin](ts-universal-attributes-size.md)的默认值为:
{
 top: 12 px,
 right: 12 px,
 bottom: 12 px,
 left: 12 px
} | | Button | 提供状态按钮样式,如果子组件有文本设置,则相应的文本内容会显示在按钮内部。 | -| Switch | 提供开关样式。
**说明:**
[通用属性margin](ts-universal-attributes-size.md)默认值为:
{
 top: 14 px,
 right:6 px,
 bottom: 6 px,
 left: 14 px
} | +| Switch | 提供开关样式。
**说明:**
[通用属性margin](ts-universal-attributes-size.md)默认值为:
{
 top: 6px,
 right: 14px,
 bottom: 6 px,
 left: 14 px
} | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 8064fe0a391ca043834bcee421be7345bd626188..1e4a0f358d76a285de40d13f7ee59bbcc366b28f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -40,9 +40,9 @@ RenderingContextSettings(antialias?: boolean) | 名称 | 类型 | 描述 | | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为number时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为number时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 | -| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为number时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为number时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
默认值:'butt'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
默认值:'miter'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
默认值:10
从API version 9开始,该接口支持在ArkTS卡片中使用。 | @@ -1269,11 +1269,11 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | 图源对象,具体参考ImageBitmap对象。 | | repetition | string | 是 | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'、'clamp'、'mirror'。
默认值:'' | -**返回值:**: +**返回值:** | 类型 | 说明 | | ------------------------------- | ----------------------- | -| [CanvasPattern](#canvaspattern) | 通过指定图像和重复方式创建图片填充的模板对象。 | +| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 通过指定图像和重复方式创建图片填充的模板对象。 | **示例:** @@ -1886,6 +1886,12 @@ getTransform(): Matrix2D 从API version 9开始,该接口支持在ArkTS卡片中使用。 +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------- | ---------- | +| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | 矩阵对象。 | + ### resetTransform @@ -2141,6 +2147,7 @@ setTransform方法使用的参数和transform()方法相同,但setTransform() ![zh-cn_image_0000001238712421](figures/zh-cn_image_0000001238712421.png) +### setTransform setTransform(transform?: Matrix2D): void @@ -2148,6 +2155,11 @@ setTransform(transform?: Matrix2D): void 从API version 9开始,该接口支持在ArkTS卡片中使用。 +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| --------- | ----------------------------------------------------- | ---- | ------ | ---------- | +| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | 否 | null | 变换矩阵。 | ### translate @@ -2899,9 +2911,3 @@ struct CanvasExample { ``` ![zh-cn_image_0000001239032419](figures/zh-cn_image_0000001239032420.png) - -## CanvasPattern - -一个Object对象, 通过[createPattern](#createpattern)方法创建。 - -从API version 9开始,该接口支持在ArkTS卡片中使用。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvaspattern.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvaspattern.md new file mode 100644 index 0000000000000000000000000000000000000000..5563ac5a2a58a0d56efa788346642b8651c76677 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvaspattern.md @@ -0,0 +1,73 @@ +# CanvasPattern + +一个Object对象,使用[createPattern](ts-canvasrenderingcontext2d.md#createpattern)方法创建,通过指定图像和重复方式创建图片填充的模板。 + +> **说明:** +> +> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +## 方法 + +### setTransform + +setTransform(transform?: Matrix2D): void + +使用Matrix2D对象作为参数、对当前CanvasPattern进行矩阵变换。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| --------- | ----------------------------------------------------- | ---- | ------ | ---------- | +| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | 否 | null | 转换矩阵。 | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct CanvasPatternPage { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() + private img: ImageBitmap = new ImageBitmap("common/pattern.jpg") + private pattern : CanvasPattern + + build() { + Column() { + Button("Click to set transform") + .onClick(() => { + this.matrix.scaleY = 1 + this.matrix.scaleX = 1 + this.matrix.translateX = 50 + this.matrix.translateY = 200 + this.pattern.setTransform(this.matrix) + this.context.fillRect(0, 0, 480, 720) + }) + .width("45%") + .margin("5px") + Canvas(this.context) + .width('100%') + .height('80%') + .backgroundColor('#FFFFFF') + .onReady(() => { + this.pattern = this.context.createPattern(this.img, 'no-repeat') + this.context.fillStyle = this.pattern + this.matrix.scaleY = 0.5 + this.matrix.scaleX = 0.5 + this.matrix.translateX = 50 + this.matrix.translateY = 50 + this.pattern.setTransform(this.matrix) + this.context.fillRect(0, 0, 480, 720) + }) + } + .width('100%') + .height('100%') + } +} +``` + +![CanvasPattern](./figures/canvas_pattern.gif) + diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-matrix2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-matrix2d.md new file mode 100644 index 0000000000000000000000000000000000000000..a6169aedd540447bcd7e435f82feb179b25498d9 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-matrix2d.md @@ -0,0 +1,601 @@ +# Matrix2D + +矩阵对象,可以对矩阵进行缩放、旋转、平移等变换。 + +> **说明:** +> +> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +## 接口 + +Matrix2D() + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +## 属性 + +| 属性 | 类型 | 描述 | +| ------------------------- | ------ | ------------------------------------------------------------ | +| [scaleX](#scalex) | number | 水平缩放系数。 从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [scaleY](#scaley) | number | 垂直缩放系数。 从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [rotateX](#rotatex) | number | 水平倾斜系数。从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [rotateY](#rotatey) | number | 垂直倾斜系数。从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [translateX](#translatex) | number | 水平平移距离,单位为vp。 从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [translateY](#translatey) | number | 垂直平移距离,单位为vp。 从API version 9开始,该接口支持在ArkTS卡片中使用。 | + +> **说明:** +> +> 可使用[px2vp](ts-pixel-units.md)接口进行单位转换。 + +### scaleX + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DScaleX { + @State message: string = 'Matrix2D ScaleX' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("Set scaleX") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.scaleX = 1 + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### scaleY + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DScaleY { + @State message: string = 'Matrix2D ScaleY' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("Set scaleY") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.scaleY = 1 + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### rotateX + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DRotateX { + @State message: string = 'Matrix2D RotateX' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("Set rotateX") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.rotateX = Math.sin(45 / Math.PI) + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### rotateY + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DRotateY { + @State message: string = 'Matrix2D RotateY' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("Set rotateY") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.rotateY = Math.cos(45 / Math.PI) + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### translateX + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DTranslateX { + @State message: string = 'Matrix2D TranslateX' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("Set translateX") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.translateX = 10 + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### translateY + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DTranslateY { + @State message: string = 'Matrix2D TranslateY' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("Set translateY") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.translateY = 10 + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +## 方法 + +### identity + +identity(): Matrix2D + +创建一个单位矩阵。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ---------- | +| [Matrix2D](#matrix2d) | 单位矩阵。 | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DIdentity { + @State message: string = 'Matrix2D Identity' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("matrix identity") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix = matrix.identity() + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### invert + +invert(): Matrix2D + +得到当前矩阵的逆矩阵。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------ | +| [Matrix2D](#matrix2d) | 逆矩阵结果。 | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DInvert { + @State message: string = 'Matrix2D Invert' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("matrix invert") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.scaleX = 2 + matrix.scaleY = 1 + matrix.rotateX = 0 + matrix.rotateY = 0 + matrix.translateX = 10 + matrix.translateY = 20 + matrix.invert() + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### multiply(deprecated) + +multiply(other?: Matrix2D): Matrix2D + +当前矩阵与目标矩阵相乘。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。该接口为空接口。 + +该接口从API version 10开始废弃。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ----- | -------- | ---- | ------ | ---------- | +| other | Matrix2D | 否 | null | 目标矩阵。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | -------------- | +| [Matrix2D](#matrix2d) | 相乘结果矩阵。 | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DMultiply { + @State message: string = 'Matrix2D Multiply' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("matrix multiply") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.scaleX = 1 + matrix.scaleY = 1 + matrix.rotateX = 0 + matrix.rotateY = 0 + matrix.translateX = 0 + matrix.translateY = 0 + var other: Matrix2D = new Matrix2D() + other.scaleX = 2 + other.scaleY = 2 + other.rotateX = 0 + other.rotateY = 0 + other.translateX = 10 + other.translateY = 10 + other.multiply(other) + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### rotate10+ + +rotate(degree: number, rx?: number, ry?: number): Matrix2D + +以旋转点为中心、对当前矩阵进行右乘旋转运算。 + +从API version 10开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ------ | ------ | ---- | ------ | ------------------------------------------------------------ | +| degree | number | 是 | 0 | 旋转角度,单位为弧度。顺时针方向为正角度,可以通过Math.PI / 180将角度转换为弧度值。 | +| rx | number | 否 | 0 | 旋转点的水平方向坐标,单位为vp。 | +| ry | number | 否 | 0 | 旋转点的垂直方向坐标,单位为vp。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | -------------------- | +| [Matrix2D](#matrix2d) | 旋转后结果矩阵对象。 | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DRotate { + @State message: string = 'Matrix2D Rotate' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("matrix rotate") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.scaleX = 1 + matrix.scaleY = 1 + matrix.rotateX = 0 + matrix.rotateY = 0 + matrix.translateX = 0 + matrix.translateY = 0 + matrix.rotate(90 / Math.PI, 10, 10) + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### translate + +translate(tx?: number, ty?: number): Matrix2D + +对当前矩阵进行左乘平移运算。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ---- | ------ | ---- | ------ | ---------------------------- | +| tx | number | 否 | 0 | 水平方向平移距离,单位为vp。 | +| ty | number | 否 | 0 | 垂直方向平移距离,单位为vp。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | -------------------- | +| [Matrix2D](#matrix2d) | 平移后结果矩阵对象。 | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DTranslate { + @State message: string = 'Matrix2D Translate' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("matrix translate") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.scaleX = 1 + matrix.scaleY = 1 + matrix.rotateX = 0 + matrix.rotateY = 0 + matrix.translateX = 0 + matrix.translateY = 0 + matrix.translate(100, 100) + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +### scale + +scale(sx?: number, sy?: number): Matrix2D + +对当前矩阵进行右乘缩放运算。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ---- | ------ | ---- | ------ | ------------------ | +| sx | number | 否 | 1 | 水平缩放比例系数。 | +| sy | number | 否 | 1 | 垂直缩放比例系数。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------ | +| [Matrix2D](#matrix2d) | 缩放结果矩阵对象。 | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct Matrix2DScale { + @State message: string = 'Matrix2D Scale' + + printMatrix(title, matrix) { + console.log(title) + console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + + ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + + ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + Button("matrix scale") + .onClick(() => { + var matrix : Matrix2D = new Matrix2D() + matrix.scaleX = 1 + matrix.scaleY = 1 + matrix.rotateX = 0 + matrix.rotateY = 0 + matrix.translateX = 0 + matrix.translateY = 0 + matrix.scale(0.5, 0.5) + this.printMatrix(this.message, matrix) + }) + } + .width('100%') + } + .height('100%') + } +} +``` diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md index ca470aa1214056fcd8070adb15955a907ea0ef31..dc2cfc788d3d07d9ea67d829bd480e61a307d5d2 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md @@ -52,7 +52,7 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | | listDirection | [Axis](ts-appendix-enums.md#axis) | 设置List组件排列方向。
默认值:Axis.Vertical
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | 设置ListItem分割线样式,不支持设置百分比,默认无分割线。
- strokeWidth: 分割线的线宽。
- color: 分割线的颜色。
- startMargin: 分割线与列表侧边起始端的距离。
- endMargin: 分割线与列表侧边结束端的距离。
从API version 9开始,该接口支持在ArkTS卡片中使用。
endMargin +startMargin 不能超过列宽度。
startMargin和endMargin不支持设置百分比。
List的分割线画在主轴方向两个子组件之间,第一个子组件上方和最后一个子组件下方不会绘制分割线。
多列模式下,ListItem与ListItem之间的分割线起始边距从每一列的交叉轴方向起始边开始计算,其他情况从List交叉轴方向起始边开始计算。 | +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | 设置ListItem分割线样式,默认无分割线。
- strokeWidth: 分割线的线宽。
- color: 分割线的颜色。
- startMargin: 分割线与列表侧边起始端的距离。
- endMargin: 分割线与列表侧边结束端的距离。
从API version 9开始,该接口支持在ArkTS卡片中使用。
endMargin +startMargin 不能超过列宽度。
startMargin和endMargin不支持设置百分比。
List的分割线画在主轴方向两个子组件之间,第一个子组件上方和最后一个子组件下方不会绘制分割线。
多列模式下,ListItem与ListItem之间的分割线起始边距从每一列的交叉轴方向起始边开始计算,其他情况从List交叉轴方向起始边开始计算。 | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 | | cachedCount | number | 设置列表中ListItem/ListItemGroup的预加载数量,只在[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)中生效,其中ListItemGroup将作为一个整体进行计算,ListItemGroup中的所有ListItem会一次性全部加载出来。具体使用可参考[减少应用白块说明](../../ui/arkts-performance-improvement-recommendation.md#减少应用滑动白块)。
默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
单列模式下,会在List显示的ListItem前后各缓存cachedCount个ListItem。
多列模式下, 会在List显示的ListItem前后各缓存cachedCount*列数个ListItem。 | | editMode(deprecated) | boolean | 声明当前List组件是否处于可编辑模式。
从API version9开始废弃。
默认值:false | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md index f30539c2f88a4f6d85de0f1347bc5ce5217b5cfb..5c0b0b53bffdb6ef76d7ae4a007410ca9382fdb7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -44,7 +44,7 @@ Swiper(controller?: SwiperController) | displayMode | SwiperDisplayMode | 主轴方向上元素排列的模式,优先以displayCount设置的个数显示,displayCount未设置时本属性生效。
默认值:SwiperDisplayMode.Stretch | | cachedCount8+ | number | 设置预加载子组件个数。
默认值:1
**说明:**
cachedCount已经做了预加载的优化,不建议与[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)一起使用。 | | disableSwipe8+ | boolean | 禁用组件滑动切换功能。
默认值:false | -| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | 设置Swiper的动画曲线,默认为淡入淡出曲线,常用曲线参考[Curve枚举说明](ts-appendix-enums.md#curve),也可以通过[插值计算](../apis/js-apis-curve.md)模块提供的接口创建自定义的插值曲线对象。
默认值:Curve.Ease | +| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | 设置Swiper的动画曲线,默认为淡入淡出曲线,常用曲线参考[Curve枚举说明](ts-appendix-enums.md#curve),也可以通过[插值计算](../apis/js-apis-curve.md)模块提供的接口创建自定义的插值曲线对象。
默认值:Curve.Linear | | indicatorStyle8+ | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md),
selectedColor?: [ResourceColor](ts-types.md)
} | 设置导航点样式:
\- left: 设置导航点距离Swiper组件左边的距离。
\- top: 设置导航点距离Swiper组件顶部的距离。
\- right: 设置导航点距离Swiper组件右边的距离。
\- bottom: 设置导航点距离Swiper组件底部的距离。
\- size: 设置导航点的直径。
\- mask: 设置是否显示导航点蒙层样式。
\- color: 设置导航点的颜色。
\- selectedColor: 设置选中的导航点的颜色。 | | displayCount8+ | number\|string | 设置一页内元素显示个数。
默认值:1
**说明:**
字符串类型仅支持设置为'auto',显示效果同SwiperDisplayMode.AutoLinear。
使用number类型时,子组件按照主轴均分Swiper宽度(减去displayCount-1的itemSpace)的方式进行主轴拉伸(收缩)布局。 | | effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。
默认值:EdgeEffect.Spring
**说明:**
控制器接口调用时不生效回弹。 | @@ -210,4 +210,4 @@ struct SwiperExample { } ``` -![swiper](figures/swiper.gif) \ No newline at end of file +![swiper](figures/swiper.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md index 04cc1ad48cf426210993e10d55a6fb19409426fa..d2bb8b9d77395d72396a1428c3688d1909644add 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -41,8 +41,8 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr | vertical | boolean | 设置为false是为横向Tabs,设置为true时为纵向Tabs。
默认值:false | | scrollable | boolean | 设置为true时可以通过滑动页面进行页面切换,为false时不可滑动切换页面。
默认值:true | | barMode | BarMode | TabBar布局模式,具体描述见BarMode枚举说明。
默认值:BarMode.Fixed | -| barWidth | number \| Length8+ | TabBar的宽度值。
**说明:**
设置为小于0或大于Tabs宽度值时,按默认值显示。 | -| barHeight | number \| Length8+ | TabBar的高度值。
**说明:**
设置为小于0或大于Tabs宽度值时,按默认值显示。 | +| barWidth | number \| Length8+ | TabBar的宽度值。
默认值:
未设置带样式的TabBar且vertical属性为false时,默认值为Tabs的宽度。
未设置带样式的TabBar且vertical属性为true时,默认值为56vp。
设置SubTabbarStyle样式且vertical属性为false时,默认值为Tabs的宽度。
设置SubTabbarStyle样式且vertical属性为true时,默认值为56vp。
设置BottomTabbarStyle样式且vertical属性为true时,默认值为96vp。
设置BottomTabbarStyle样式且vertical属性为false时,默认值为Tabs的宽度。
**说明:**
设置为小于0或大于Tabs宽度值时,按默认值显示。 | +| barHeight | number \| Length8+ | TabBar的高度值。
默认值:
未设置带样式的TabBar且vertical属性为false时,默认值为56vp。
未设置带样式的TabBar且vertical属性为true时,默认值为Tabs的高度。
设置SubTabbarStyle样式且vertical属性为false时,默认值为56vp。
设置SubTabbarStyle样式且vertical属性为true时,默认值为Tabs的高度。
设置BottomTabbarStyle样式且vertical属性为true时,默认值为Tabs的高度。
设置BottomTabbarStyle样式且vertical属性为false时,默认值为56vp。
**说明:**
设置为小于0或大于Tabs高度值时,按默认值显示。| | animationDuration | number | TabContent滑动动画时长。不设置时,点击切换页签无动画,滑动切换有动画;设置时,点击切换和滑动切换都有动画。
默认值:300
**说明:**
设置为小于0或百分比时,按默认值显示。 | | divider10+ | [DividerStyle](#dividerstyle10对象说明) \| null | 用于设置区分TabBar和TabContent的分割线样式设置分割线样式,默认不显示分割线。
DividerStyle: 分割线的样式;
null: 不显示分割线。 | | fadingEdge10+ | boolean | 设置页签超过容器宽度时是否渐隐消失
默认值:true | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index c203bd2371555dddb87e1cc9854660a1187d7d11..1f791b2caf3f55a4cc4274e9d2120a04cf5ae14e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -110,9 +110,10 @@ struct CustomDialogUser { customStyle: false }) + // 在自定义组件即将析构销毁时将dialogControlle删除和置空 aboutToDisappear() { - delete this.dialogController, - this.dialogController = undefined + delete this.dialogController, // 删除dialogController + this.dialogController = undefined // 将dialogController置空 } onCancel() { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 047b4c783b6802414d20a3c2bfdc84fee13ba3b5..8823443bf9dac73a25e134252837f7a13d9f10e5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -27,9 +27,9 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, settings?: Rend | 名称 | 类型 | 描述 | | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为number时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为number时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineWidth](#linewidth) | number | 设置绘制线条的宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为number时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为number时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
- 默认值:'butt'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
- 默认值:'miter'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
- 默认值:10。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | @@ -1280,7 +1280,7 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu | 类型 | 说明 | | ------------------------------- | ----------------------- | -| [CanvasPattern](#canvaspattern) | 通过指定图像和重复方式创建图片填充的模板对象。 | +| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | 通过指定图像和重复方式创建图片填充的模板对象。 | **示例:** @@ -1925,6 +1925,11 @@ getTransform(): Matrix2D 从API version 9开始,该接口支持在ArkTS卡片中使用。 +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------- | ---------- | +| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | 矩阵对象。 | ### resetTransform @@ -3000,9 +3005,3 @@ struct OffscreenCanvasConicGradientPage { ``` ![zh-cn_image_0000001239032419](figures/zh-cn_image_0000001239032420.png) - -## CanvasPattern - -一个Object对象, 通过[createPattern](#createpattern)方法创建。 - -从API version 9开始,该接口支持在ArkTS卡片中使用。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index 4d527b1fe4c4ef36af2adf80fc291ba59b9bda66..637af5f82670074428b988214b11e693febe3b5b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -40,7 +40,7 @@ | 名称 | 类型 | 必填 | 描述 | | ---------------------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 提示气泡内容的构造器。 | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 提示气泡内容的构造器。
**说明:**
popup为通用属性,自定义popup中不支持再次弹出popup。对builder下的第一层容器组件不支持使用position属性,如果使用将导致气泡不显示。 | | placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡的颜色。 | | enableArrow | boolean | 否 | 是否显示箭头。
从API Version 9开始,如果箭头所在方位侧的气泡长度不足以显示下箭头,则会默认不显示箭头。比如:placement设置为Left,此时如果气泡高度小于箭头的宽度(32vp)与气泡圆角两倍(48vp)之和(80vp),则实际不会显示箭头。
默认值:true | @@ -112,7 +112,7 @@ struct PopupExample { .bindPopup(this.customPopup, { builder: this.popupBuilder, placement: Placement.Top, - maskColor: '0x33000000', + mask: {color:'0x33000000'}, popupColor: Color.Yellow, enableArrow: true, showInSubWindow: false, diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index ac23958c7db2a7f4271484d5aa6b6ab8ddf042ef..733e49cde195026da3d3ffb7c677c22dfac61704 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -71,10 +71,10 @@ | 名称 | 描述 | | ----- | ----------------- | | DRAG_SUCCESS | 拖拽成功 | -| DRAG_FAIL | 拖拽失败 | -| DRAG_CANCEL | 拖拽取消 | -| ENABLE_DROP | 组件允许落入 | -| DISABLE_DROP | 组件不允许落入 | +| DRAG_FAILED | 拖拽失败 | +| DRAG_CANCELED | 拖拽取消 | +| DROP_ENABLED | 组件允许落入 | +| DROP_DISABLED | 组件不允许落入 | ## 示例 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md b/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md index 46b6f21845ad06667c31091c0c9d34d11f64093c..bd7edf5760e8b30bbc6350aa10a91f36f0e3ebd0 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md @@ -22,4 +22,41 @@ The DataShareHelper is not initialized successfully. **处理步骤** 1. 咨询DataShare服务端提供者,获取正确的uri路径。 -2. DataShare仅支持Stage模型,检查context是否为Stage模型的context。 \ No newline at end of file +2. DataShare仅支持Stage模型,检查context是否为Stage模型的context。 + +## 15700011 添加/删除模板异常 + +**错误信息** + +The uri is not exist. + +**错误描述** + +添加/删除模板异常时,系统会产生此错误码。 + +**可能原因** + +1. 添加模板异常时,接口addTemplate的入参uri不正确。 +2. 删除模板异常时,接口delTemplate的入参uri不正确。 + +**处理步骤** + +咨询DataShare服务端提供者,获取正确的uri路径。 + +## 15700012 数据区不存在 + +**错误信息** + +The data area is not exist. + +**错误描述** + +数据更新异常时,系统会产生此错误码。 + +**可能原因** + +数据更新异常时,接口publish的入参bundleName不正确。 + +**处理步骤** + +咨询DataShare服务端提供者,获取正确的bundleName。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md b/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md index 94683a9fbed9f6eec70f4d2aa26907d7495fecdc..2ee8c54182533f715403a4a0cade66fc1fc7cc42 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md @@ -1,4 +1,4 @@ -# 键鼠穿越管理错误码 +# 键鼠穿越管理错误码(待停用) > **说明:** > diff --git a/zh-cn/application-dev/reference/native-apis/Readme-CN.md b/zh-cn/application-dev/reference/native-apis/Readme-CN.md index a4c69e7b287af84c564ee6a69cc37eaee7144938..56e89cb8de8e3a8bd38b57dbfd595ed7e2d6ad5b 100644 --- a/zh-cn/application-dev/reference/native-apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/native-apis/Readme-CN.md @@ -21,6 +21,7 @@ - [HuksKeyApi](_huks_key_api.md) - [HuksParamSetApi](_huks_param_set_api.md) - [HuksTypeApi](_huks_type_api.md) + - [Init](init.md) - 头文件 - [drawing_bitmap.h](drawing__bitmap_8h.md) - [drawing_brush.h](drawing__brush_8h.md) @@ -62,6 +63,7 @@ - [native_huks_api.h](native__huks__api_8h.md) - [native_huks_param.h](native__huks__param_8h.md) - [native_huks_type.h](native__huks__type_8h.md) + - [syscap_ndk.h](syscap__ndk_8h.md) - 结构体 - [OH_Drawing_BitmapFormat](_o_h___drawing___bitmap_format.md) - [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) diff --git a/zh-cn/application-dev/reference/native-apis/init.md b/zh-cn/application-dev/reference/native-apis/init.md new file mode 100644 index 0000000000000000000000000000000000000000..227e03e0b4c878790ccbd142b2e93756e5b02396 --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/init.md @@ -0,0 +1,54 @@ +# Init + + +## 概述 + +提供系统能力查询接口。 + +通过读取系统能力参数文件,返回指定的某个系统能力是否被支持。 + +**起始版本:** + +8 + + +## 汇总 + + +### 文件 + +| 名称 | 描述 | +| -------- | -------- | +| [syscap_ndk.h](syscap__ndk_8h.md) | 查询单个系统能力是否被支持的API。 | + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [canIUse](#caniuse) (const char \*cap) | 查询指定的系统能力是否被支持。 系统能力(SystemCapability,简称SysCap),指操作系统中每一个相对独立的特性。不同的设备对应不同的系统能力集,每个系统能力对应一个或多个API。开发者可根据系统能力来判断是否可以使用某接口。 | + + +## 函数说明 + + +### canIUse() + + +``` +bool canIUse (const char * cap) +``` + +**描述:** + +查询指定的系统能力是否被支持。 系统能力(SystemCapability,简称SysCap),指操作系统中每一个相对独立的特性。不同的设备对应不同的系统能力集,每个系统能力对应一个或多个API。开发者可根据系统能力来判断是否可以使用某接口。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| cap | 待查询的系统能力名称。 | + +**返回:** + +系统能力查询结果,true表示系统具备该能力,false表示系统不具备。 diff --git a/zh-cn/application-dev/reference/native-apis/syscap__ndk_8h.md b/zh-cn/application-dev/reference/native-apis/syscap__ndk_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..a8803443c00b1df574f9568202dc7ff6f4ad4bcc --- /dev/null +++ b/zh-cn/application-dev/reference/native-apis/syscap__ndk_8h.md @@ -0,0 +1,24 @@ +# syscap_ndk.h + + +## 概述 + +查询单个系统能力是否被支持的API。 + +**起始版本:** + +8 + +**相关模块:** + +[Init](init.md) + + +## 汇总 + + +### 函数 + +| 名称 | 描述 | +| -------- | -------- | +| [canIUse](init.md#caniuse) (const char \*cap) | 查询指定的系统能力是否被支持。
系统能力(SystemCapability,简称SysCap),指操作系统中每一个相对独立的特性。不同的设备对应不同的系统能力集,每个系统能力对应一个或多个API。开发者可根据系统能力来判断是否可以使用某接口。 | diff --git a/zh-cn/application-dev/reference/syscap-list.md b/zh-cn/application-dev/reference/syscap-list.md index a6f93df873d2c99562f8d45ef29b8b7bc4bd0ec6..46fb2e39815ef2560410b16163c0405d6aa0fdae 100644 --- a/zh-cn/application-dev/reference/syscap-list.md +++ b/zh-cn/application-dev/reference/syscap-list.md @@ -4,7 +4,9 @@ SysCap,全称SystemCapability,即系统能力,指操作系统中每一个 开发者使用某个接口进行开发前,建议先阅读[SysCap使用指南](syscap.md),了解Syscap的定义和使用指导。再结合下文中的表格判断具体能力集是否支持某个设备,提高开发效率。 -> 说明:default代表了一个功能比较全面的OpenHarmony设备,具有大部分的通用能力。在尚未明确设备具体能力集的情况下,可使用default类型进行开发。 +> **说明:** +> +> Default代表了一个功能比较全面的OpenHarmony设备,具有大部分的通用能力。在尚未明确设备具体能力集的情况下,可使用Default类型进行开发。 ## SystemCapability.ArkUI.ArkUI.Full diff --git a/zh-cn/application-dev/reference/syscap.md b/zh-cn/application-dev/reference/syscap.md index 5ab69bbb18a97b2645a1300ea7a258741fb19bad..2eeaed9a4cda4c4404c683270a3fefa164f1378e 100644 --- a/zh-cn/application-dev/reference/syscap.md +++ b/zh-cn/application-dev/reference/syscap.md @@ -93,29 +93,49 @@ DevEco Studio会根据创建的工程所支持的设置自动配置联想能力 ### 判断 API 是否可以使用 -- 方法1:OpenHarmony定义了API canIUse帮助开发者来判断该设备是否支持某个特定的syscap。 - - ```ts - if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) { - console.log("该设备支持SystemCapability.ArkUI.ArkUI.Full"); - } else { - console.log("该设备不支持SystemCapability.ArkUI.ArkUI.Full"); - } - ``` - -- 方法2:开发者可通过import的方式将模块导入,若当前设备不支持该模块,import的结果为undefined,开发者在使用其API时,需要判断其是否存在。 - - ```ts - import geolocation from '@ohos.geolocation'; - - if (geolocation) { - geolocation.getCurrentLocation((location) => { - console.log(location.latitude, location.longitude); - }); - } else { - console.log('该设备不支持位置信息'); - } - ``` +当前提供了ArtTS API和Native API用于帮助判断某个API是否可以使用。 + +- ArkTS API + + - 方法1:OpenHarmony定义了API canIUse帮助开发者来判断该设备是否支持某个特定的syscap。 + + ```ts + if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) { + console.log("该设备支持SystemCapability.ArkUI.ArkUI.Full"); + } else { + console.log("该设备不支持SystemCapability.ArkUI.ArkUI.Full"); + } + ``` + + - 方法2:开发者可通过import的方式将模块导入,若当前设备不支持该模块,import的结果为undefined,开发者在使用其API时,需要判断其是否存在。 + + ```ts + import geolocation from '@ohos.geolocation'; + + if (geolocation) { + geolocation.getCurrentLocation((location) => { + console.log(location.latitude, location.longitude); + }); + } else { + console.log('该设备不支持位置信息'); + } + ``` +- Native API + + ```c + #include + #include + #include "syscap_ndk.h" + + char syscap[] = "SystemCapability.ArkUI.ArkUI.Full"; + bool result = canIUse(syscap); + if (result) { + printf("SysCap: %s is supported!\n", syscap); + } else { + printf("SysCap: %s is not supported!\n", syscap); + } + ``` + 除此之外,开发者可以通过API参考文档查询API接口所属的SysCap。 ### 不同设备相同能力的差异检查 diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index bb1e857b9ca7d6889ee28637eedae689e029480b..d512d0d715c0a82060cec85d950a11c4f9f0f9e9 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -24,11 +24,11 @@ | 标签 | 是否必填 | 说明 | | --------- | -------- | ------------------------------------------------------------ | | name | 是 | 权限名称。 | -| reason | 否 | 描述申请权限的原因。
> **说明**:当申请的权限为user_grant权限时,此字段必填。 | -| usedScene | 否 | 描述权限使用的场景和时机。
> **说明**:当申请的权限为user_grant权限时,此字段必填。 | +| reason | 否 | 描述申请权限的原因。
> **说明**:当申请的权限为user_grant权限时,此字段必填。 | +| usedScene | 否 | 描述权限使用的场景和时机。
> **说明**:当申请的权限为user_grant权限时,此字段必填。 | | abilities | 否 | 标识需要使用到该权限的Ability,标签为数组形式。
**适用模型**:Stage模型 | | ability | 否 | 标识需要使用到该权限的Ability,标签为数组形式。
**适用模型**:FA模型 | -| when | 否 | 标识权限使用的时机,值为`inuse/always`。
- inuse:表示为仅允许前台使用。
- always:表示前后台都可使用。 | +| when | 否 | 标识权限使用的时机,值为`inuse/always`。
- inuse:表示为仅允许前台使用。
- always:表示前后台都可使用。 | ### Stage模型 @@ -307,7 +307,9 @@ reqPermissions() { - `app_signature`字段配置为应用的指纹信息。指纹信息的配置参见[应用特权配置指南](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#install_list_capabilityjson中配置)。 - `permissions`字段中`name`配置为需要预授权的`user_grant`类型的权限名;`permissions`字段中`userCancellable`表示为用户是否能够取消该预授权,配置为true,表示支持用户取消授权,为false则表示不支持用户取消授权。 -> **说明**:当前仅支持预置应用配置该文件。 +> **说明**: +> +> 当前仅支持预置应用配置该文件。 ```json [ diff --git a/zh-cn/application-dev/security/hapsigntool-guidelines.md b/zh-cn/application-dev/security/hapsigntool-guidelines.md index fc36ed99b1b25c7f977b622bfaea7fb577eb63ba..cb98abdfe2f4ee66bc0a8d7a6a72e65b578b68a2 100644 --- a/zh-cn/application-dev/security/hapsigntool-guidelines.md +++ b/zh-cn/application-dev/security/hapsigntool-guidelines.md @@ -241,7 +241,9 @@ OpenHarmony系统内置密钥库文件,文件名称为OpenHarmony.p12,内含 java -jar hap-sign-tool.jar generate-keypair -keyAlias "oh-app1-key-v1" -keyAlg "ECC" -keySize "NIST-P-256" -keystoreFile "OpenHarmony.p12" -keyPwd "123456" -keystorePwd "123456" ``` - > **说明:** 请记录下**keyAlias、keyStorePwd**和**keyPwd**的值,在后续生成应用 签名证书和对Hap包进行签名操作会使用到。 + > **说明:** + > + > 请记录下**keyAlias、keyStorePwd**和**keyPwd**的值,在后续生成应用 签名证书和对Hap包进行签名操作会使用到。 该命令的参数说明: @@ -319,7 +321,9 @@ OpenHarmony系统内置密钥库文件,文件名称为OpenHarmony.p12,内含 ```shell java -jar hap-sign-tool.jar sign-app -keyAlias "oh-app1-key-v1" -signAlg "SHA256withECDSA" -mode "localSign" -appCertFile "app1.pem" -profileFile "app1-profile.p7b" -inFile "app1-unsigned.zip" -keystoreFile "OpenHarmony.p12" -outFile "app1-signed.hap" -keyPwd "123456" -keystorePwd "123456" ``` - > **说明**:以下参数说明默认为无应用签名证书场景,当开发场景为有应用签名证书场景时,下列参数需要修改: + > **说明**: + > + > 以下参数说明默认为无应用签名证书场景,当开发场景为有应用签名证书场景时,下列参数需要修改: > -keyAlias:密钥别名,填写已有应用签名证书对应的密钥别名,参数必填。 > -appCertFile:应用签名证书,填写已有的应用签名证书,参数必填。 > -keystoreFile:密钥库文件,填写已有应用签名证书对应的密钥库文件,参数必填。 diff --git a/zh-cn/application-dev/security/hapsigntool-overview.md b/zh-cn/application-dev/security/hapsigntool-overview.md index 993d56023533862a6121ad98243441669091f3d1..d415d2dd7f57605723442151046fd7ed3677dd82 100644 --- a/zh-cn/application-dev/security/hapsigntool-overview.md +++ b/zh-cn/application-dev/security/hapsigntool-overview.md @@ -2,7 +2,9 @@ 为了保证OpenHarmony应用的完整性和来源可靠,在应用构建时需要对应用进行签名。经过签名的应用才能在真机设备上安装、运行、和调试。[developtools_hapsigner仓](https://gitee.com/openharmony/developtools_hapsigner)提供了签名工具的源码,包含密钥对生成、CSR文件生成、证书生成、Profile文件签名、Hap包签名等功能。 -> **说明:** 针对无需通过ACL跨级别申请权限的应用,DevEco Studio为开发者提供了自动化签名方案,可以一键完成应用/服务签名。具体可参考[自动化签名方案](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465)。 +> **说明:** +> +> 针对无需通过ACL跨级别申请权限的应用,DevEco Studio为开发者提供了自动化签名方案,可以一键完成应用/服务签名。具体可参考[自动化签名方案](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465)。 ## 基本概念 diff --git a/zh-cn/application-dev/security/huks-guidelines.md b/zh-cn/application-dev/security/huks-guidelines.md index 855b5adcd2140fac53f3e3e9c8adfe698c03bfa8..11f3be25474bc098ad41bff00db3d649544d6e59 100644 --- a/zh-cn/application-dev/security/huks-guidelines.md +++ b/zh-cn/application-dev/security/huks-guidelines.md @@ -92,24 +92,19 @@ async function TestGenKey() { ``` ## 导入外部密钥 + 如果密钥是在HUKS外部生成(比如应用间协商生成、服务器端生成),应用可以将密钥导入到HUKS托管。HUKS支持直接将密钥明文导入到HUKS,但是明文导入会导致密钥暴露在REE内存中,一般适用于轻量级设备或低安业务。对于高安敏感业务,HUKS还提供了安全导入密钥的能力,允许业务自己生成密钥,并通过与处于安全环境中的HUKS建立端到端的加密传输通道,将密钥安全加密导入到HUKS中,确保导入传入过程中密钥不被泄露。 与生成密钥一样,密钥一旦导入到HUKS中,密钥的生命周期明文不出安全环境,同样能保证任何人都无法接触获取到密钥的明文。 - - ### 明文导入 - 导入明文密钥时使用[huks.importKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksimportkeyitem9)方法,传入keyAlias作为密钥别名,传入options,其中必须包含密钥材料和密钥属性集,传入callback用于回调异步结果。关于接口的具体信息,可在[API参考文档](../reference/apis/js-apis-huks.md)中查看。 - 1. 确定密钥别名; 2. 封装密钥材料和密钥属性集:密钥材料须符合[HUKS密钥材料格式](./huks-appendix.md#密钥材料格式)并以Uint8Array形式赋值给[HuksOptions](../reference/apis/js-apis-huks.md#huksoptions)的inData字段;另外,通过[HuksParam](../reference/apis/js-apis-huks.md#huksparam)封装密钥属性,搭配Array组成密钥属性集赋值给properties字段,属性集中必须包含[HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg),[HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize),[HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose)属性; 3. 导入密钥。 - - **代码示例:** ```ts @@ -207,15 +202,10 @@ try { 相比明文导入,加密导入步骤更多,密钥材料更复杂,此章节将展示开发过程中关键的开发流程和密钥材料数据结构。下图是加密导入的基本开发流程。 - - **图2** 加密导入开发流程 ![huks_import_wrapped_key](figures/huks_import_wrapped_key.png) - - - **接口说明** 根据开发流程,在导入加密密钥过程中,需要依次调用HUKS的生成密钥、导出公钥、导入加密密钥、删除密钥接口。 @@ -243,6 +233,7 @@ try { **开发步骤** 这里主要展示涉及调用HUKS的开发样例(使用ECDH密钥协商套件),部分在业务本地执行的步骤不在这里展示详细样例。 + 1. 转换成HUKS格式的密钥材料 2. 生成加密导入用途的密钥 3. 导出公钥材料 @@ -625,7 +616,6 @@ try { } ``` - ## 常见密钥操作 **场景概述** @@ -635,11 +625,13 @@ try { **通用开发流程** HUKS基于密钥会话来操作数据,使用密钥时基于以下流程: + 1. **初始化密钥会话[huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9):** 传入密钥别名和密钥操作参数,初始化一个密钥会话并获取会话句柄。其中密钥操作参数中必须包含对应密码算法所必须的参数,包括密码算法、密钥大小、密钥目的、工作模式、填充模式、散列模式、IV、Nonce、AAD等。如果密钥设置了访问控制属性,还需要其他参数具体[密钥访问控制](#密钥访问控制)。此步骤必选! 2. **分段操作数据[huks.updateSession()](../reference/apis/js-apis-huks.md#huksupdatesession9):** 如数据过大(超过100K)或密码算法的要求需要对数据进行分段操作,反之可跳过此步。此步骤可选! 3. **结束密钥会话[huks.finishSession()](../reference/apis/js-apis-huks.md#huksfinishsession9):** 操作最后一段数据并结束密钥会话,如过程中发生错误或不需要此次密钥操作数据,必须取消会话[huks.abortSession()](../reference/apis/js-apis-huks.md#huksabortsession9)。此步骤必选! ### 加密解密 + ```ts /* * 以下以AES 128密钥的Callback操作使用为例 @@ -1663,6 +1655,7 @@ HUKS提供了全面完善的密钥访问控制能力,确保存储在HUKS中的 生成或导入密钥时,可以指定密钥必须经过用户身份认证后才能使用。您可以指定用于解锁设备锁屏的凭据(锁屏密码、指纹、人脸)的子集进行身份认证。在生成/导入密钥后,即使应用进程被攻击也不会导致未经用户授权的密钥访问,一般用于高敏感且高级别安全保护的场景,比如免密登录、免密支付、自动填充密码保护场景。 除用户身份认证外,应用还须将密钥的授权访问类型(即失效条件)设置为以下两种类型之一: + - **清除锁屏密码后密钥永久无效。** 设置此模式的前提是当前用户已经设置了锁屏密码,在生成/导入密钥后,一旦清除了锁屏密码,此类密钥将永久失效。注意,修改密码不会导致失效情况发生。此模式适合那些需要锁屏密码授权访问或用户强相关的数据保护的场景。 - **用户新录入生物特征后永久无效。** 此模式需要当前用户至少录入了一个生物特征(如指纹)才能生效,在生成/导入密钥后,一旦录入新的生物特征,这些密钥将永久失效。注意,仅删除生物特征不会导致失效情况发生。如果您不希望新录入的生物特征后,用户还可以授权访问原有数据(密钥保护的数据),那么可以使用此模式,如免密登录,免密支付等场景。 @@ -1699,13 +1692,12 @@ HUKS提供了全面完善的密钥访问控制能力,确保存储在HUKS中的 | HUKS_CHALLENGE_TYPE_NONE | 2 | 无挑战值类型,用户认证时不需要挑战值 | > **注意** - > + > > 当指定挑战值类型为**HUKS_CHALLENGE_TYPE_NONE** 时,不需要传递挑战值,但是存在新的限制:在用户身份认证后,一段时间内允许访问该密钥,超时后不能访问,需要重新认证才能访问。因此应用需要额外指定超时时间**HUKS_TAG_AUTH_TIMEOUT**属性(最大60秒)。 - 2. 使用密钥时,先初始化密钥会话,然后根据密钥生成/导入阶段指定的挑战值类型属性是否需要获取挑战值,或组装新的挑战值。 - **表6** 使用密钥的接口介绍 + **表6** 使用密钥的接口介绍 | 接口名 | 描述 | | -------------------------------------- | ----------------------------| @@ -1713,380 +1705,381 @@ HUKS提供了全面完善的密钥访问控制能力,确保存储在HUKS中的 |updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| 分段操作数据,传递认证令牌| |finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| 结束密钥会话,传递认证令牌| - - **开发步骤** 1. 生成密钥并指定指纹访问控制和相关属性 -```ts -import huks from '@ohos.security.huks'; -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let keyAlias = 'dh_key_fingerprint_access'; -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -} -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -// 指定密钥身份认证的类型:指纹 -properties[5] = { - tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, - value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT -} -// 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 -properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, - value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL -} -// 指定挑战值的类型:默认类型 -properties[7] = { - tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, - value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL -} -let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) -} - -/* - * 生成密钥 - */ -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + ```ts + import huks from '@ohos.security.huks'; + + /* + * 确定密钥别名和封装密钥属性参数集 + */ + let keyAlias = 'dh_key_fingerprint_access'; + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + // 指定密钥身份认证的类型:指纹 + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT + } + // 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL + } + // 指定挑战值的类型:默认类型 + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL + } + let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) + } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - let throwObject = {isThrow: false}; - try { - await generateKeyItem(keyAlias, huksOptions, throwObject) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + /* + * 生成密钥 + */ + function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -async function TestGenKeyForFingerprintAccessControl() { - await publicGenKeyFunc(keyAlias, huksOptions); -} -``` + async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } + async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); + } + ``` 2. 初始化密钥会话获取挑战值并发起指纹认证获取认证令牌 -```ts -import huks from '@ohos.security.huks'; -import userIAM_userAuth from '@ohos.userIAM.userAuth'; - -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let srcKeyAlias = 'sm4_key_fingerprint_access'; -let handle; -let challenge; -let fingerAuthToken; -let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; -let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - -/* 集成生成密钥参数集 & 加密参数集 */ -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -} -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) -} - -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - challenge = data.challenge; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + ```ts + import huks from '@ohos.security.huks'; + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + /* + * 确定密钥别名和封装密钥属性参数集 + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let handle; + let challenge; + let fingerAuthToken; + let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + /* 集成生成密钥参数集 & 加密参数集 */ + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) + } -function userIAMAuthFinger(huksChallenge:Uint8Array) { - // 获取认证对象 - let auth; - try { - auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); - console.log("get auth instance success"); - } catch (error) { - console.log("get auth instance failed" + error); - } + function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } - // 订阅认证结果 - try { - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - /* 认证成功获取认证令牌 */ - fingerAuthToken = result.token; - } - }); - console.log("subscribe authentication event success"); - } catch (error) { - console.log("subscribe authentication event failed " + error); - } + async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } - // 开始认证 - try { - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } -} + function userIAMAuthFinger(huksChallenge:Uint8Array) { + // 获取认证对象 + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // 订阅认证结果 + try { + auth.on("result", { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + /* 认证成功获取认证令牌 */ + fingerAuthToken = result.token; + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // 开始认证 + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + } -async function testInitAndAuthFinger() { - /* 初始化密钥会话获取挑战值 */ - await publicInitFunc(srcKeyAlias, huksOptions); - /* 调用userIAM进行身份认证 */ - userIAMAuthFinger(challenge); -} -``` + async function testInitAndAuthFinger() { + /* 初始化密钥会话获取挑战值 */ + await publicInitFunc(srcKeyAlias, huksOptions); + /* 调用userIAM进行身份认证 */ + userIAMAuthFinger(challenge); + } + ``` 3. 传入认证令牌进行数据操作 -```ts -/* - * 以下以SM4 128密钥的Callback操作使用为例 - */ -import huks from '@ohos.security.huks'; - -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let srcKeyAlias = 'sm4_key_fingerprint_access'; -let IV = '1234567890123456'; -let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; -let handle; -let fingerAuthToken; -let updateResult = new Array(); -let finishOutData; -/* 集成生成密钥参数集 & 加密参数集 */ -let propertiesEncrypt = new Array(); -propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, -} -propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), -} -let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) -} - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} + ```ts + /* + * 以下以SM4 128密钥的Callback操作使用为例 + */ + import huks from '@ohos.security.huks'; + + /* + * 确定密钥别名和封装密钥属性参数集 + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let IV = '1234567890123456'; + let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; + let handle; + let fingerAuthToken; + let updateResult = new Array(); + let finishOutData; + + /* 集成生成密钥参数集 & 加密参数集 */ + let propertiesEncrypt = new Array(); + propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, + } + propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), + } + let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) + } -function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); + } -async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - let throwObject = {isThrow: false}; - try { - await updateSession(handle, huksOptions, token, throwObject) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.updateSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; + try { + await updateSession(handle, huksOptions, token, throwObject) + .then ((data) => { + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, token, throwObject) - .then ((data) => { - finishOutData = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -async function testSm4Cipher() { - encryptOptions.inData = StringToUint8Array(cipherInData); - /* 传入认证令牌 */ - await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); - encryptUpdateResult = updateResult; + async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } - encryptOptions.inData = new Uint8Array(new Array()); - /* 传入认证令牌 */ - await publicFinishFunc(handle, fingerAuthToken, encryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } -} -``` + async function testSm4Cipher() { + encryptOptions.inData = StringToUint8Array(cipherInData); + /* 传入认证令牌 */ + await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); + encryptUpdateResult = updateResult; + + encryptOptions.inData = new Uint8Array(new Array()); + /* 传入认证令牌 */ + await publicFinishFunc(handle, fingerAuthToken, encryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish encrypt err '); + } else { + console.info('test finish encrypt success'); + } + } + ``` ### 细粒度用户身份认证访问控制 该功能是基于已有[密钥访问控制](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/huks-guidelines.md#%E5%AF%86%E9%92%A5%E8%AE%BF%E9%97%AE%E6%8E%A7%E5%88%B6)能力的扩展,提供了基于生物特征和锁屏密码二次身份认证的细粒度访问控制能力,允许设置密钥在加密、解密、签名、验签、密钥协商、密钥派生的单个或多个场景时是否需要进行身份验证。比如,业务需要使用HUKS密钥加密保存账号密码信息等数据,要求在加密的时候不进行指纹等身份认证,解密的时候需要进行指纹等身份认证,这是就需要依赖HUKS提供细粒度的二次身份认证访问控制机制。 **开发流程** + 1. 基于用户身份认证访问控制的流程,在密钥生成阶段,通过额外指定用于细粒度用户身份认证访问控制的HuksTag:[HUKS_TAG_KEY_AUTH_PURPOSE](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-huks.md#hukstag)值,来指定在某种算法用途的情况下需要使用用户身份认证访问控制能力。 2. 基于用户身份认证访问控制的流程,在密钥使用阶段,业务无需再次指定HUKS_TAG_KEY_AUTH_PURPOSE值,同用户身份认证访问控制的开发流程。 @@ -2100,6 +2093,7 @@ async function testSm4Cipher() { |HUKS_TAG_KEY_AUTH_PURPOSE| 表示密钥认证用途的tag,用于设置某种算法用途下需要用户身份认证访问控制| **注意** + 1. 当业务未指定用户认证类型[HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9)时表示默认都不需要用户身份认证访问控制能力,则此时设置HUKS_TAG_KEY_AUTH_PURPOSE是默认无效的; 当业务指定了[HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9)时表示需要用户身份认证访问控制能力,此时若不设置HUKS_TAG_KEY_AUTH_PURPOSE值,则生成密钥阶段指定的算法用途在密钥使用时都默认需要进行用户身份认证访问控制。 2. 当指定的算法是对称算法AES和SM4时,且同时指定用于加解密用途,则只允许设置CBC模式,其它模式不支持细粒度用户身份认证访问控制能力。 @@ -2108,425 +2102,429 @@ async function testSm4Cipher() { 示例场景:密钥生成阶段,生成用于加解密的密钥并指定只有解密的时候需要用户身份认证访问控制;密钥使用阶段,加密时不需要用户身份认证访问控制,解密时需要用户身份认证访问控制 1. 生成密钥并指定指纹访问控制和相关属性,以及HUKS_TAG_KEY_AUTH_PURPOSE值 -```ts -import huks from '@ohos.security.huks'; -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let keyAlias = 'dh_key_fingerprint_access'; -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -} -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -// 指定密钥身份认证的类型:指纹 -properties[5] = { - tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, - value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT -} -// 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 -properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, - value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL -} -// 指定挑战值的类型:默认类型 -properties[7] = { - tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, - value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL -} -// 指定某种算法用途时需要用户身份认证访问控制:比如解密需要 -properties[8] = { - tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -} -let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) -} + ```ts + import huks from '@ohos.security.huks'; + + /* + * 确定密钥别名和封装密钥属性参数集 + */ + let keyAlias = 'dh_key_fingerprint_access'; + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + // 指定密钥身份认证的类型:指纹 + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT + } + // 指定密钥安全授权的类型(失效类型):新录入生物特征(指纹)后无效 + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL + } + // 指定挑战值的类型:默认类型 + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL + } + // 指定某种算法用途时需要用户身份认证访问控制:比如解密需要 + properties[8] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + } + let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) + } -/* - * 生成密钥 - */ -async function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + /* + * 生成密钥 + */ + async function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - let throwObject = {isThrow: false}; - try { - await generateKeyItem(keyAlias, huksOptions, throwObject) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -async function TestGenKeyForFingerprintAccessControl() { - await publicGenKeyFunc(keyAlias, huksOptions); -} -``` + async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); + } + ``` 2. 使用密钥-加密场景-加密时不需要进行用户身份认证访问控制 -```ts -import huks from '@ohos.security.huks'; - -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let srcKeyAlias = 'sm4_key_fingerprint_access'; -let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; // 明文数据 -let IV = '1234567890123456'; -let handle; -let cipherText; // 加密后的密文数据 -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} + ```ts + import huks from '@ohos.security.huks'; + + /* + * 确定密钥别名和封装密钥属性参数集 + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; // 明文数据 + let IV = '1234567890123456'; + let handle; + let cipherText; // 加密后的密文数据 + + function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); + } -/* 集成生成密钥参数集 & 加密参数集 */ -let propertiesEncrypt = new Array(); -propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, -} -propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), -} -let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) -} + /* 集成生成密钥参数集 & 加密参数集 */ + let propertiesEncrypt = new Array(); + propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, + } + propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), + } + let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) + } -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, throwObject) - .then ((data) => { - cipherText = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, throwObject) + .then ((data) => { + cipherText = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -async function testSm4Cipher() { - /* 初始化密钥会话获取挑战值 */ - await publicInitFunc(srcKeyAlias, encryptOptions); + async function testSm4Cipher() { + /* 初始化密钥会话获取挑战值 */ + await publicInitFunc(srcKeyAlias, encryptOptions); - /* 加密 */ - encryptOptions.inData = StringToUint8Array(cipherInData); - await publicFinishFunc(handle, encryptOptions); -} -``` + /* 加密 */ + encryptOptions.inData = StringToUint8Array(cipherInData); + await publicFinishFunc(handle, encryptOptions); + } + ``` 3. 使用密钥-解密场景-解密时需要进行用户身份认证访问控制 -```ts -import huks from '@ohos.security.huks'; -import userIAM_userAuth from '@ohos.userIAM.userAuth'; - -/* - * 确定密钥别名和封装密钥属性参数集 - */ -let srcKeyAlias = 'sm4_key_fingerprint_access'; -let cipherText = 'r56ywtTJUQC6JFJ2VV2kZw=='; // 加密时得到的密文数据, 业务需根据实际加密结果修改 -let IV = '1234567890123456'; -let handle; -let finishOutData; // 解密后的明文数据 -let fingerAuthToken; -let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; -let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} - -/* 集成生成密钥参数集 & 加密参数集 */ -let propertiesDecrypt = new Array(); -propertiesDecrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, -} -propertiesDecrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, -} -propertiesDecrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, -} -propertiesDecrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, -} -propertiesDecrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, -} -propertiesDecrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), -} -let decryptOptions = { - properties: propertiesDecrypt, - inData: new Uint8Array(new Array()) -} -function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + ```ts + import huks from '@ohos.security.huks'; + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + /* + * 确定密钥别名和封装密钥属性参数集 + */ + let srcKeyAlias = 'sm4_key_fingerprint_access'; + let cipherText = 'r56ywtTJUQC6JFJ2VV2kZw=='; // 加密时得到的密文数据, 业务需根据实际加密结果修改 + let IV = '1234567890123456'; + let handle; + let finishOutData; // 解密后的明文数据 + let fingerAuthToken; + let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); + } -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - let throwObject = {isThrow: false}; - try { - await initSession(keyAlias, huksOptions, throwObject) - .then ((data) => { - console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - challenge = data.challenge; - }) - .catch((error) => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + /* 集成生成密钥参数集 & 加密参数集 */ + let propertiesDecrypt = new Array(); + propertiesDecrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, + } + propertiesDecrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, + } + propertiesDecrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, + } + propertiesDecrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, + } + propertiesDecrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, + } + propertiesDecrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), + } + let decryptOptions = { + properties: propertiesDecrypt, + inData: new Uint8Array(new Array()) + } -function userIAMAuthFinger(huksChallenge:Uint8Array) { - // 获取认证对象 - let auth; - try { - auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); - console.log("get auth instance success"); - } catch (error) { - console.log("get auth instance failed" + error); - } + function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } - // 订阅认证结果 - try { - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - /* 认证成功获取认证令牌 */ - fingerAuthToken = result.token; - } - }); - console.log("subscribe authentication event success"); - } catch (error) { - console.log("subscribe authentication event failed " + error); - } + async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } - // 开始认证 - try { - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } -} + function userIAMAuthFinger(huksChallenge:Uint8Array) { + // 获取认证对象 + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // 订阅认证结果 + try { + auth.on("result", { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + /* 认证成功获取认证令牌 */ + fingerAuthToken = result.token; + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // 开始认证 + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + } -function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, token, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throwObject.isThrow = true; - throw(error); - } - }); -} + function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); + } -async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - let throwObject = {isThrow: false}; - try { - await finishSession(handle, huksOptions, token, throwObject) - .then ((data) => { - finishOutData = data.outData; - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - if (throwObject.isThrow) { - throw(error); - } else { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - } - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} + async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } + } -async function testSm4Cipher() { - /* 初始化密钥会话获取挑战值 */ - await publicInitFunc(srcKeyAlias, decryptOptions); + async function testSm4Cipher() { + /* 初始化密钥会话获取挑战值 */ + await publicInitFunc(srcKeyAlias, decryptOptions); - /* 调用userIAM进行身份认证 */ - userIAMAuthFinger(challenge); + /* 调用userIAM进行身份认证 */ + userIAMAuthFinger(challenge); - /* 认证成功后进行解密, 需要传入Auth获取到的authToken值 */ - decryptOptions.inData = StringToUint8Array(cipherText); - await publicFinishFunc(handle, fingerAuthToken, decryptOptions); -} -``` + /* 认证成功后进行解密, 需要传入Auth获取到的authToken值 */ + decryptOptions.inData = StringToUint8Array(cipherText); + await publicFinishFunc(handle, fingerAuthToken, decryptOptions); + } + ``` ## 密钥证明 HUKS为密钥提供合法性证明能力,主要应用于非对称密钥的公钥的证明。基于PKI证书链技术,HUKS可以为存储在HUKS中的非对称密钥对的公钥签发证书,证明其公钥的合法性。业务可以通过OpenHarmony提供的根CA证书,逐级验证HUKS签发的密钥证明证书,来确保证书中的公钥以及对应的私钥,确实来自合法的硬件设备,且存储管理在HUKS中。 **开发流程** + 1. 指定密钥别名和需要证明的密钥属性的标签传入HUKS。 2. 调用HUKS为应用生成一个依次由根CA证书、设备CA证书、设备证书、密钥证书组成的X.509证书链。 3. 将证书链传输至受信任的服务器,并在服务器上解析和验证证书链的有效性和单个证书是否吊销。 @@ -2708,7 +2706,7 @@ async function AttestKeyTest() { } ``` -> 常见问题 +**常见问题** 1. Cannot find name 'huks'. diff --git a/zh-cn/application-dev/ui/arkts-page-transition-animation.md b/zh-cn/application-dev/ui/arkts-page-transition-animation.md index 31b996ce9952b8fea4ebdfecf53320bdca18e9ba..9a717c81e48803c5afa7a2b72813234dfee6c324 100644 --- a/zh-cn/application-dev/ui/arkts-page-transition-animation.md +++ b/zh-cn/application-dev/ui/arkts-page-transition-animation.md @@ -34,7 +34,7 @@ type为RouteType.None表示对页面栈的push、pop操作均生效,type的默 ```ts -// page A +// pageA pageTransition() { // 定义页面进入时的效果,从左侧滑入,时长为1200ms,无论页面栈发生push还是pop操作均可生效 PageTransitionEnter({ type: RouteType.None, duration: 1200 }) @@ -48,7 +48,7 @@ pageTransition() { ```ts -// page B +// pageB pageTransition() { // 定义页面进入时的效果,从右侧滑入,时长为1000ms,无论页面栈发生push还是pop操作均可生效 PageTransitionEnter({ type: RouteType.None, duration: 1000 }) @@ -80,7 +80,7 @@ type为RouteType.Push表示仅对页面栈的push操作生效,type为RouteType ```ts -// page A +// pageA pageTransition() { // 定义页面进入时的效果,从右侧滑入,时长为1200ms,页面栈发生push操作时该效果才生效 PageTransitionEnter({ type: RouteType.Push, duration: 1200 }) @@ -100,7 +100,7 @@ pageTransition() { ```ts -// page B +// pageB pageTransition() { // 定义页面进入时的效果,从右侧滑入,时长为1000ms,页面栈发生push操作时该效果才生效 PageTransitionEnter({ type: RouteType.Push, duration: 1000 }) @@ -157,7 +157,7 @@ pageTransition() { ```ts -// page A +// PageTransitionSrc1 import router from '@ohos.router'; @Entry @Component @@ -175,7 +175,7 @@ struct PageTransitionSrc1 { Button("pushUrl") .onClick(() => { // 路由到下一个页面,push操作 - router.pushUrl({ url: 'pages/myTest/pageTransitionDst1' }); + router.pushUrl({ url: 'pages/myTest/PageTransitionDst1' }); }) Button("back") .onClick(() => { @@ -209,7 +209,7 @@ struct PageTransitionSrc1 { ```ts -// page B +// PageTransitionDst1 import router from '@ohos.router'; @Entry @Component @@ -227,7 +227,7 @@ struct PageTransitionDst1 { Button("pushUrl") .onClick(() => { // 路由到下一页面,push操作 - router.pushUrl({ url: 'pages/myTest/pageTransitionSrc1' }); + router.pushUrl({ url: 'pages/myTest/PageTransitionSrc1' }); }) Button("back") .onClick(() => { @@ -267,7 +267,7 @@ struct PageTransitionDst1 { ```ts -// page A +// PageTransitionSrc2 import router from '@ohos.router'; @Entry @Component @@ -313,7 +313,7 @@ struct PageTransitionSrc2 { ```ts -// page B +// PageTransitionDst2 import router from '@ohos.router'; @Entry @Component diff --git a/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md b/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md index 1431af7662a57ee4f796a40a459b7f67279965e6..08231b5832981c9db33a280b026f7fd1279cf79f 100644 --- a/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md +++ b/zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md @@ -28,7 +28,7 @@ Button('click for Menu') ## 创建自定义样式的菜单 -当默认样式不满足开发需求时,可使用\@CustomBuilder自定义菜单内容。可通过bindContextMenu接口进行菜单的自定义。 +当默认样式不满足开发需求时,可使用\@CustomBuilder自定义菜单内容。可通过bindMenu接口进行菜单的自定义。 ### \@Builder开发菜单内的内容 @@ -70,7 +70,7 @@ MyMenu(){ startIcon: $r("app.media.view_list_filled"), content: "菜单选项", endIcon: $r("app.media.arrow_right_filled"), - builder: this.SubMenu.bind(this)\ + builder: this.SubMenu.bind(this) }) } MenuItem({ @@ -101,7 +101,7 @@ Button('click for Menu') 通过bindContextMenu接口进行菜单的自定义及菜单弹出的触发方式:右键或长按。使用bindContextMenu弹出的菜单项是在独立子窗口内的,可显示在应用窗口外部。 -- [@Builder开发菜单内的内容](#builder开发菜单内的内容)与上文写法相同。 +- @Builder开发菜单内的内容与上文写法相同。 - 确认菜单的弹出方式,使用bindContextMenu属性绑定组件。示例中为右键弹出菜单。 diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index 663e2086e3eeeca904c0a369b620b03b0db0c877..27749d259f90bc6a06a82b77e7eef2a4cc22de94 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -553,7 +553,7 @@ - [分布式文件系统概述](file-management/distributed-fs-overview.md) - [设置分布式文件数据等级](file-management/set-security-label.md) - [跨设备文件访问](file-management/file-access-across-devices.md) - - 任务管理 + - 后台任务(Background Task)管理 - 后台任务 - [后台任务概述](task-management/background-task-overview.md) - [短时任务开发指导](task-management/transient-task-dev-guide.md) @@ -1242,6 +1242,9 @@ - [@ohos.multimedia.camera (相机管理)](reference/apis/js-apis-camera.md) - [@ohos.multimedia.image (图片处理)](reference/apis/js-apis-image.md) - [@ohos.multimedia.media (媒体服务)](reference/apis/js-apis-media.md) + - [@ohos.multimedia.systemSoundManager (系统声音管理)](reference/apis/js-apis-systemSoundManager.md) + - multimedia + - [ringtonePlayer (铃声播放器)](reference/apis/js-apis-inner-multimedia-ringtonePlayer.md) - 资源管理 - [@ohos.i18n (国际化-I18n)](reference/apis/js-apis-i18n.md) - [@ohos.intl (国际化-Intl)](reference/apis/js-apis-intl.md) @@ -1274,7 +1277,8 @@ - [@ohos.data.distributedDataObject (分布式数据对象)](reference/apis/js-apis-data-distributedobject.md) - [@ohos.data.distributedKVStore (分布式键值数据库)](reference/apis/js-apis-distributedKVStore.md) - [@ohos.data.preferences (用户首选项)](reference/apis/js-apis-data-preferences.md) - - [@ohos.data.relationalStore (关系型数据库)](reference/apis/js-apis-data-relationalStore.md) + - [@ohos.data.relationalStore (关系型数据库)](reference/apis/js-apis-data-relationalStore.md) + - [@ohos.data.UDMF (统一数据管理框架)](reference/apis/js-apis-data-udmf.md) - [@ohos.data.ValuesBucket (数据集)](reference/apis/js-apis-data-valuesBucket.md) - 文件管理 - [@ohos.file.backup (备份恢复)](reference/apis/js-apis-file-backup.md) diff --git a/zh-cn/device-dev/driver/driver-peripherals-face_auth-des.md b/zh-cn/device-dev/driver/driver-peripherals-face_auth-des.md index 48ffbf0f5263bd9d898e07ec03a5f096778628ec..a876de316424a4a0fcf639019b7010deab93c0ac 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-face_auth-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-face_auth-des.md @@ -90,7 +90,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 ### 接口说明 -注:以下接口列举的为IDL接口描述生成的对应C++语言函数接口,接口声明见idl文件(/drivers/interface/face_auth/v1_0/)。 +注:以下接口列举的为IDL接口描述生成的对应C++语言函数接口,接口声明见idl文件(/drivers/interface/face_auth)。 在本文中,人脸凭据的录入、认证、识别和删除相关的HDI接口如表1所示,表2中的回调函数分别用于人脸执行器返回操作结果给框架和返回操作过程中的提示信息给上层应用。 @@ -98,23 +98,29 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 | 接口名称 | 功能介绍 | | ----------------------------------- | ---------------------------------- | -| GetExecutorList(std::vector>& executorList) | 获取执行器列表。 | +| GetExecutorList(std::vector\>& executorList) | 获取V1_0版本执行器列表。 | +| GetExecutorListV1_1(std::vector\>& executorList) | 获取V1_1版本执行器列表。 | | GetExecutorInfo(ExecutorInfo& info) | 获取执行器信息,包括执行器类型、执行器角色、认证类型、安全等级、执行器公钥等信息,用于向用户认证框架注册执行器。 | | GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | 获取指定人脸模板ID的模板信息。 | -| OnRegisterFinish(const std::vector& templateIdList,
const std::vector& frameworkPublicKey, const std::vector& extraInfo) | 执行器注册成功后,获取用户认证框架的公钥信息;获取用户认证框架的人脸模板列表用于对账。 | -| Enroll(uint64_t scheduleId, const std::vector& extraInfo,
const sptr& callbackObj) | 录入人脸模板。 | -| Authenticate(uint64_t scheduleId, const std::vector& templateIdList,
const std::vector& extraInfo, const sptr& callbackObj) | 认证人脸模板。 | -| Identify(uint64_t scheduleId, const std::vector& extraInfo,
const sptr& callbackObj) | 识别人脸模板。 | -| Delete(const std::vector& templateIdList) | 删除人脸模板。 | +| OnRegisterFinish(const std::vector\& templateIdList,
const std::vector\& frameworkPublicKey, const std::vector\& extraInfo) | 执行器注册成功后,获取用户认证框架的公钥信息;获取用户认证框架的人脸模板列表用于对账。 | +| Enroll(uint64_t scheduleId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 录入人脸模板。 | +| Authenticate(uint64_t scheduleId, const std::vector\& templateIdList,
const std::vector\& extraInfo, const sptr\& callbackObj) | 认证人脸模板。 | +| Identify(uint64_t scheduleId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 识别人脸模板。 | +| Delete(const std::vector\& templateIdList) | 删除人脸模板。 | | Cancel(uint64_t scheduleId) | 通过scheduleId取消指定录入、认证、识别操作。 | -| SendCommand(int32_t commandId, const std::vector& extraInfo,
const sptr& callbackObj) | 人脸认证服务向Face_auth驱动传递参数的通用接口。 | +| SendCommand(int32_t commandId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 人脸认证服务向Face_auth驱动传递参数的通用接口。 | +| SetBufferProducer(const sptr\ &bufferProducer) | 设置预览流缓冲区。 | +| GetProperty(const std::vector\& templateIdList,
const std::vector\& propertyTypes, Property& property) | 获取执行器属性信息。 | +| SetCachedTemplates(const std::vector\ &templateIdList) | 设置需缓存模板列表。 | +| RegisterSaCommandCallback(const sptr\ &callbackObj) | 注册SA命令回调。 | **表2** 回调函数介绍 | 接口名称 | 功能介绍 | | ------------------------------------------------------------ | ------------------------ | -| IExecutorCallback::OnResult(int32_t code, const std::vector& extraInfo) | 返回操作的最终结果。 | -| IExecutorCallback::OnTip(int32_t code, const std::vector& extraInfo) | 返回操作的过程交互信息。 | +| IExecutorCallback::OnResult(int32_t code, const std::vector\& extraInfo) | 返回操作的最终结果。 | +| IExecutorCallback::OnTip(int32_t code, const std::vector\& extraInfo) | 返回操作的过程交互信息。 | +| ISaCommandCallback::OnSaCommands(const std::vector\& commands) | 发送命令列表。 | ### 开发步骤 @@ -143,7 +149,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 struct IDeviceIoService ioService; OHOS::sptr stub; }; - + // 服务接口调用响应接口 static int32_t FaceAuthInterfaceDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) @@ -151,11 +157,11 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGI("start"); auto *hdfFaceAuthInterfaceHost = CONTAINER_OF(client->device->service, struct HdfFaceAuthInterfaceHost, ioService); - + OHOS::MessageParcel *dataParcel = nullptr; OHOS::MessageParcel *replyParcel = nullptr; OHOS::MessageOption option; - + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { IAM_LOGE("%{public}s:invalid data sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; @@ -164,10 +170,10 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGE("%{public}s:invalid reply sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; } - + return hdfFaceAuthInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); } - + // 初始化接口 int HdfFaceAuthInterfaceDriverInit(struct HdfDeviceObject *deviceObject) { @@ -178,7 +184,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 } return HDF_SUCCESS; } - + // Face_auth驱动对外提供的服务绑定到HDF框架 int HdfFaceAuthInterfaceDriverBind(struct HdfDeviceObject *deviceObject) { @@ -188,29 +194,29 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGE("%{public}s: failed to create HdfFaceAuthInterfaceHost object", __func__); return HDF_FAILURE; } - + hdfFaceAuthInterfaceHost->ioService.Dispatch = FaceAuthInterfaceDriverDispatch; hdfFaceAuthInterfaceHost->ioService.Open = NULL; hdfFaceAuthInterfaceHost->ioService.Release = NULL; - + auto serviceImpl = IFaceAuthInterface::Get(true); if (serviceImpl == nullptr) { IAM_LOGE("%{public}s: failed to implement service", __func__); return HDF_FAILURE; } - + hdfFaceAuthInterfaceHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, IFaceAuthInterface::GetDescriptor()); if (hdfFaceAuthInterfaceHost->stub == nullptr) { IAM_LOGE("%{public}s: failed to get stub object", __func__); return HDF_FAILURE; } - + deviceObject->service = &hdfFaceAuthInterfaceHost->ioService; IAM_LOGI("success"); return HDF_SUCCESS; } - + // 释放Face_auth驱动中的资源 void HdfFaceAuthInterfaceDriverRelease(struct HdfDeviceObject *deviceObject) { @@ -220,7 +226,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 delete hdfFaceAuthInterfaceHost; IAM_LOGI("success"); } - + // 注册Face_auth驱动入口数据结构体对象 struct HdfDriverEntry g_faceAuthInterfaceDriverEntry = { .moduleVersion = 1, @@ -229,7 +235,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 .Init = HdfFaceAuthInterfaceDriverInit, .Release = HdfFaceAuthInterfaceDriverRelease, }; - + // 调用HDF_INIT将驱动入口注册到HDF框架中。在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出 HDF_INIT(g_faceAuthInterfaceDriverEntry); ``` @@ -238,19 +244,19 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 ```c++ // 执行器实现类 - class ExecutorImpl : public IExecutor { + class ExecutorImpl : public V1_1::IExecutor { public: ExecutorImpl(struct ExecutorInfo executorInfo); virtual ~ExecutorImpl() {} - + private: struct ExecutorInfo executorInfo_; // 执行器信息 }; - + static constexpr uint16_t SENSOR_ID = 123; // 执行器sensorID static constexpr uint32_t EXECUTOR_TYPE = 123; // 执行器类型 static constexpr size_t PUBLIC_KEY_LEN = 32; // 执行器32字节公钥 - + // 创建HDI服务对象 extern "C" IFaceAuthInterface *FaceAuthInterfaceImplGetInstance(void) { @@ -261,9 +267,9 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 } return faceAuthInterfaceService; } - + // 获取执行器列表实现,创建执行器 - int32_t GetExecutorList(std::vector>& executorList) + int32_t GetExecutorListV1_1(std::vector>& executorList) { IAM_LOGI("interface mock start"); executorList.clear(); @@ -281,10 +287,21 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGE("executor is nullptr"); return HDF_FAILURE; } - executorList.push_back(sptr(executor)); + executorList.push_back(sptr(executor)); IAM_LOGI("interface mock success"); return HDF_SUCCESS; } + + // 获取V1_0执行器列表实现,使用V1_1版本执行器实现V1_0版本执行器的功能 + int32_t GetExecutorList(std::vector> &executorList) + { + std::vector> executorListV1_1; + int32_t result = GetExecutorListV1_1(executorListV1_1); + for (auto &executor : executorListV1_1) { + executorList.push_back(executor); + } + return result; + } ``` 3. 实现执行器每个功能接口,详细代码参见[executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/face_auth/hdi_service/src/executor_impl.cpp)文件。 @@ -298,7 +315,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGI("get executor information success"); return HDF_SUCCESS; } - + // 实现获取指定模板ID的模板信息接口 int32_t GetTemplateInfo(uint64_t templateId, TemplateInfo& info) { @@ -308,7 +325,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGI("get template information success"); return HDF_SUCCESS; } - + // 实现执行器注册成功后,获取用户认证框架的公钥信息、获取用户认证框架的模板列表接口。将公钥信息保持,模板列表用于和本地的模板做对账 int32_t OnRegisterFinish(const std::vector& templateIdList, const std::vector& frameworkPublicKey, const std::vector& extraInfo) @@ -320,7 +337,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGI("register finish"); return HDF_SUCCESS; } - + // 实现人脸录入接口 int32_t Enroll(uint64_t scheduleId, const std::vector& extraInfo, const sptr& callbackObj) @@ -336,7 +353,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 } return HDF_SUCCESS; } - + // 实现人脸认证接口 int32_t Authenticate(uint64_t scheduleId, const std::vector& templateIdList, const std::vector& extraInfo, const sptr& callbackObj) @@ -353,7 +370,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 } return HDF_SUCCESS; } - + // 实现人脸识别接口 int32_t Identify(uint64_t scheduleId, const std::vector& extraInfo, const sptr& callbackObj) @@ -369,7 +386,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 } return HDF_SUCCESS; } - + // 实现删除人脸模板接口 int32_t Delete(const std::vector& templateIdList) { @@ -378,7 +395,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGI("delete success"); return HDF_SUCCESS; } - + // 实现通过scheduleId取消指定操作接口 int32_t Cancel(uint64_t scheduleId) { @@ -387,7 +404,7 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 IAM_LOGI("cancel success"); return HDF_SUCCESS; } - + // 实现人脸认证服务向Face_auth驱动传递参数的通用接口,当前需要实现冻结与解锁模板命令 int32_t SendCommand(int32_t commandId, const std::vector& extraInfo, const sptr& callbackObj) @@ -422,8 +439,42 @@ Face_auth驱动的主要工作是为上层用户认证框架和Face_auth服务 } return HDF_SUCCESS; } + + // 实现设置预览流缓冲区接口 + int32_t ExecutorImpl::SetBufferProducer(const sptr &bufferProducer) + { + IAM_LOGI("interface mock start set buffer producer %{public}s", + UserIam::Common::GetPointerNullStateString(bufferProducer.GetRefPtr()).c_str()); + return HDF_SUCCESS; + } + + // 实现获取执行器属性接口 + int32_t ExecutorImpl::GetProperty( + const std::vector &templateIdList, const std::vector &propertyTypes, Property &property) + { + IAM_LOGI("interface mock start"); + property = {}; + IAM_LOGI("get property success"); + return HDF_SUCCESS; + } + + // 实现设置需缓存模板列表接口 + int32_t ExecutorImpl::SetCachedTemplates(const std::vector &templateIdList) + { + IAM_LOGI("interface mock start"); + IAM_LOGI("set cached templates success"); + return HDF_SUCCESS; + } + + // 实现注册SA命令回调接口 + int32_t ExecutorImpl::RegisterSaCommandCallback(const sptr &callbackObj) + { + IAM_LOGI("interface mock start"); + IAM_LOGI("register sa command callback success"); + return HDF_SUCCESS; + } ``` - + 4. 用户身份认证框架支持多driver,当增加driver或者修改driver信息,需要修改如下文件中serviceName2Config。 ```c++ diff --git a/zh-cn/device-dev/driver/driver-peripherals-fingerprint_auth-des.md b/zh-cn/device-dev/driver/driver-peripherals-fingerprint_auth-des.md index 0f593ed75d8056df216db4837681c86934b2e7a9..4d9def9e5e89cb19804a6eff52fc7bc1dce6b400 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-fingerprint_auth-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-fingerprint_auth-des.md @@ -95,23 +95,27 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin | 接口名称 | 功能介绍 | | -------------------------------- | ----------------------------------- | -| GetExecutorList(std::vector>& executorList) | 获取执行器列表。 | +| GetExecutorList(std::vector\>& executorList) | 获取V1_0版本执行器列表。 | +| GetExecutorListV1_1(std::vector\>& executorList) | 获取V1_1版本执行器列表。 | | GetExecutorInfo(ExecutorInfo& info) | 获取执行器信息,包括执行器类型、执行器角色、认证类型、安全等级、执行器公钥等信息,用于向用户认证框架注册执行器。 | | GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | 获取指定模板ID的模板信息。 | -| OnRegisterFinish(const std::vector& templateIdList,
const std::vector& frameworkPublicKey, const std::vector& extraInfo) | 执行器注册成功后,获取用户认证框架的公钥信息;获取用户认证框架的模板列表用于对账。 | -| Enroll(uint64_t scheduleId, const std::vector& extraInfo,
const sptr& callbackObj) | 录入指纹模板。 | -| Authenticate(uint64_t scheduleId, const std::vector& templateIdList,
const std::vector& extraInfo, const sptr& callbackObj) | 认证指纹模板。 | -| Identify(uint64_t scheduleId, const std::vector& extraInfo,
const sptr& callbackObj) | 识别指纹模板。 | -| Delete(const std::vector& templateIdList) | 删除指纹模板。 | +| OnRegisterFinish(const std::vector\& templateIdList,
const std::vector\& frameworkPublicKey, const std::vector\& extraInfo) | 执行器注册成功后,获取用户认证框架的公钥信息;获取用户认证框架的模板列表用于对账。 | +| Enroll(uint64_t scheduleId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 录入指纹模板。 | +| Authenticate(uint64_t scheduleId, const std::vector\& templateIdList,
const std::vector\& extraInfo, const sptr\& callbackObj) | 认证指纹模板。 | +| Identify(uint64_t scheduleId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 识别指纹模板。 | +| Delete(const std::vector\& templateIdList) | 删除指纹模板。 | | Cancel(uint64_t scheduleId) | 通过scheduleId取消指定录入、认证、识别操作。 | -| SendCommand(int32_t commandId, const std::vector& extraInfo,
const sptr& callbackObj) | 指纹认证服务向Fingerprint_auth驱动传递参数的通用接口。 | - +| SendCommand(int32_t commandId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 指纹认证服务向Fingerprint_auth驱动传递参数的通用接口。 | +| GetProperty(const std::vector\& templateIdList,
const std::vector\& propertyTypes, Property& property) | 获取执行器属性信息。 | +| SetCachedTemplates(const std::vector\ &templateIdList) | 设置需缓存模板列表。 | +| RegisterSaCommandCallback(const sptr\ &callbackObj) | 注册SA命令回调。 | **表2** 回调函数介绍 | 接口名称 | 功能介绍 | | ------------------------------------------------------------ | ------------------------ | -| IExecutorCallback::OnResult(int32_t code, const std::vector& extraInfo) | 返回操作的最终结果。 | -| IExecutorCallback::OnTip(int32_t code, const std::vector& extraInfo) | 返回操作的过程交互信息。 | +| IExecutorCallback::OnResult(int32_t code, const std::vector\& extraInfo) | 返回操作的最终结果。 | +| IExecutorCallback::OnTip(int32_t code, const std::vector\& extraInfo) | 返回操作的过程交互信息。 | +| ISaCommandCallback::OnSaCommands(const std::vector\& commands) | 发送命令列表。 | ### 开发步骤 @@ -140,7 +144,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin struct IDeviceIoService ioService; OHOS::sptr stub; }; - + // 服务接口调用响应接口 static int32_t FingerprintAuthInterfaceDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) @@ -148,11 +152,11 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGI("start"); auto *hdfFingerprintAuthInterfaceHost = CONTAINER_OF(client->device->service, struct HdfFingerprintAuthInterfaceHost, ioService); - + OHOS::MessageParcel *dataParcel = nullptr; OHOS::MessageParcel *replyParcel = nullptr; OHOS::MessageOption option; - + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { IAM_LOGE("%{public}s:invalid data sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; @@ -161,10 +165,10 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGE("%{public}s:invalid reply sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; } - + return hdfFingerprintAuthInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); } - + // 初始化接口 int HdfFingerprintAuthInterfaceDriverInit(struct HdfDeviceObject *deviceObject) { @@ -175,7 +179,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin } return HDF_SUCCESS; } - + // Fingerprint_auth驱动对外提供的服务绑定到HDF框架 int HdfFingerprintAuthInterfaceDriverBind(struct HdfDeviceObject *deviceObject) { @@ -185,29 +189,29 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGE("%{public}s: failed to create HdfFaceAuthInterfaceHost object", __func__); return HDF_FAILURE; } - + hdfFingerprintAuthInterfaceHost->ioService.Dispatch = FingerprintAuthInterfaceDriverDispatch; hdfFingerprintAuthInterfaceHost->ioService.Open = NULL; hdfFingerprintAuthInterfaceHost->ioService.Release = NULL; - + auto serviceImpl = IFingerprintAuthInterface::Get(true); if (serviceImpl == nullptr) { IAM_LOGE("%{public}s: failed to implement service", __func__); return HDF_FAILURE; } - + hdfFingerprintAuthInterfaceHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, IFaceAuthInterface::GetDescriptor()); if (hdfFingerprintAuthInterfaceHost->stub == nullptr) { IAM_LOGE("%{public}s: failed to get stub object", __func__); return HDF_FAILURE; } - + deviceObject->service = &hdfFingerprintAuthInterfaceHost->ioService; IAM_LOGI("success"); return HDF_SUCCESS; } - + // 释放Fingerprint_auth驱动中的资源 void HdfFingerprintAuthInterfaceDriverRelease(struct HdfDeviceObject *deviceObject) { @@ -217,7 +221,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin delete hdfFaceAuthInterfaceHost; IAM_LOGI("success"); } - + // 注册Fingerprint_auth驱动入口数据结构体对象 struct HdfDriverEntry g_fingerprintAuthInterfaceDriverEntry = { .moduleVersion = 1, @@ -226,7 +230,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin .Init = HdfFingerprintAuthInterfaceDriverInit, .Release = HdfFingerprintAuthInterfaceDriverRelease, }; - + // 调用HDF_INIT将驱动入口注册到HDF框架中。在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出 HDF_INIT(g_fingerprintAuthInterfaceDriverEntry); ``` @@ -239,15 +243,15 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin public: ExecutorImpl(struct ExecutorInfo executorInfo); virtual ~ExecutorImpl() {} - + private: struct ExecutorInfo executorInfo_; // 执行器信息 }; - + static constexpr uint16_t SENSOR_ID = 123; // 执行器sensorID static constexpr uint32_t EXECUTOR_TYPE = 123; // 执行器类型 static constexpr size_t PUBLIC_KEY_LEN = 32; // 执行器32字节公钥 - + // 创建HDI服务对象 extern "C" IFaceAuthInterface *FingerprintAuthInterfaceImplGetInstance(void) { @@ -258,9 +262,9 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin } return fingerprintAuthInterfaceService; } - + // 获取执行器列表实现,创建执行器 - int32_t GetExecutorList(std::vector>& executorList) + int32_t GetExecutorListV1_1(std::vector>& executorList) { IAM_LOGI("interface mock start"); executorList.clear(); @@ -278,10 +282,21 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGE("executor is nullptr"); return HDF_FAILURE; } - executorList.push_back(sptr(executor)); + executorList.push_back(sptr(executor)); IAM_LOGI("interface mock success"); return HDF_SUCCESS; } + + // 获取V1_0执行器列表实现,使用V1_1版本执行器实现V1_0版本执行器的功能 + int32_t GetExecutorList(std::vector> &executorList) + { + std::vector> executorListV1_1; + int32_t result = GetExecutorListV1_1(executorListV1_1); + for (auto &executor : executorListV1_1) { + executorList.push_back(executor); + } + return result; + } ``` 3. 步骤1、2完成后基本实现了Fingerprint_auth驱动和Fingerprint_auth服务对接。接下来需实现执行器每个功能接口,来完成指纹认证基础能力。关键代码如下,详细代码请参见[executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/fingerprint_auth/hdi_service/src/executor_impl.cpp)文件。 @@ -295,7 +310,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGI("get executor information success"); return HDF_SUCCESS; } - + // 实现获取指定模板ID的模板信息接口 int32_t GetTemplateInfo(uint64_t templateId, TemplateInfo& info) { @@ -305,7 +320,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGI("get template information success"); return HDF_SUCCESS; } - + // 实现执行器注册成功后,获取用户认证框架的公钥信息、获取用户认证框架的模板列表接口。将公钥信息保持,模板列表用于和本地的模板做对账 int32_t OnRegisterFinish(const std::vector& templateIdList, const std::vector& frameworkPublicKey, const std::vector& extraInfo) @@ -317,7 +332,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGI("register finish"); return HDF_SUCCESS; } - + // 实现指纹录入接口 int32_t Enroll(uint64_t scheduleId, const std::vector& extraInfo, const sptr& callbackObj) @@ -333,7 +348,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin } return HDF_SUCCESS; } - + // 实现指纹认证接口 int32_t Authenticate(uint64_t scheduleId, const std::vector& templateIdList, const std::vector& extraInfo, const sptr& callbackObj) @@ -350,7 +365,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin } return HDF_SUCCESS; } - + // 实现指纹识别接口 int32_t Identify(uint64_t scheduleId, const std::vector& extraInfo, const sptr& callbackObj) @@ -366,7 +381,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin } return HDF_SUCCESS; } - + // 实现删除指纹模板接口 int32_t Delete(const std::vector& templateIdList) { @@ -375,7 +390,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGI("delete success"); return HDF_SUCCESS; } - + // 实现通过scheduleId取消指定操作接口 int32_t Cancel(uint64_t scheduleId) { @@ -384,7 +399,7 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin IAM_LOGI("cancel success"); return HDF_SUCCESS; } - + // 实现指纹认证服务向Fingerprint_auth驱动传递参数的通用接口,当前需要实现冻结与解锁模板命令 int32_t SendCommand(int32_t commandId, const std::vector& extraInfo, const sptr& callbackObj) @@ -419,8 +434,34 @@ Fingerprint_auth驱动的主要工作是为上层用户认证框架和Fingerprin } return HDF_SUCCESS; } + + // 实现获取执行器属性接口 + int32_t ExecutorImpl::GetProperty( + const std::vector &templateIdList, const std::vector &propertyTypes, Property &property) + { + IAM_LOGI("interface mock start"); + property = {}; + IAM_LOGI("get property success"); + return HDF_SUCCESS; + } + + // 实现设置需缓存模板列表接口 + int32_t ExecutorImpl::SetCachedTemplates(const std::vector &templateIdList) + { + IAM_LOGI("interface mock start"); + IAM_LOGI("set cached templates success"); + return HDF_SUCCESS; + } + + // 实现注册SA命令回调接口 + int32_t ExecutorImpl::RegisterSaCommandCallback(const sptr &callbackObj) + { + IAM_LOGI("interface mock start"); + IAM_LOGI("register sa command callback success"); + return HDF_SUCCESS; + } ``` - + 4. 用户身份认证框架支持多driver,当增加driver或者修改driver信息,需要修改如下文件中serviceName2Config。 ```c++ diff --git a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md b/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md index 8167cb3617097d6a990324989389d902cb741778..1ef89e591cf752671a632c5a6711736b44951c84 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md @@ -208,17 +208,17 @@ LCD驱动模型属于驱动基础适配模块,第三方需要适配OpenHarmony ```c++ struct PanelInfo { - uint32_t width; - uint32_t height; - uint32_t hbp; - uint32_t hfp; - uint32_t hsw; - uint32_t vbp; - uint32_t vfp; - uint32_t vsw; - uint32_t frameRate; - enum LcdIntfType intfType; - enum IntfSync intfSync; + uint32_t width; // 水平尺寸 + uint32_t height; // 垂直尺寸 + uint32_t hbp; // 水平同步信号的后肩 + uint32_t hfp; // 水平同步信号的前肩 + uint32_t hsw; // 水平同步信号的脉宽 + uint32_t vbp; // 垂直同步信号的后肩 + uint32_t vfp; // 垂直同步信号的前肩 + uint32_t vsw; // 垂直同步信号的脉宽 + uint32_t frameRate; // 帧率 + enum LcdIntfType intfType; // LCD接口类型 + enum IntfSync intfSync; // 用户时序参数 struct MipiDsiDesc mipi; struct BlkDesc blk; struct PwmCfg pwm; @@ -263,11 +263,13 @@ LCD驱动模型属于驱动基础适配模块,第三方需要适配OpenHarmony static int32_t LcdResetOn(void) { int32_t ret; + /*设置管脚方向*/ ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); if (ret != HDF_SUCCESS) { HDF_LOGE("GpioSetDir failure, ret:%d", ret); return HDF_FAILURE; } + /*写入管脚*/ ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); if (ret != HDF_SUCCESS) { HDF_LOGE("GpioWrite failure, ret:%d", ret); @@ -282,6 +284,7 @@ LCD驱动模型属于驱动基础适配模块,第三方需要适配OpenHarmony - 器件驱动入口函数 ```c++ + /*初始化入口函数*/ int32_t SampleEntryInit(struct HdfDeviceObject *object) { HDF_LOGI("%s: enter", __func__); @@ -297,6 +300,7 @@ LCD驱动模型属于驱动基础适配模块,第三方需要适配OpenHarmony return HDF_SUCCESS; } + /*实现驱动*/ struct HdfDriverEntry g_sampleDevEntry = { .moduleVersion = 1, .moduleName = "LCD_SAMPLE", @@ -304,4 +308,4 @@ LCD驱动模型属于驱动基础适配模块,第三方需要适配OpenHarmony }; HDF_INIT(g_sampleDevEntry); - ``` \ No newline at end of file + ``` diff --git a/zh-cn/device-dev/driver/driver-peripherals-pinauth-des.md b/zh-cn/device-dev/driver/driver-peripherals-pinauth-des.md index d7fb9533461155f43ad86d78425756746164cf94..cd26d990f3221e89cfa9dd2b4852e1dcbaef08a9 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-pinauth-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-pinauth-des.md @@ -81,30 +81,32 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 ### 接口说明 -注:以下接口列举的为IDL接口描述生成的对应C++语言函数接口,接口声明见idl文件(/drivers/interface/pin_auth/v1_0/)。 +注:以下接口列举的为IDL接口描述生成的对应C++语言函数接口,接口声明见idl文件(/drivers/interface/pin_auth)。 在本文中,口令凭据的录入、认证和删除相关的HDI接口如表1所示,表2中的回调函数分别用于口令执行器返回操作结果给框架和获取用户输入的口令信息。 **表1** 接口功能介绍 | 接口名称 | 功能介绍 | | ------------------------------- | ------------------------------------------- | -| GetExecutorList(std::vector>& executorList) | 获取执行器列表。 | -| GetExecutorInfo(ExecutorInfo& info) | 获取执行器信息。 | +| GetExecutorList(std::vector\>& executorList) | 获取V1_0执行器列表。 | +| GetExecutorListV1_1(std::vector\>& executorList) | 获取V1_1版本执行器列表。 | | GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | 获取指定templateId的模板信息。 | -| OnRegisterFinish(const std::vector& templateIdList,
const std::vector& frameworkPublicKey,
const std::vector& extraInfo) | 执行器注册成功后,获取用户认证框架的公钥信息;获取用户认证框架的template 列表用于对账。 | -| OnSetData(uint64_t scheduleId, uint64_t authSubType,
const std::vector &data) | 回调函数,返回用户录入的口令子类型和录入的口令脱敏数据。 | -| Enroll(uint64_t scheduleId, const std::vector& extraInfo,
const sptr& callbackObj) | 录入pin码。 | -| Authenticate(uint64_t scheduleId, uint64_t templateId, const std::vector& extraInfo, const sptr& callbackObj) | pin码认证。 | +| OnRegisterFinish(const std::vector\& templateIdList,
const std::vector\& frameworkPublicKey,
const std::vector\& extraInfo) | 执行器注册成功后,获取用户认证框架的公钥信息;获取用户认证框架的template 列表用于对账。 | +| OnSetData(uint64_t scheduleId, uint64_t authSubType,
const std::vector\ &data) | 回调函数,返回用户录入的口令子类型和录入的口令脱敏数据。 | +| Enroll(uint64_t scheduleId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 录入pin码。 | +| Authenticate(uint64_t scheduleId, uint64_t templateId, const std::vector\& extraInfo, const sptr\& callbackObj) | pin码认证。 | | Delete(uint64_t templateId) | 删除pin码模板。 | | Cancel(uint64_t scheduleId) | 通过scheduleId取消指定操作。 | -| SendCommand(int32_t commandId, const std::vector& extraInfo,
const sptr& callbackObj) | 预留接口。 | +| SendCommand(int32_t commandId, const std::vector\& extraInfo,
const sptr\& callbackObj) | 预留接口。 | +| GetProperty(const std::vector\& templateIdList,
const std::vector\& propertyTypes, Property& property) | 获取执行器属性信息。 | + **表2** 回调函数介绍 | 接口名称 | 功能介绍 | | ------------------------------------------------------------ | -------------------- | -| IExecutorCallback::OnResult(int32_t code, const std::vector& extraInfo) | 返回操作的最终结果。 | -| IExecutorCallback::OnGetData(uint64_t scheduleId, const std::vector& salt,
uint64_t authSubType)| 返回获取pin码数据信息。 | +| IExecutorCallback::OnResult(int32_t code, const std::vector\& extraInfo) | 返回操作的最终结果。 | +| IExecutorCallback::OnGetData(uint64_t scheduleId, const std::vector\& salt,
uint64_t authSubType)| 返回获取pin码数据信息。 | ### 开发步骤 @@ -139,18 +141,18 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 struct IDeviceIoService ioService; OHOS::sptr stub; }; - + // 服务接口调用响应接口 static int32_t PinAuthInterfaceDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) { IAM_LOGI("start"); auto *hdfPinAuthInterfaceHost = CONTAINER_OF(client->device->service, struct HdfPinAuthInterfaceHost, ioService); - + OHOS::MessageParcel *dataParcel = nullptr; OHOS::MessageParcel *replyParcel = nullptr; OHOS::MessageOption option; - + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { IAM_LOGE("%{public}s:invalid data sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; @@ -159,10 +161,10 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 IAM_LOGE("%{public}s:invalid reply sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; } - + return hdfPinAuthInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); } - + // 初始化接口 static int HdfPinAuthInterfaceDriverInit(struct HdfDeviceObject *deviceObject) { @@ -176,7 +178,7 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 } return HDF_SUCCESS; } - + // PinAuth驱动对外提供的服务绑定到HDF框架 static int HdfPinAuthInterfaceDriverBind(struct HdfDeviceObject *deviceObject) { @@ -186,29 +188,29 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 IAM_LOGE("%{public}s: failed to create create HdfPinAuthInterfaceHost object", __func__); return HDF_FAILURE; } - + hdfPinAuthInterfaceHost->ioService.Dispatch = PinAuthInterfaceDriverDispatch; hdfPinAuthInterfaceHost->ioService.Open = NULL; hdfPinAuthInterfaceHost->ioService.Release = NULL; - + auto serviceImpl = IPinAuthInterface::Get(true); if (serviceImpl == nullptr) { IAM_LOGE("%{public}s: failed to get of implement service", __func__); return HDF_FAILURE; } - + hdfPinAuthInterfaceHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, IPinAuthInterface::GetDescriptor()); if (hdfPinAuthInterfaceHost->stub == nullptr) { IAM_LOGE("%{public}s: failed to get stub object", __func__); return HDF_FAILURE; } - + deviceObject->service = &hdfPinAuthInterfaceHost->ioService; IAM_LOGI("success"); return HDF_SUCCESS; } - + // 释放PinAuth驱动中的资源 static void HdfPinAuthInterfaceDriverRelease(struct HdfDeviceObject *deviceObject) { @@ -218,7 +220,7 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 delete hdfPinAuthInterfaceHost; IAM_LOGI("success"); } - + static struct HdfDriverEntry g_pinAuthInterfaceDriverEntry = { .moduleVersion = 1, .moduleName = "pinauth_interface_service", @@ -226,18 +228,18 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 .Init = HdfPinAuthInterfaceDriverInit, .Release = HdfPinAuthInterfaceDriverRelease, }; - + // 调用HDF_INIT将驱动入口注册到HDF框架中,在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动,当Init调用异常时,HDF框架会调用Release释放驱动资源并退出 HDF_INIT(g_pinauthinterfaceDriverEntry); ``` - - + + 1. 完成获取执行器列表接口实现,详细代码参见[pin_auth_interface_service.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/pin_auth/hdi_service/service/src/pin_auth_interface_service.cpp)文件。 ```c++ // 执行器实现类 - class ExecutorImpl : public IExecutor, public NoCopyable { + class ExecutorImpl : public V1_1::IExecutor, public NoCopyable { public: explicit ExecutorImpl(std::shared_ptr pinHdi); virtual ~ExecutorImpl() {} @@ -254,7 +256,9 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 int32_t Cancel(uint64_t scheduleId) override; int32_t SendCommand(int32_t commandId, const std::vector &extraInfo, const sptr &callbackObj) override; - + int32_t GetProperty(const std::vector &templateIdList, const std::vector &propertyTypes, + Property &property) override; + private: class ScheduleMap { public: @@ -263,7 +267,7 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 uint32_t GetScheduleInfo(const uint64_t scheduleId, uint32_t &commandId, sptr &callback, uint64_t &templateId, std::vector &salt); uint32_t DeleteScheduleId(const uint64_t scheduleId); - + private: struct ScheduleInfo { uint32_t commandId; @@ -271,20 +275,20 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 uint64_t templateId; std::vector salt; }; - + std::mutex mutex_; std::map scheduleInfo_; }; - + private: uint32_t NewSalt(std::vector &salt); void CallError(const sptr &callbackObj, const uint32_t errorCode); std::shared_ptr pinHdi_; ScheduleMap scheduleMap_; }; - - // 获取执行器列表实现,创建执行器(仅作示例) - int32_t PinAuthInterfaceService::GetExecutorList(std::vector> &executorList) + + // 获取V1_1执行器列表实现,创建执行器(仅作示例) + int32_t PinAuthInterfaceService::GetExecutorListV1_1(std::vector> &executorList) { IAM_LOGI("start"); std::shared_ptr pinHdi = @@ -302,10 +306,21 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 IAM_LOGI("end"); return HDF_SUCCESS; } + + // 获取V1_0执行器列表实现,使用V1_1版本执行器实现V1_0版本执行器的功能 + int32_t PinAuthInterfaceService::GetExecutorList(std::vector> &executorList) + { + std::vector> executorListV1_1; + int32_t result = GetExecutorListV1_1(executorListV1_1); + for (auto &executor : executorListV1_1) { + executorList.push_back(executor); + } + return result; + } ``` - - - + + + 1. 完成执行器每个功能接口实现,详细代码参见[executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/pin_auth/hdi_service/service/src/executor_impl.cpp)文件。 ```c++ @@ -329,10 +344,10 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 return result; } info.esl = static_cast(eslRet); - + return HDF_SUCCESS; } - + // 实现获取指定templateId的模板信息接口 int32_t ExecutorImpl::GetTemplateInfo(uint64_t templateId, TemplateInfo &info) { @@ -353,14 +368,14 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 IAM_LOGE("copy subType to extraInfo fail!"); return HDF_FAILURE; } - + info.executorType = EXECUTOR_TYPE; info.remainAttempts = infoRet.remainTimes; info.lockoutDuration = infoRet.freezingTime; - + return HDF_SUCCESS; } - + // 实现执行器注册成功后,获取用户认证框架的公钥信息、获取用户认证框架的template 列表接口,将公钥信息保存,template列表用于和本地的template做对账 int32_t ExecutorImpl::OnRegisterFinish(const std::vector &templateIdList, const std::vector &frameworkPublicKey, const std::vector &extraInfo) @@ -377,10 +392,10 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 IAM_LOGE("Verify templateData failed"); return result; } - + return HDF_SUCCESS; } - + // 实现口令录入接口 int32_t ExecutorImpl::Enroll(uint64_t scheduleId, const std::vector &extraInfo, const sptr &callbackObj) @@ -412,10 +427,10 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 } return result; } - + return HDF_SUCCESS; } - + // 实现回调数据获取的接口 int32_t ExecutorImpl::OnSetData(uint64_t scheduleId, uint64_t authSubType, const std::vector &data) { @@ -451,7 +466,7 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 default: IAM_LOGE("Error commandId"); } - + if (callback->OnResult(result, resultTlv) != SUCCESS) { IAM_LOGE("callbackObj Pin failed"); } @@ -459,7 +474,7 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 if (scheduleMap_.DeleteScheduleId(scheduleId) != HDF_SUCCESS) { IAM_LOGI("delete scheduleId failed"); } - + return HDF_SUCCESS; } // 实现口令认证接口 @@ -499,10 +514,10 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 } return result; } - + return HDF_SUCCESS; } - + // 实现删除口令模板接口 int32_t ExecutorImpl::Delete(uint64_t templateId) { @@ -516,10 +531,10 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 IAM_LOGE("Verify templateData failed, fail code : %{public}d", result); return result; } - + return HDF_SUCCESS; } - + // 实现通过scheduleId取消指定操作接口 int32_t ExecutorImpl::Cancel(uint64_t scheduleId) { @@ -530,7 +545,7 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 } return HDF_SUCCESS; } - + // 口令预留接口 int32_t ExecutorImpl::SendCommand(int32_t commandId, const std::vector &extraInfo, const sptr &callbackObj) @@ -541,8 +556,37 @@ Pin_auth驱动的主要工作是为上层用户认证框架和Pin_auth服务提 static_cast(callbackObj); return HDF_SUCCESS; } + + // 获取执行器属性信息接口 + int32_t ExecutorImpl::GetProperty( + const std::vector &templateIdList, const std::vector &propertyTypes, Property &property) + { + IAM_LOGI("start"); + if (pinHdi_ == nullptr) { + IAM_LOGE("pinHdi_ is nullptr"); + return HDF_FAILURE; + } + + if (templateIdList.size() != 1) { + IAM_LOGE("templateIdList size is not 1"); + return HDF_FAILURE; + } + + uint64_t templateId = templateIdList[0]; + OHOS::UserIam::PinAuth::PinCredentialInfo infoRet = {}; + int32_t result = pinHdi_->QueryPinInfo(templateId, infoRet); + if (result != SUCCESS) { + IAM_LOGE("Get TemplateInfo failed, fail code : %{public}d", result); + return HDF_FAILURE; + } + + property.authSubType = infoRet.subType; + property.remainAttempts = infoRet.remainTimes; + property.lockoutDuration = infoRet.freezingTime; + return HDF_SUCCESS; + } ``` - + ### 调测验证 驱动开发完成后,可基于RK3568平台验证, 通过设备的设置和锁屏功能验证口令认证功能是否正常,测试步骤如下: diff --git a/zh-cn/device-dev/driver/driver-peripherals-user-auth-des.md b/zh-cn/device-dev/driver/driver-peripherals-user-auth-des.md index 57c11bc60473b958dd3421f13e04700c3655d0db..9ad49967ae009f5e67cc1829d0c6136c4806a031 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-user-auth-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-user-auth-des.md @@ -71,7 +71,7 @@ - Kit OpenHarmony系统向第三方应用提供的基础应用编程接口。 - + - Inner API OpenHarmony系统向系统应用提供的应用编程接口。 @@ -117,26 +117,30 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 | 接口名称 | 功能介绍 | | --------------------------- | --------------------------- | | Init() | 初始化缓存信息。 | -| AddExecutor(const ExecutorRegisterInfo& info, uint64_t& index, std::vector& publicKey,
std::vector& templateIds) | 添加认证执行器,获得此认证能力。 | +| AddExecutor(const ExecutorRegisterInfo& info, uint64_t& index, std::vector\& publicKey,
std::vector\& templateIds) | 添加认证执行器,获得此认证能力。 | | DeleteExecutor(uint64_t index) | 根据索引值index删除认证执行器。 | -| OpenSession(int32_t userId, std::vector& challenge) | 开启认证凭据管理Session。 | +| OpenSession(int32_t userId, std::vector\& challenge) | 开启认证凭据管理Session。 | | CloseSession(int32_t userId) | 关闭认证凭据管理Session。 | -| BeginEnrollment(int32_t userId, const std::vector& authToken, const EnrollParam& param,
ScheduleInfo& info) | 发起用户的认证凭据的录入,当录入类型为PIN码且当前用户已录入PIN码的情况下会更新PIN码。 | -| UpdateEnrollmentResult(int32_t userId, const std::vector& scheduleResult, uint64_t& credentialId,
CredentialInfo& oldInfo) | 更新录入结果,完成此次录入。 | +| BeginEnrollment(int32_t userId, const std::vector\& authToken, const EnrollParam& param,
ScheduleInfo& info) | 发起用户的认证凭据的录入,当录入类型为PIN码且当前用户已录入PIN码的情况下会更新PIN码(V1_0版本)。 | +| UpdateEnrollmentResult(int32_t userId, const std::vector\& scheduleResult, uint64_t& credentialId,
CredentialInfo& oldInfo) | 更新录入结果,完成此次录入。 | | CancelEnrollment(int32_t userId) | 取消此次录入。 | -| DeleteCredential(int32_t userId, uint64_t credentialId, const std::vector& authToken,
CredentialInfo& info) | 根据credentialId删除凭据信息。 | -| DeleteUser(int32_t userId, const std::vector& authToken,
std::vector& deletedInfos) | 删除PIN码即在用户认证框架中删除用户。 | -| EnforceDeleteUser(int32_t userId, std::vector& deletedInfos) | 强制删除用户,当系统内此用户被删除时强制调用。 | -| GetCredential(int32_t userId, AuthType authType, std::vector& infos) | 查询用户某种认证类型下的凭据信息。 | -| GetSecureInfo(int32_t userId, uint64_t& secureUid, std::vector& infos) | 查询用户的安全用户Id和每种认证类型的录入标记Id。 | -| BeginAuthentication(uint64_t contextId, const AuthSolution& param,
std::vector& scheduleInfos) | 发起认证,生成认证方案和调度信息。 | -| UpdateAuthenticationResult(uint64_t contextId, const std::vector& scheduleResult,
AuthResultInfo& info) | 更新认证结果,进行此次认证方案结果的评估。 | +| DeleteCredential(int32_t userId, uint64_t credentialId, const std::vector\& authToken,
CredentialInfo& info) | 根据credentialId删除凭据信息。 | +| DeleteUser(int32_t userId, const std::vector\& authToken,
std::vector\& deletedInfos) | 删除PIN码即在用户认证框架中删除用户。 | +| EnforceDeleteUser(int32_t userId, std::vector\& deletedInfos) | 强制删除用户,当系统内此用户被删除时强制调用。 | +| GetCredential(int32_t userId, AuthType authType, std::vector\& infos) | 查询用户某种认证类型下的凭据信息。 | +| GetSecureInfo(int32_t userId, uint64_t& secureUid, std::vector\& infos) | 查询用户的安全用户Id和每种认证类型的录入标记Id。 | +| BeginAuthentication(uint64_t contextId, const AuthSolution& param,
std::vector\& scheduleInfos) | 发起认证,生成认证方案和调度信息(V1_0版本)。 | +| UpdateAuthenticationResult(uint64_t contextId, const std::vector\& scheduleResult,
AuthResultInfo& info) | 更新认证结果,进行此次认证方案结果的评估。 | | CancelAuthentication(uint64_t contextId) | 取消此次认证。 | -| BeginIdentification(uint64_t contextId, AuthType authType, const std::vector& challenge,
uint32_t executorId, ScheduleInfo& scheduleInfo) | 发起识别,生成识别方案和调度信息。 | -| UpdateIdentificationResult(uint64_t contextId, const std::vector& scheduleResult,
IdentifyResultInfo& info) | 更新识别结果,进行此次识别方案结果的评估。 | +| BeginIdentification(uint64_t contextId, AuthType authType, const std::vector\& challenge,
uint32_t executorId, ScheduleInfo& scheduleInfo) | 发起识别,生成识别方案和调度信息(V1_0版本)。 | +| UpdateIdentificationResult(uint64_t contextId, const std::vector\& scheduleResult,
IdentifyResultInfo& info) | 更新识别结果,进行此次识别方案结果的评估。 | | CancelIdentification(uint64_t contextId) | 取消此次识别。 | | GetAuthTrustLevel(int32_t userId, AuthType authType, uint32_t& authTrustLevel) | 获取此用户当前认证类型的认证可信等级。 | -| GetValidSolution(int32_t userId, const std::vector& authTypes, uint32_t authTrustLevel,
std::vector& validTypes) | 筛选此用户当前认证可信等级下可用的认证方式。 | +| GetValidSolution(int32_t userId, const std::vector\& authTypes, uint32_t authTrustLevel,
std::vector\& validTypes) | 筛选此用户当前认证可信等级下可用的认证方式。 | +| BeginEnrollmentV1_1(int32_t userId, const std::vector\& authToken, const EnrollParam& param, ScheduleInfoV1_1& info) | 发起用户的认证凭据的录入,当录入类型为PIN码且当前用户已录入PIN码的情况下会更新PIN码(V1_1版本)。 | +| BeginAuthenticationV1_1(uint64_t contextId, const AuthSolution& param, std::vector\& scheduleInfos) | 发起认证,生成认证方案和调度信息(V1_1版本)。 | +| BeginIdentificationV1_1(uint64_t contextId, AuthType authType, + const std::vector\& challenge, uint32_t executorSensorHint, ScheduleInfoV1_1& scheduleInfo)| 发起识别,生成识别方案和调度信息(V1_1版本)。 | ### 开发步骤 @@ -164,17 +168,17 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 struct IDeviceIoService ioService; OHOS::sptr stub; }; - + // 服务接口调用响应接口 static int32_t UserAuthInterfaceDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply) { auto *hdfUserAuthInterfaceHost = CONTAINER_OF(client->device->service, struct HdfUserAuthInterfaceHost, ioService); - + OHOS::MessageParcel *dataParcel = nullptr; OHOS::MessageParcel *replyParcel = nullptr; OHOS::MessageOption option; - + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { HDF_LOGE("%{public}s:invalid data sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; @@ -183,10 +187,10 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 HDF_LOGE("%{public}s:invalid reply sbuf object to dispatch", __func__); return HDF_ERR_INVALID_PARAM; } - + return hdfUserAuthInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); } - + // 初始化接口 int HdfUserAuthInterfaceDriverInit(struct HdfDeviceObject *deviceObject) { @@ -194,46 +198,46 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 OHOS::UserIAM::Common::Init(); return HDF_SUCCESS; } - + // User_auth驱动对外提供的服务绑定到HDF框架 int HdfUserAuthInterfaceDriverBind(struct HdfDeviceObject *deviceObject) { HDF_LOGI("HdfUserAuthInterfaceDriverBind enter"); - + auto *hdfUserAuthInterfaceHost = new (std::nothrow) HdfUserAuthInterfaceHost; if (hdfUserAuthInterfaceHost == nullptr) { HDF_LOGE("%{public}s: failed to create HdfUserAuthInterfaceHost object", __func__); return HDF_FAILURE; } - + hdfUserAuthInterfaceHost->ioService.Dispatch = UserAuthInterfaceDriverDispatch; hdfUserAuthInterfaceHost->ioService.Open = NULL; hdfUserAuthInterfaceHost->ioService.Release = NULL; - + auto serviceImpl = IUserAuthInterface::Get(true); if (serviceImpl == nullptr) { HDF_LOGE("%{public}s: failed to implement service", __func__); return HDF_FAILURE; } - + hdfUserAuthInterfaceHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, IUserAuthInterface::GetDescriptor()); if (hdfUserAuthInterfaceHost->stub == nullptr) { HDF_LOGE("%{public}s: failed to get stub object", __func__); return HDF_FAILURE; } - + deviceObject->service = &hdfUserAuthInterfaceHost->ioService; return HDF_SUCCESS; } - + // 释放User_auth驱动中的资源 void HdfUserAuthInterfaceDriverRelease(struct HdfDeviceObject *deviceObject){ HDF_LOGI("HdfUserAuthInterfaceDriverRelease enter"); auto *hdfUserAuthInterfaceHost = CONTAINER_OF(deviceObject->service, struct HdfUserAuthInterfaceHost, ioService); delete hdfUserAuthInterfaceHost; } - + // 注册User_auth驱动入口数据结构体对象 struct HdfDriverEntry g_userAuthInterfaceDriverEntry = { .moduleVersion = 1, @@ -242,7 +246,7 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 .Init = HdfUserAuthInterfaceDriverInit, .Release = HdfUserAuthInterfaceDriverRelease, }; - + // 调用HDF_INIT将驱动入口注册到HDF框架中,在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动,当Init调用异常时,HDF框架会调用Release释放驱动资源并退出 #ifndef __cplusplus extern "C" { @@ -267,14 +271,14 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 GlobalUnLock(); return ret; } - + // 删除执行器 int32_t UserAuthInterfaceService::DeleteExecutor(uint64_t index) { return UnRegisterExecutor(index); } ``` - + 3. 录入接口举例实现,详细代码参见[user_auth_interface_service.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/user_auth/hdi_service/service/user_auth_interface_service.cpp)文件。 ```c++ @@ -292,7 +296,7 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 GlobalUnLock(); return ret; } - + // 关闭认证凭据管理会话 int32_t UserAuthInterfaceService::CloseSession(int32_t userId) { @@ -301,10 +305,10 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 GlobalUnLock(); return ret; } - - // 发起认证,生成录入调度信息 - int32_t UserAuthInterfaceService::BeginEnrollment(int32_t userId, const std::vector& authToken, - const EnrollParam& param, ScheduleInfo& info) + + // 发起录入,生成录入调度信息(V1_1版本) + int32_t UserAuthInterfaceService::BeginEnrollmentV1_1(int32_t userId, const std::vector& authToken, + const EnrollParam& param, ScheduleInfoV1_1& info) { IAM_LOGI("start"); GlobalLock(); @@ -342,7 +346,18 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 GlobalUnLock(); return ret; } - + + // 发起录入,生成录入调度信息(V1_0版本),通过调用 V1_1 版本相应接口实现功能 + int32_t UserAuthInterfaceService::BeginEnrollment(int32_t userId, const std::vector &authToken, + const EnrollParam ¶m, ScheduleInfo &info) + { + IAM_LOGI("start"); + ScheduleInfoV1_1 infoV1_1; + int32_t ret = BeginEnrollmentV1_1(userId, authToken, param, infoV1_1); + CopyScheduleInfoV1_1ToV1_0(infoV1_1, info); + return ret; + } + // 取消录入接口实现 int32_t UserAuthInterfaceService::CancelEnrollment(int32_t userId) { @@ -350,7 +365,7 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 BreakOffCoauthSchedule(userId); return RESULT_SUCCESS; } - + // 录入凭据信息存储接口实现 int32_t UserAuthInterfaceService::UpdateEnrollmentResult(int32_t userId, const std::vector& scheduleResult, uint64_t& credentialId, CredentialInfo& oldInfo) @@ -405,10 +420,10 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 } return userAuthInterfaceService; } - + // 发起认证,生成认证方案和调度信息 - int32_t UserAuthInterfaceService::BeginAuthentication(uint64_t contextId, const AuthSolution& param, - std::vector& infos) + int32_t UserAuthInterfaceService::BeginAuthenticationV1_1(uint64_t contextId, const AuthSolution& param, + std::vector& infos) { IAM_LOGI("start"); if (param.challenge.size() != sizeof(uint64_t)) { @@ -436,7 +451,7 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 return ret; } for (uint32_t i = 0; i < scheduleIdNum; i++) { - ScheduleInfo temp; + ScheduleInfoV1_1 temp; if (!CopyScheduleInfo(schedulesGet + i, &temp)) { infos.clear(); ret = RESULT_GENERAL_ERROR; @@ -448,7 +463,18 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 GlobalUnLock(); return ret; } - + + // 发起认证,生成认证方案和调度信息(V1_0版本),通过调用 V1_1 版本相应接口实现功能 + int32_t UserAuthInterfaceService::BeginAuthentication(uint64_t contextId, const AuthSolution ¶m, + std::vector &infos) + { + IAM_LOGI("start"); + std::vector infosV1_1; + int32_t ret = BeginAuthenticationV1_1(contextId, param, infosV1_1); + CopyScheduleInfosV1_1ToV1_0(infosV1_1, infos); + return ret; + } + // 更新认证结果,进行此次认证方案结果的评估 int32_t UserAuthInterfaceService::UpdateAuthenticationResult(uint64_t contextId, const std::vector& scheduleResult, AuthResultInfo& info) @@ -487,7 +513,7 @@ User_auth驱动的主要工作是为User_auth服务提供稳定的用户凭据 GlobalUnLock(); return RESULT_SUCCESS; } - + // 取消认证 int32_t UserAuthInterfaceService::CancelAuthentication(uint64_t contextId) { diff --git a/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md b/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md index f5d3d8ece567e727088479f5355b2a4ab8de1298..ab2288c40e8f8c4da1982fc4c4f795d78ac2865c 100644 --- a/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md +++ b/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md @@ -1230,10 +1230,10 @@ HiviewRegisterHilogProc(HilogProc_Impl); { "component": "histreamer", "features": [ - "multimedia_histreamer_enable_plugin_hdi_adapter = true", - "multimedia_histreamer_enable_plugin_minimp3_adapter = true", - "multimedia_histreamer_enable_plugin_ffmpeg_adapter = false", - "config_ohos_multimedia_histreamer_stack_size = 65536" + "histreamer_enable_plugin_hdi_adapter = true", + "histreamer_enable_plugin_minimp3_adapter = true", + "histreamer_enable_plugin_ffmpeg_adapter = false", + "config_ohos_histreamer_stack_size = 65536" ] } ] @@ -1242,12 +1242,12 @@ HiviewRegisterHilogProc(HilogProc_Impl); `histreamer`部件配置项说明如下: -| 配置项 | 说明 | -| --------------------------------------------------- | ------------------------------- | -| multimedia_histreamer_enable_plugin_hdi_adapter | 是否使能histreamer对接到hdi接口 | -| multimedia_histreamer_enable_plugin_minimp3_adapter | 是否使能插件适配minimp3 | -| multimedia_histreamer_enable_plugin_ffmpeg_adapter | 是否使能插件适配FFmpeg | -| config_ohos_multimedia_histreamer_stack_size | histreamer栈大小设置 | +| 配置项 | 说明 | +| ---------------------------------------- | ------------------------------- | +| histreamer_enable_plugin_hdi_adapter | 是否使能histreamer对接到hdi接口 | +| histreamer_enable_plugin_minimp3_adapter | 是否使能插件适配minimp3 | +| histreamer_enable_plugin_ffmpeg_adapter | 是否使能插件适配FFmpeg | +| config_ohos_histreamer_stack_size | histreamer栈大小设置 | #### 公共基础库子系统适配 diff --git a/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md b/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md deleted file mode 100644 index f73f6c9398ade014d335277d4744f20e7725f279..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md +++ /dev/null @@ -1,60 +0,0 @@ -# 预置应用配置与安装指导 - -预置应用是指随OpenHarmony系统出厂预置的应用。 - -本文介绍开发者如何将一个非预置应用配置为预置应用,以及已有预置应用更新后如何重新安装。 - -## 将非预置应用配置为预置应用。 - -1. 确定预置应用支持的路径,可以通过下述命令查询。本文将以路径/system/etc/app/为例。 - -``` -hdc_std param get const.cust.config_dir_layer -``` - -2. 在install_list.json中配置hap在设备上的路径。 - -``` -hdc_std shell mount -o rw,renount / -hdc_std file recv /system/etc/app/install_list.json . -``` - -3. 按照json中的配置方式,配置对应的字段。 - -``` -{ - "app_dir":"system/app/xxxx/yyyy", // 设备上的hap路径,如果不存在,需要手动创建,并推送hap到此目录。 - "removable":true // 是否支持卸载,false表示不可卸载,true表示可以卸载。 -} -``` - -4. 修改完成后,将install_list.json文件推送到设备上,并重启设备生效。 - -``` - hdc_std shell mount -o rw,remount / - hdc_std file send install_list.json /system/etc/app/install_list.json - hdc_std shell reboot -``` - -## 重新安装更新后的已有预置应用 - -有两种方法。 - -- 方法一:直接清空data,重启设备,应用会自动安装。 - -``` - hdc_std shell mount -o rw,remount / - hdc_std shell rm /data/* -rf - hdc_std shell sync - hdc_std shell /system/bin/udevadm trigger - hdc_std shell reboot -``` -- 方法二:如果该应用之前没有安装过,则可以执行下面命令后重启设备。 - -``` - hdc_std shell mount -o rw,remount / - hdc_std shell param set persist.bms.test-upgrade true - hdc_std shell reboot -``` - -如果应用之前已经安装过,这时继续推送新的hap到/system/app/的路径下,则需要保证应用的版本号,分为[Stage模型的版本号(versionCode)](../../application-dev/quick-start/app-configuration-file.md),[FA模型的版本号(code)](../../application-dev/quick-start/app-structure.md#version对象内部结构)比之前的大。 这时执行方法二的命令,重启后应用同样可以正常安装。需要注意的是方法二命令,不需要反复执行, 重启之后依然生效。 \ No newline at end of file diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md b/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md index 4e86032eb3c5af9189a946ecea2a11b6d85c02af..3a7303a2bce1fb9b415f14139a5d5838178bfe9e 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md @@ -68,18 +68,3 @@ 安装完成后,当界面输出“DevEco Device Tool successfully installed.”时,表示DevEco Device Tool安装成功。 ![zh-cn_image_0000001338201457](figures/zh-cn_image_0000001338201457.png) - - -6. 使用如下apt-get命令安装后续操作所需的库和工具。 - - ```shell - sudo apt-get update && sudo apt-get install binutils binutils-dev git git-lfs gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib gcc-arm-linux-gnueabi libc6-dev-i386 libc6-dev-amd64 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 bc gnutls-bin python3.8 python3-pip ruby genext2fs device-tree-compiler make libffi-dev e2fsprogs pkg-config perl openssl libssl-dev libelf-dev libdwarf-dev u-boot-tools mtd-utils cpio doxygen liblz4-tool openjdk-8-jre gcc g++ texinfo dosfstools mtools default-jre default-jdk libncurses5 apt-utils wget scons python3.8-distutils tar rsync git-core libxml2-dev lib32z-dev grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev - ``` - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > - > 以上安装命令适用于Ubuntu18.04,其他版本请根据安装包名称采用对应的安装命令。其中: - > - > - Python要求安装Python 3.8及以上版本,此处以Python 3.8为例。 - > - > - Java要求java8及以上版本,此处以java8为例。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md b/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md index 7468669d72dd3a528a1f45312383448d841ae652..9ad6c874391abe700815cc390bef0e1faca87563 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md @@ -20,8 +20,6 @@ OpenHarmony Stable Version类型的源码为OpenHarmony稳定版本源码,通 ## 操作步骤 -OpenHarmony稳定版本源码,支持OpenHarmony-v1.1.4-LTS、OpenHarmony-v3.0.3-LTS和OpenHarmony-v3.1-Release版本。 - 1. 打开DevEco Device Tool,进入Home页,点击**New Project**创建新工程。 ![zh-cn_image_0000001272258726](figures/zh-cn_image_0000001272258726.png) diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-seccomp.md b/zh-cn/device-dev/subsystems/subsys-boot-init-seccomp.md index b8970299226bf4b16c2c65dff3fc4688a0e25d1a..f022097e0ef18ea91e814507ccf6f043f32db379 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-seccomp.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-seccomp.md @@ -114,13 +114,13 @@ Seccomp(Secure computing mode)是Linux kernel支持的一种安全机制。 **表2** ohos_prebuilt_seccomp模板字段说明 | 字段 | 说明 | | --- | --- | - | sources | 必填,策略配置文件的路径 | - | filtername | 必填,该内容与进程[引导启动配置文件](subsys-boot-init-cfg.md)中的services name保持一致,否则会使能失败。该字段决定了动态库的名称。例如,将filtername设置为xxx,则编译生成的策略动态库名称为libxxx_filter.z.so | - | process_type | 必填,根据使能进程类型填写不同的字符串。若使能的进程为init孵化的进程,则该字段赋值"system";若是应用进程,则该字段赋值"app" | - | part_name | 必填,部件名 | - | subsystem_name | 必填,子系统名 | - | install_enable | 必填,是否安装到镜像,为true | - | install_images | 必填,安装的镜像位置 | + | sources | 必填,策略配置文件的路径。 | + | filtername | 必填,该内容与进程[引导启动配置文件](subsys-boot-init-cfg.md)中的services name保持一致,否则会使能失败。该字段决定了动态库的名称。例如,将filtername设置为xxx,则编译生成的策略动态库名称为libxxx_filter.z.so。 | + | process_type | 必填,根据使能进程类型填写不同的字符串。若使能的进程为init孵化的进程,则该字段赋值"system";若是应用进程,则该字段赋值"app"。 | + | part_name | 必填,部件名。 | + | subsystem_name | 必填,子系统名。 | + | install_enable | 必填,是否安装到镜像,为true。 | + | install_images | 必填,安装的镜像位置。 | 示例 ```python @@ -236,12 +236,12 @@ base/startup/init/services/modules/seccomp | 策略文件 | 说明 | | --- | --- | | system.seccomp.policy | 大部分系统服务进程使能的Seccomp策略 | - | system.blocklist.seccomp.policy | 系统进程的系统调用基线黑名单,即非特权进程禁止使用的系统调用名单 | + | system.blocklist.seccomp.policy | 系统进程的系统调用基线黑名单,即非特权进程禁止使用的系统调用名单。 | | app.seccomp.policy | 所有应用进程使能的Seccomp策略 | - | app.blocklist.seccomp.policy | 应用进程的系统调用基线黑名单,即应用进程禁止使用的系统调用名单 | + | app.blocklist.seccomp.policy | 应用进程的系统调用基线黑名单,即应用进程禁止使用的系统调用名单。 | | spawn.seccomp.policy | appspawn进程与nwebspawn进程使能的Seccomp策略 | | renderer.seccomp.policy | 由nwebspawn孵化的渲染进程使能的Seccomp策略 | - | privileged_process.seccomp.policy | 特权进程声明名单,即某些进程需使用基线黑名单系统调用时,可在此文件中声明进程标识符与需使用的基线黑名单 | + | privileged_process.seccomp.policy | 特权进程声明名单,即某些进程需使用基线黑名单系统调用时,可在此文件中声明进程标识符与需使用的基线黑名单。 | ### 普通策略文件编写规则 - 若要声明配置项,以“@”加配置项的形式书写,例如,@returnValue。 @@ -255,11 +255,11 @@ base/startup/init/services/modules/seccomp | 配置项 | 说明 | 规则 | | --- | --- | -- | -| returnValue | 返回值 | 必填,范围为:
- LOG: 宽容模式,只记录Audit日志,不会终止进程;
- TRAP: 终止进程,且可交给faultloggerd处理;
- KILL_PROCESS: 终止进程;
- KILL_THREAD:终止线程。 | +| returnValue | 返回值 | 必填,范围为:
- LOG:宽容模式,只记录Audit日志,不会终止进程;
- TRAP:终止进程,且可交给faultloggerd处理;
- KILL_PROCESS:终止进程。
- KILL_THREAD:终止线程。 | | headFiles | 头文件,用于声明allowListWithArgs与priorityWithArgs字段中出现的宏。 | 格式上:用""、<>来包含头文件名称,例如 、"cde.h" 默认有的头文件:。 | | priority | 频繁使用的系统调用白名单 | 在策略中优先判断,用于提高性能。 | | priorityWithArgs | 频繁使用的带参数限制的系统调用白名单 | 在策略中优先判断,用于提高性能。 | -| allowList | 白名单 | 进程允许的系统调用。 | +| allowList | 白名单 | 进程允许的系统调用 | | allowListWithArgs | 带参数限制白名单 | 其中系统调用名称与参数限制说明用“:”隔开,判断符号可用<、<=、>、>=、==、!=、&,逻辑符号可用&&、\|\|。
系统调用的第几个参数,使用argn表示,n的范围为0~5。判断语句用“if”开头,else语句结尾。语句结束后需声明返回值,判断语句与返回值使用“;”隔开。
声明返回值的样式为“return xxx”,xxx的范围与returnValue一致。若有多重判断条件,判断条件之间可使用elif隔开。 | | blockList | 黑名单 | 在解析策略过程中,生成BPF指令前会检查白名单中的系统调用会不会存在于黑名单中。若存在,则会出现解析错误的信息。 | | selfDefineSyscall | 自定义系统调用 | 填写的内容为数字。 | @@ -329,26 +329,27 @@ swapon;all **表6** 统计方法对比说明 | 统计方法 | 基本方法 | 优点 | 缺点 | | --- | --- | --- | --- | -|
静态分析 |
分析ELF反汇编代码得到调用关系,统计调用libc库的接口集合,解析libc库得到libc接口与系统调用号的调用关系,从而得到ELF文件使用的系统调用号 |
可以统计到异常分支的系统调用。 |
不支持解析指针函数的调用关系。 | -| Strace工具统计 | 设备运行时,使用Strace跟踪业务进程或者跟踪测试进程。跟踪过程中会将系统调用的执行记录下来。收集日志后使用脚本解析日志生成Seccomp策略文件。 | 操作简单 | 代码分支全部覆盖才能完整统计使用的系统调用。 | +|
静态分析 |
分析ELF反汇编代码得到调用关系,统计调用libc库的接口集合,解析libc库得到libc接口与系统调用号的调用关系,从而得到ELF文件使用的系统调用号。 |
可以统计到异常分支的系统调用。 |
不支持解析指针函数的调用关系。 | +| Strace工具统计 | 设备运行时,使用Strace跟踪业务进程。跟踪过程中会将系统调用的执行记录下来。收集日志后使用脚本解析日志生成Seccomp策略文件。 | 操作简单 | 代码分支全部覆盖才能完整统计使用的系统调用。 | | Audit统计 | 进程使能Seccomp策略后,Seccomp机制会拦截非法系统调用,在内核日志生成含系统调用号信息的Audit日志。收集日志后使用脚本解析日志生成Seccomp策略文件。 | 可对上面两个方法进行查漏补缺。 | 日志有丢失的风险。
代码分支全部覆盖才能完整统计使用的系统调用。 | -> ![icon-note.gif](public_sys-resources/icon-note.gif)**免责声明:使用第三方软件或网站**
-> 我们可能会推荐使用其它公司拥有或运营的软件、信息、产品或网站。我们通过超链接或其它方法作此推荐,以帮助您访问第三方资源。
-> 虽然我们努力将您引导至有用的、值得信赖的资源,但我们无法保证由第三方资源提供或在第三方资源处提供的软件、信息、产品或服务,也无法跟踪这些资源的变化。因此,我们不对任何第三方资源的内容或结果的合规性、准确性、完整性负责,也不对因使用第三方资源提供的产品或服务或由第三方资源提供的产品或服务的使用或故障而导致的任何损失或损害负责。 - #### 静态分析 1. 环境准备 1. 准备linux环境。 2. 下载交叉编译器arm-linux-musleabi与aarch64-linux-musl。 ```shell - # 将执行工具路径加入环境变量 + wget https://musl.cc/arm-linux-musleabi-cross.tgz + wget https://musl.cc/aarch64-linux-musl-cross.tgz + + tar -zxvf arm-linux-musleabi-cross.tgz + tar -zxvf aarch64-linux-musl-cross.tgz + + # 将执行工具路径加入环境变量。 export PATH=$PATH:/path/to/arm-linux-musleabi-cross/bin export PATH=$PATH:/path/to/aarch64-linux-musl-cross/bin ``` - 3. 下载openharmony源代码, - 见[下载说明](../get-code/sourcecode-acquire.md)。 + 3. 下载OpenHarmony源代码,见[下载说明](../get-code/sourcecode-acquire.md)。 2. 通过编译seccomp_filter得到静态分析的依赖文件libsyscall_to_nr_arm与libsyscall_to_nr_arm64。 @@ -362,8 +363,8 @@ swapon;all 3. 复制generate_code_from_policy.py到统计系统调用工具的文件夹内。该脚本存在于//base/startup/init/services/modules/seccomp/scripts/路径下 ```shell - # 进入Openharmony代码根目录 - cd /root/to/OpenharmonyCode; + # 进入OpenHarmony代码根目录 + cd /root/to/OpenHarmonyCode; # 进入generate_code_from_policy.py所在目录 cd base/startup/init/services/modules/seccomp/scripts/; # 复制generate_code_from_policy.py @@ -375,31 +376,40 @@ swapon;all ./build.sh --product-name 产品文件 --ccache --target-cpu arm64 --build-target 目标文件 ``` -5. 修改collect_elf_syscall.py脚本文件,将objdump与readelf工具的路径从空修改为工具在linux环境下的绝对路径。工具路径存放在//prebuilts文件夹下,具体路径一般在//prebuilts/clang/ohos/linux-x86_64/15.0.4/llvm/bin文件夹下。 +5. 若此前未进行全量编译,且第4步依赖的动态库未在//out文件夹下,则通过执行以下命令将业务依赖的相关动态库复制到//out目录下。以下为参考操作,若还依赖其它动态库,请自行复制。 + ```shell + # 先进入代码根目录 + cd /root/to/OpenHarmonyCode + # 在out/产品名称/lib.unstripped/下创建aarch64-linux-ohos文件夹存放依赖的动态库 + mkdir out/产品名称/lib.unstripped/aarch64-linux-ohos + # 复制相关动态库到out目录下 + cp prebuilts/clang/ohos/${host_platform_dir}/llvm/lib/clang/${clang_version}/lib/aarch64-linux-ohos/*.so out/产品名称/lib.unstripped/aarch64-linux-ohos/ + cp prebuilts/clang/ohos/${host_platform_dir}/${clang_version}/llvm/lib/aarch64-linux-ohos/*.so out/产品名称/lib.unstripped/aarch64-linux-ohos/ + ``` + +6. 修改collect_elf_syscall.py脚本文件,将objdump与readelf工具的路径从空修改为工具在linux环境下的绝对路径。脚本文件存放在base/startup/init/services/modules/seccomp/scripts/tools/下。objdump与readelf工具存放在//prebuilts文件夹内部。 ```python #modified the path of objdump and readelf path def get_obj_dump_path(): - obj_dump_path = '/path/to/prebuilts/clang/ohos/linux-x86_64/15.0.4/llvm/bin/llvm-objdump' + obj_dump_path = '/path/to/llvm-objdump' return obj_dump_path def get_read_elf_path(): - read_elf_path = '/path/to/prebuilts/clang/ohos/linux-x86_64/15.0.4/llvm/bin/llvm-readelf' + read_elf_path = '/path/to/llvm-readelf' return read_elf_path ``` -6. 使用脚本解析生成对应的策略文件xxx.seccomp.policy - - 脚本collect_elf_syscall.py在//base/startup/init/services/modules/seccomp/scripts/tools/路径下 +7. 使用脚本解析生成对应的策略文件xxx.seccomp.policy **表7** collect_elf_syscall.py的参数说明 | 参数 | 说明 | | --- | --- | - | --src-elf-path | ELF文件所在文件夹,例如,~/ohcode/out/rk3568,不以'/'结尾| - | --elf-name| ELF文件名,例如,libmedia_service.z.so| - | --src-syscall-path | libsyscall_to_nr_arm或libsyscall_to_nr_arm64,与--target-cpu架构对应 | - | --target-cpu | 架构号,表示需要统计系统调用的对应架构,该参数影响解析何种架构的libc文件,arm或arm64 | - | --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy | + | --src-elf-path | ELF文件所在文件夹,例如,~/ohcode/out/rk3568,不以'/'结尾。| + | --elf-name| ELF文件名,例如,libmedia_service.z.so。| + | --src-syscall-path | libsyscall_to_nr_arm或libsyscall_to_nr_arm64,与--target-cpu架构对应。 | + | --target-cpu | 架构号,表示需要统计系统调用的对应架构,该参数影响解析何种架构的libc文件,arm或arm64。 | + | --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy。 | 使用collect_elf_syscall.py解析ELF文件。 @@ -424,53 +434,8 @@ swapon;all #### Strace统计 1. 使用arm-linux-musleabi与aarch64-linux-musl交叉编译器分别构建32位与64的Strace工具。 -2. [跟踪测试进程](#跟踪测试进程),得到Strace日志。 -3. [跟踪业务进程](#跟踪业务进程),得到Strace日志。 -4. 利用脚本[解析Strace日志](#解析strace日志文件),得到Seccomp策略文件。 -##### 跟踪测试进程 -1. 将Strace工具推入设备中。 - ```shell - hdc shell mount -rw -o remount / - hdc file send /path/to/strace /system/bin/ - hdc shell chmod a+x /system/bin/strace - ``` - -2. 在[开发者测试框架](https://gitee.com/openharmony/testfwk_developer_test)本地代码进行嵌入式修改,使得执行测试套会执行Strace跟踪测试进程。 - - 在src/core/driver/drivers.py修改_init_gtest函数与_run_gtest函数的内容,以下为修改内容。其中行首符号为“+”,则该行为新增内容,若符号为“-”,则是需删除的内容。 - - ```python - --- a/src/core/driver/drivers.py - +++ b/src/core/driver/drivers.py - @@ -500,6 +500,8 @@ class CppTestDriver(IDriver): - "rm -rf %s" % self.config.target_test_path) - self.config.device.execute_shell_command( - "mkdir -p %s" % self.config.target_test_path) - + self.config.device.execute_shell_command( - + "mkdir -p /data/strace") - self.config.device.execute_shell_command( - "mount -o rw,remount,rw /") - if "fuzztest" == self.config.testtype[0]: - @@ -539,10 +541,11 @@ class CppTestDriver(IDriver): - test_para, - seed) - else: - - command = "cd %s; rm -rf %s.xml; chmod +x *; ./%s %s" % ( - + command = "cd %s; rm -rf %s.xml; chmod +x *; strace -ff -o /data/strace/%s.strace.log ./%s %s" % ( - self.config.target_test_path, - filename, - filename, - + filename, - test_para) - else: - coverage_outpath = self.config.coverage_outpath - ``` -3. 执行相关业务测试用例。 -4. 从设备中/data/strace文件夹取出Strace日志。 - ```shell - hdc file recv /data/strace /path/to/base/startup/init/services/modules/seccomp/scripts/tools/ - ``` - +2. [跟踪业务进程](#跟踪业务进程),得到Strace日志。 +3. 利用脚本[解析Strace日志](#解析strace日志文件),得到Seccomp策略文件。 ##### 跟踪业务进程 1. 在init仓代码中进行嵌入式修改,修改文件为//base/startup/init/services/init/init_common_service.c,在执行SetSystemseccompPolicy函数设置Seccomp策略前增加以下内容。以下为修改内容。其中行首符号为“+”,则该行为新增内容,若符号为“-”,则是需删除的内容,“xxxx”与进程[引导启动配置文件](subsys-boot-init-cfg.md)中的Services name保持一致。 ```c @@ -525,16 +490,16 @@ swapon;all cp out/产品名称/gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/strace/ ``` -2. 使用脚本解析生成对应的策略文件xxx.seccomp.policy +2. 使用脚本解析生成对应的策略文件xxx.seccomp.policy。 脚本strace_log_analysis.py在//base/startup/init/services/modules/seccomp/scripts/tools/路径下 **表8** strace_log_analysis.py的参数说明 | 参数 | 说明 | | --- | --- | - | --src-path | 日志文件所在文件夹,需含libsyscall_to_nr_arm与libsyscall_to_nr_arm64例如,./strace,不以'/'结尾| - | --target-cpu | 架构号,与跟踪进程的对应的架构一致,arm或arm64 | - | --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy | + | --src-path | 日志文件所在文件夹,需含libsyscall_to_nr_arm与libsyscall_to_nr_arm64例如,./strace,不以'/'结尾。| + | --target-cpu | 架构号,与跟踪进程的对应的架构一致,arm或arm64。 | + | --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy。 | 使用strace_log_analysis.py解析Strace日志。 ```shell @@ -562,7 +527,7 @@ swapon;all ```shell mkdir -p /data/audit ``` - 2. 利用Shell命令获取内核日志中与Seccomp相关的Audit日志,存放的日志以“.audit.log”结尾 + 2. 利用Shell命令获取内核日志中与Seccomp相关的Audit日志,存放的日志以“.audit.log”结尾。 ```shell cat /proc/kmsg | grep type=1326 > /data/audit/media_service.audit.log ``` @@ -591,30 +556,29 @@ swapon;all Audit日志示例 ```shell - <5>[ 198.963101] audit: type=1326 audit(1659528178.748:27): auid=4294967295 uid=0 gid=1000 ses=4294967295 subj=u:r:appspawn:s0 pid=2704 comm="config_dialog_s" exe="/system/bin/appspawn" sig=31 arch=40000028 syscall= - 208 compat=1 ip=0xf7b79400 code=0x80000000 + <5>[ 198.963101] audit: type=1326 audit(1659528178.748:27): auid=4294967295 uid=0 gid=1000 ses=4294967295 subj=u:r:appspawn:s0 pid=2704 comm="config_dialog_s" exe="/system/bin/appspawn" sig=31 arch=40000028 syscall=208 compat=1 ip=0xf7b79400 code=0x80000000 ``` **表9** Audit日志关键字段说明 | 参数 | 说明 | | --- | --- | - | type | 类型,值为1326说明是seccomop类型日志 | - | sig | 信号量,31为SIGSYS,表示Seccomp发生拦截时给进程发出的信号 | - | arch | 架构标识,值为40000028表示arm,值为c00000b7表示arm64 | + | type | 类型,值为1326说明是seccomop类型日志。 | + | sig | 信号量,31为SIGSYS,表示Seccomp发生拦截时给进程发出的信号。 | + | arch | 架构标识,值为40000028表示arm,值为c00000b7表示arm64。 | | syscall | 系统调用号 | - | compat | 1表示为兼容模式,即arm64的内核使用了arm的系统调用 | + | compat | 1表示为兼容模式,即arm64的内核使用了arm的系统调用。 | 1. 将解析日志时所依赖的文件复制到日志文件夹以备使用,该依赖文件为[静态分析](#静态分析)第2步的产物。 ```shell cp out/产品名称/gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/audit/ ``` - 2. 使用audit_log_analysis.py脚本解析日志生成xxx.seccomp.policy。工具路径在//base/startup/init/services/modules/seccomp/scripts/tools/下 + 2. 使用audit_log_analysis.py脚本解析日志生成xxx.seccomp.policy。工具路径在//base/startup/init/services/modules/seccomp/scripts/tools/下。 **表10** audit_log_analysis.py的参数说明 | 参数 | 说明 | | --- | --- | - | --src-path | 日志文件所在文件夹,需含libsyscall_to_nr_arm与libsyscall_to_nr_arm64。例如,./audit,不以'/'结尾| - | --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy | + | --src-path | 日志文件所在文件夹,需含libsyscall_to_nr_arm与libsyscall_to_nr_arm64。例如,./audit,不以'/'结尾。| + | --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy。 | ```shell cd base/startup/init/services/modules/seccomp/scripts/tools @@ -627,13 +591,13 @@ swapon;all **表11** merge_policy.py的参数说明 | 参数 | 说明 | | --- | --- | -| --src-files | 需处理的文件,需含libsyscall_to_nr_arm与libsyscall_to_nr_arm64| -| --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy | +| --src-files | 需处理的文件,需含libsyscall_to_nr_arm与libsyscall_to_nr_arm64。 | +| --filter-name | 生成的策略文件名名称,例如,输入值为test,生成的文件名为test.seccomp.policy。 | 1. 将合并文件所依赖的文件复制到日志文件夹以备使用。 ```shell cp out/产品名称/gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/ ``` -2. 使用merge_policy.py将policy1.seccomp.policy,policy2.seccomp.policy策略文件合并成xxxx.seccomp.policy +2. 使用merge_policy.py将policy1.seccomp.policy,policy2.seccomp.policy策略文件合并成xxxx.seccomp.policy。 ```shell python3 merge_policy.py --src-files libsyscall_to_nr_arm --src-files libsyscall_to_nr_arm64 --src-files policy1.seccomp.policy --src-files policy2.seccomp.policy --filter-name xxxx ``` \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-build-all.md b/zh-cn/device-dev/subsystems/subsys-build-all.md index b6bddb7fb95fef31be91e2c937ec6692e78eb1bc..3da6fa6c5cc7feefdbdcb7d52160f418310629a1 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-all.md +++ b/zh-cn/device-dev/subsystems/subsys-build-all.md @@ -105,6 +105,7 @@ OpenHarmony编译子系统是以GN和Ninja构建为基座,对构建和配置 - [子系统配置规则](subsys-build-subsystem.md#子系统配置规则) - [部件配置规则](subsys-build-component.md#部件配置规则) - [模块配置规则](subsys-build-module.md#模块配置规则) +- [Rust模块配置规则](subsys-build-rust-compilation.md#Rust模块配置规则) - [芯片解决方案配置规则](subsys-build-chip_solution.md#芯片解决方案配置规则) - [特性配置规则](subsys-build-feature.md#特性配置规则) - [系统能力配置规则](subsys-build-syscap.md#如何按需配置部件的系统能力) diff --git a/zh-cn/device-dev/subsystems/subsys-build-cargo2gn-guide.md b/zh-cn/device-dev/subsystems/subsys-build-cargo2gn-guide.md index 1bd28164b41007f94187a2ab7459bfd79aeec40b..3071cb6508db35dc7185e7bbaa5434bbeae90670 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-cargo2gn-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-build-cargo2gn-guide.md @@ -12,7 +12,7 @@ rust三方库使用cargo编译,配置为Cargo.toml。集成到OpenHarmony上 2. 创建配置文件cargo2gn.json,可以参考如下配置。 - ``` + ```json { "copy-out": true, "run": true, @@ -24,7 +24,7 @@ rust三方库使用cargo编译,配置为Cargo.toml。集成到OpenHarmony上 3. 执行以下命令进行转换。 ``` - python /mnt/xxx/openharmony/build/scripts/cargo2gn.py --config cargo2gn.json + python3 /mnt/xxx/openharmony/build/scripts/cargo2gn.py --config cargo2gn.json ``` 转换结果 @@ -83,7 +83,7 @@ rust三方库使用cargo编译,配置为Cargo.toml。集成到OpenHarmony上 ``` 2. 把所有需要转换的rust三方库添加到rust目录下的Cargo.toml的[workspace]里,如下所示。 - ``` + ```toml [workspace] members = [ "aho-corasick", diff --git a/zh-cn/device-dev/subsystems/subsys-build-rust-compilation.md b/zh-cn/device-dev/subsystems/subsys-build-rust-compilation.md index 1fc2e56d6d6f306e3ce279b4e1fc460afd3ee577..ab5bbfc1008c2f2bea1d16a12849f9e29663f63a 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-rust-compilation.md +++ b/zh-cn/device-dev/subsystems/subsys-build-rust-compilation.md @@ -12,7 +12,7 @@ OpenHarmony为了集成C/C++代码和提升编译速度,使用了GN + Ninja的 | ----- | ------------------------------------------------------------ | | Cargo | Cargo是Rust官方使用的构建工具,允许Rust项目声明其各种依赖项,并确保您始终获得可重复的构建。 | | crate | crate是一个独立的可编译单元。 | -| lints | lints 是指出常见编程错误、错误、样式错误和可疑结构的工具。可以对程序进行更加广泛的错误分析。 | +| Lint | Lint是指出常见编程错误、错误、样式错误和可疑结构的工具。可以对程序进行更加广泛的错误分析。 | @@ -100,6 +100,9 @@ OpenHarmony提供了用于Rust代码编译构建的各类型GN模板,可以用 ![test_rlib_crate](./figures/test_rlib_crate.png) ### 配置三方库示例 + +rust三方库的BUILD.gn文件可通过cargo2gn工具自动生成。参见:[Cargo2gn工具操作指导](subsys-build-cargo2gn-guide.md) + 该示例用于测试包含预编译文件build.rs的三方静态库rlib文件的编译,使用了模板ohos_rust_executable和ohos_rust_cargo_crate。操作步骤如下: 1. 创建build/rust/tests/test_rlib_cargo_crate/crate/src/lib.rs,如下所示: @@ -301,26 +304,27 @@ OpenHarmony提供了用于Rust代码编译构建的各类型GN模板,可以用 在build/rust/tests目录下有Rust各类型模块的配置实例可供参考: | 用例目录 | 测试功能 | | -------------------------------------------- | ------------------------------------------------------------ | -| build/rust/tests/test_bin_crate | 测试ohos_rust_executable的host和target编译链接及运行 | -| build/rust/tests/test_static_link | 测试ohos_rust_executable对libstd.rlib进行静态链接 | -| build/rust/tests/test_dylib_crate | 测试ohos_rust_executable对ohos_rust_shared_library的编译依赖和运行 | -| build/rust/tests/test_rlib_crate | 测试ohos_rust_executable对ohos_rust_static_library的编译依赖和运行 | -| build/rust/tests/test_proc_macro_crate | 测试ohos_rust_executable对ohos_rust_proc_macro的编译依赖和运行,对不同类型都有用例覆盖 | -| build/rust/tests/test_cdylib_crate | 测试ohos_rust_executable对ohos_rust_shared_ffi的编译依赖和运行 | -| build/rust/tests/test_staticlib_crate | 测试ohos_rust_executable对ohos_rust_static_ffi的编译依赖和运行 | -| build/rust/tests/test_rust_ut | 测试ohos_rust_unittest,用例代码与特性代码在同一个文件中 | -| build/rust/tests/test_rust_st | 测试ohos_rust_systemtest,用例代码在独立的test目录中 | -| build/rust/tests/test_bin_cargo_crate | 测试ohos_cargo_crate对拥有build.rs预编译的可执行文件编译链接和运行,适用于rust三方crate编译依赖 | -| build/rust/tests/test_rlib_cargo_crate | 测试ohos_cargo_crate对拥有build.rs预编译的静态库文件编译链接和运行,适用于rust三方crate编译依赖 | -| build/rust/tests/test_proc_macro_cargo_crate | 测试ohos_cargo_crate对拥有build.rs预编译的过程宏编译链接和运行,适用于rust三方crate编译依赖 | +| build/rust/tests/test_bin_crate | 用ohos_rust_executable模板在host平台编译可执行文件,在target平台上运行可执行文件。 | +| build/rust/tests/test_static_link | 测试可执行文件对标准库的静态链接。 | +| build/rust/tests/test_dylib_crate | 测试对动态库的编译和动态链接功能 | +| build/rust/tests/test_rlib_crate | 测试对静态库的编译和静态链接功能 | +| build/rust/tests/test_proc_macro_crate | 测试对Rust过程宏的编译和链接功能。提供对不同类型的宏的测试用例。 | +| build/rust/tests/test_cdylib_crate | 测试将Rust代码编译成C/C++动态库。 | +| build/rust/tests/test_staticlib_crate | 测试将Rust代码编译成C/C++静态库。 | +| build/rust/tests/test_rust_ut | 测试Rust代码单元测试模板功能(ability)。 | +| build/rust/tests/test_rust_st | 测试Rust代码系统测试模板功能(ability)。 | +| build/rust/tests/test_bin_cargo_crate | 测试Rust三方可执行文件的编译和运行。三方源码中包含build.rs。 | +| build/rust/tests/test_rlib_cargo_crate | 测试Rust三方静态库的编译和静态链接。三方源码中包含build.rs。 | +| build/rust/tests/test_proc_macro_cargo_crate | 测试Rust三方过程宏的编译和链接。三方源码中包含build.rs。 | ## 参考 ### 特性点实例 #### Rust源码依赖调用C/C++库 -OpenHarmony上C/C++模块动态库默认用.z.so后缀,但是Rust的编译命令通过-l链接时,默认只会链接.so后缀的动态库。因此如果要依赖一个C/C++动态库编译模块,需要在该动态库的GN构建文件中添加output_externsion = "so"的声明,这样编译得到的动态库将会以".so"作为后缀,而不是".z.so"。 +OpenHarmony上C/C++模块动态库默认用.z.so后缀,但是Rust的编译命令通过-l链接时,默认只会链接.so后缀的动态库。因此如果要依赖一个C/C++动态库编译模块,需要在该动态库的GN构建文件中添加output_extension = "so"的声明,这样编译得到的动态库将会以".so"作为后缀,而不是".z.so"。 在Rust源码中如果直接链接动态库,后缀也需要使用".so",这时使用动态库的中间名,不需要添加lib前缀。例如Rust源码中链接libhilog.so: + ```rust #[link(name = "hilog")] ``` @@ -335,10 +339,11 @@ executable("foo") { }] } ``` -### lints规则 -OpenHarmony框架支持rustc lints和clippy lints两种lints,每种lints划为三个等级的标准:"openharmony"、"vendor"和"none",严格程度按照"openharmony" -> "vendor" -> "none"逐级递减。 -配置Rust模块时可以通过rustc_lints和clippy_lints来指定使用lints的等级。 +### Lint规则 +OpenHarmony框架支持rustc lints和clippy lints两种Lint,每种Lint划为三个等级的标准:"openharmony"、"vendor"和"none",严格程度按照"openharmony" -> "vendor" -> "none"逐级递减。 +配置Rust模块时可以通过rustc_lints和clippy_lints来指定使用Lint的等级。 模块中没有配置rustc_lints或者clippy_lints时会根据模块所在路径来匹配lints等级。不同路径下的Rust代码的语法规范会有不同程度地约束,因此用户在OpenHarmony配置Rust代码编译模块时还应关注模块所在路径。 + #### rustc lints和clippy lints的各等级标志 | **lints类型** | **模块属性** | **lints等级** | **lints等级标志** | **lints内容** | | ------------- | ------------ | ------------- | ----------------- | ------------------------------------------------------------ | @@ -358,3 +363,5 @@ OpenHarmony框架支持rustc lints和clippy lints两种lints,每种lints划为 | device | vendor | | others | openharmony | +### [交互工具使用指导](subsys-build-bindgen-cxx-guide.md) +### [Cargo2gn工具操作指导](subsys-build-cargo2gn-guide.md) diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md index 58a4e82fea85f151a2101dd586adec0c520bed21..f8ccc1315303b939369d570fa967b89a0a9d2430 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md @@ -279,6 +279,7 @@ HiTraceMeter提供了可执行的二进制程序hitrace,设备刷openharmony | --trace_begin | 启动抓trace | | --trace_dump | 将数据输出到指定位置(默认控制台) | | --trace_finish | 停止抓trace,并将数据输出到指定位置(默认控制台) | +| --trace_finish_nodump | 停止抓trace,不输出trace信息 | | -l,--list_categories | 输出手机能支持的trace模块 | | --overwrite | 当缓冲区满的时候,将丢弃最新的信息。(默认丢弃最老的日志) | | -o filename,--output filename | 指定输出的目标文件名称 | diff --git a/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md b/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md index 920b47ea9c60fdb3b23b46419991764370ecb019..eb4a809978709dfdfa008d2cf5f4b05f1b042a12 100755 --- a/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md @@ -1,35 +1,73 @@ -# 预置应用配置指南 +# 预置应用配置与安装指导 -OpenHarmony支持在不同产品上对预置应用进行差异化配置,设备厂商可根据需要对预置应用进行配置。 +预置应用是指随设备出厂预置的应用。OpenHarmony支持在不同设备上对预置应用进行差异化配置,设备厂商可根据需要对与预置应用进行配置。 -此外,OpenHarmony根据GetCfgDirList获得系统支持的预置目录,如system、chipset、sys_prod、chip_prod;并且按照返回的顺序越靠后优先级越高,如chip_prod的优先级高于system的优先级。 +## 将应用配置为预置应用 -## 预置应用安装列表配置 +1. 在进行预置应用配置前,使用如下命令查询系统支持的预置目录。 + + 命令查询结果如system、chipset、sys_prod、chip_prod等,并且返回的顺序越靠后优先级越高,如chip_prod的优先级高于system的优先级。本文以路径/system/etc/app/为例。 -### 应用预置到系统中的配置步骤 +``` +hdc shell param get const.cust.config_dir_layer +``` + +2. 在install_list.json中配置hap在设备上的路径。 -1. 在预置目录下创建应用的名称作为应用目录 -2. 将应用预置到应用目录下,如 /system/app/Hiworld/entry.hap -3. 添加应用目录到[install_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list.json),根据需求配置removable +``` +hdc shell mount -o rw,remount / +hdc file recv /system/etc/app/install_list.json . +``` -### 示例 +3. 按照json中的配置方式,配置对应的字段。 ``` { "install_list" : [ { - "app_dir" : "/system/app/Hiworld", - "removable" : false // 是否可卸载 + "app_dir":"system/app/xxxx/yyyy", // 设备上的hap路径,如果不存在,需要手动创建,并推送hap到此目录。 + "removable":true // 是否支持卸载,false表示不可卸载,true表示可以卸载。 } ] } ``` -## 预置不安装列表配置 +4. 修改完成后,将install_list.json文件推送到设备上,并重启设备生效。 + +``` + hdc shell mount -o rw,remount / + hdc file send install_list.json /system/etc/app/install_list.json + hdc shell reboot +``` + +## 更新预置应用 + +预置应用更新后,使用如下方法重新安装。 + +- 方法一:直接清空data,重启设备,应用会自动安装。 + +``` + hdc shell mount -o rw,remount / + hdc shell rm /data/* -rf + hdc shell sync + hdc shell /system/bin/udevadm trigger + hdc shell reboot +``` +- 方法二:执行如下命令,重启设备,应用即可安装。 + + 如果应用之前已经安装过,这时推送新的hap到/system/app/路径下,需保证应用的版本号(Stage模型下对应app.json5配置文件中的[versionCode](../../application-dev/quick-start/app-configuration-file.md)标签;FA模型下对应配置文件中的[code](../../application-dev/quick-start/app-structure.md#version对象内部结构)标签)大于之前的版本号。 + +``` + hdc shell mount -o rw,remount / + hdc shell param set persist.bms.test-upgrade true + hdc shell reboot +``` + +# 预置不安装列表配置 [uninstall_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/uninstall_list.json)的配置优先级高于install_list.json,在该文件中配置后,则对应的预置应用不会安装。 -### 示例一 +## 示例一 ``` /system/etc/app/uninstall_list.json @@ -39,7 +77,7 @@ OpenHarmony支持在不同产品上对预置应用进行差异化配置,设备 } ``` -### 示例二 +## 示例二 ``` /system/etc/app/uninstall_list.json diff --git a/zh-cn/release-notes/Readme.md b/zh-cn/release-notes/Readme.md index 1aeb73131e25262d597a4166b458f668eca6c6cf..8b55d4ec39811fdd4d7a937e9daf689003445272 100644 --- a/zh-cn/release-notes/Readme.md +++ b/zh-cn/release-notes/Readme.md @@ -2,6 +2,7 @@ ## OpenHarmony 3.x Releases - [OpenHarmony v3.2 Release (2023-04-09)](OpenHarmony-v3.2-release.md) +- [OpenHarmony v3.2.1 Release (2023-05-22)](OpenHarmony-v3.2.1-release.md) - [OpenHarmony v3.2 Beta5 (2023-01-31)](OpenHarmony-v3.2-beta5.md) - [OpenHarmony v3.2 Beta4 (2022-11-30)](OpenHarmony-v3.2-beta4.md) - [OpenHarmony v3.2 Beta3 (2022-09-30)](OpenHarmony-v3.2-beta3.md)