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 63d7d26d47b64407e30fc03c2edb7ead210dc392..4ecdf35ead5482d4b4b2e0d0a2a4544e75686612 100644 --- a/en/application-dev/application-models/data-share-via-want.md +++ b/en/application-dev/application-models/data-share-via-want.md @@ -56,20 +56,20 @@ Users often need to share data (such as a text or an image) from one application } } } - ``` - - In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved: - + ``` + + In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved: + - **"ability.picker.type"**: The application selector renders the file type icon based on this field. - **"ability.picker.fileNames"**: The application selector displays the file name based on this field. - **"ability.picker.fileSizes"**: The application selector displays the file size based on this field. The unit is byte. - - **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping. - + - **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping. + For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows: - + stage-want2 - In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Implicit Want Matching Rules](explicit-implicit-want-mappings.md#interpretation-of-implicit-want-matching-rules). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application. + In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application. - Shared party 1. As mentioned above, the application selector performs implicit matching based on the **ability.want.params.INTENT** field. Therefore, you must set **skills** in the ability configuration file (**module.json5** file in the stage model) of the shared party as follows: diff --git a/en/application-dev/application-models/redirection-rules.md b/en/application-dev/application-models/redirection-rules.md index c5c9987c261364f87dadc0333b310744fe12f971..d7456653640942bca333a28f7f6d5262ec4d63f3 100644 --- a/en/application-dev/application-models/redirection-rules.md +++ b/en/application-dev/application-models/redirection-rules.md @@ -33,4 +33,4 @@ To enable an ability to be called by any application, configure the **config.jso ``` -If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#interpretation-of-implicit-want-matching-rules) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant. +If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant. diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index 064c3e393fe27cedceb1f3f7d2d1e03b8ec22db6..95001df839e0d5ef56bc12126f0fdcd59c72db30 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share |query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.| |delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.| -For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). +For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md). **Table 2** APIs of the data consumer @@ -29,7 +29,7 @@ For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataS ## When to Use -There are two roles in **DataShare**: +There are two roles in **DataShare**: - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data consumer: accesses the data provided by the provider using **DataShareHelper**. @@ -108,8 +108,8 @@ Examples are given below. | ------------ | ------------------------------------------------------------ | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.| - | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | - | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| + | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | + | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | **module.json5 example** @@ -129,10 +129,10 @@ Examples are given below. ### Data Consumer Application Development -1. Import the dependencies. +1. Import dependencies. ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` @@ -150,7 +150,7 @@ Examples are given below. let dsHelper; let abilityContext; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { abilityContext = this.context; dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{ @@ -180,7 +180,7 @@ Examples are given below. dsHelper.query(dseUri, predicates, valArray, (err, data) => { console.log("dsHelper query result: " + data); }); - // Delete data. + // Delete specified data. dsHelper.delete(dseUri, predicates, (err, data) => { console.log("dsHelper delete result: " + data); }); diff --git a/en/application-dev/device/device-location-geocoding.md b/en/application-dev/device/device-location-geocoding.md deleted file mode 100644 index e18c3fbcce93e40b87c3af9e473b3e1b2828fd4c..0000000000000000000000000000000000000000 --- a/en/application-dev/device/device-location-geocoding.md +++ /dev/null @@ -1,87 +0,0 @@ -# Geocoding and Reverse Geocoding Capabilities - - -## When to Use - -Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. - -The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address. - - -## Available APIs - -The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md). - - **Table1** APIs for geocoding and reverse geocoding - -| API | Description | -| -------- | -------- | -| isGeocoderAvailable(): boolean; | Checks whether the (reverse) geocoding service is available.| -| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. | -| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>> | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. | - - -## How to Develop - -> **NOTE** -> -> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network. - -1. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. - - ```ts - import geoLocationManager from '@ohos.geolocation'; - ``` - -2. Query whether geocoder service is available. - - Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3. - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - try { - var isAvailable = geoLocationManager.isGeocoderAvailable(); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - -3. Obtain the conversion result. - - Call **getAddressesFromLocation** to convert coordinates into geographical location information. - - ```ts - var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; - try { - geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); - } - }); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). - - Call **getAddressesFromLocationName** to convert geographic description into coordinates. - - ```ts - var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; - try { - geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); - } - }); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). - - To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**. diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md deleted file mode 100644 index 1a386fe6bbfd44009b3aa8ab5ea48e36ad87f3c3..0000000000000000000000000000000000000000 --- a/en/application-dev/device/device-location-info.md +++ /dev/null @@ -1,145 +0,0 @@ -# Obtaining Device Location Information - - -## When to Use - -You can call location-related APIs in OpenHarmony to obtain the real-time location or last known location of a mobile device. - -Real-time location of the device is recommended for location-sensitive services. If you want to lower power consumption when the real-time location of the device is not needed, you may consider obtaining the last known location of the device. - - -## Available APIs - -For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md). - -## How to Develop - -To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geoLocationManager.md). - -1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. - The system provides the following location permissions: - - ohos.permission.LOCATION - - - ohos.permission.APPROXIMATELY_LOCATION - - - ohos.permission.LOCATION_IN_BACKGROUND - - If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: - - API versions earlier than 9: Apply for **ohos.permission.LOCATION**. - - API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. - - | Target API Level| Location Permission| Permission Application Result| Location Accuracy| - | -------- | -------- | -------- | -------- | - | Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| - | 9 and later| ohos.permission.LOCATION | Failure| No location obtained| - | 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| - | 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| - - If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. - - You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md). - -2. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities. - - ```ts - import geoLocationManager from '@ohos.geolocation'; - ``` - -3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.
- **Method 1:** - - To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported. - - - ``` - export enum LocationRequestScenario { - UNSET = 0x300, - NAVIGATION, - TRAJECTORY_TRACKING, - CAR_HAILING, - DAILY_LIFE_SERVICE, - NO_POWER, - } - ``` - - - **Table 2** Common use cases of the location function - - | Use Case | Constant | Description | - | ------------ | ------------------- | ------------------------------------------------------------ | - | Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - - Sample code for initializing **requestInfo** for navigation: - - ```ts - var requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - ``` - - **Method 2:** - - If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system. - - - ```ts - export enum LocationRequestPriority { - UNSET = 0x200, - ACCURACY, - LOW_POWER, - FIRST_FIX, - } - ``` - - - **Table 3** Location priority policies - - | Policy | Constant | Description | - | ------------------ | -------------- | ------------------------------------------------------------ | - | Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.| - - Sample code for initializing **requestInfo** for the location accuracy priority policy: - - ```ts - var requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - ``` - -4. Instantiate the **Callback** object for the system to report location results. - Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic. - - ```ts - var locationChange = (location) => { - console.log('locationChanger: data: ' + JSON.stringify(location)); - }; - ``` - -5. Start device location. - - ```ts - geoLocationManager.on('locationChange', requestInfo, locationChange); - ``` - -6. (Optional) Stop device location. - - ```ts - geoLocationManager.off('locationChange', locationChange); - ``` - -If your application does not need the real-time device location, it can use the last known device location cached in the system instead. - - ```ts - import geoLocationManager from '@ohos.geoLocationManager'; - try { - var location = geoLocationManager.getLastLocation(); - } catch (err) { - console.error("errCode:" + err.code + ",errMessage:" + err.message); - } - ``` - - To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user. diff --git a/en/application-dev/device/device-location-overview.md b/en/application-dev/device/device-location-overview.md deleted file mode 100644 index a26f0c5a7003a14c13cf4fc697e3a55a202f1eec..0000000000000000000000000000000000000000 --- a/en/application-dev/device/device-location-overview.md +++ /dev/null @@ -1,48 +0,0 @@ -# Location Overview - - -People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices. - - -With the location awareness capability offered by , mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users. - - -Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording. - - -## Basic Concepts - -Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors. - -- **Coordinate** - - A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. - -- **GNSS positioning** - GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. - -- **Base station positioning** - - Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. - -- **WLAN or Bluetooth positioning** - - WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. - - -## Working Principles - -Location awareness is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a location request to the system and stop the location request when the service scenario ends. In this process, the system reports the location information to the application on a real-time basis. - - -## Limitations and Constraints - -Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application. - -Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information. - -## Samples - -The following sample is provided to help you better understand how to develop location services: - --[`Location`: Location (eTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location) diff --git a/en/application-dev/device/inputdevice-guidelines.md b/en/application-dev/device/inputdevice-guidelines.md index d29d1ae340f5f2c569559791fe2b001e07adce4a..da6eef71d750b74e01d1ea8a9eaaf49b1bf598cb 100644 --- a/en/application-dev/device/inputdevice-guidelines.md +++ b/en/application-dev/device/inputdevice-guidelines.md @@ -16,8 +16,8 @@ The following table lists the common APIs for input device management. For detai | Instance| API | Description| | ----------- | ------------------------------------------------------------ | -------------------------- | -| inputDevice | function getDeviceList(callback: AsyncCallback\>): void; | Obtains the list of input devices.| -| inputDevice | function getKeyboardType(deviceId: number, callback: AsyncCallback\): void; | Obtains the keyboard type of the input device.| +| inputDevice | function getDeviceList(): Promise\>; | Obtains the list of input devices.| +| inputDevice | function getKeyboardType(deviceId: number): Promise\; | Obtains the keyboard type of the input device.| | inputDevice | function on(type: "change", listener: Callback\): void; | Enables listening for device hot swap events.| | inputDevice | function off(type: "change", listener?: Callback\): void; | Disables listening for device hot swap events.| @@ -51,7 +51,7 @@ try { // 2. Listen for device hot swap events. inputDevice.on("change", (data) => { console.log(`Device event info: ${JSON.stringify(data)}`); - inputDevice.getKeyboardType(data.deviceId, (error, type) => { + inputDevice.getKeyboardType(data.deviceId).then((type) => { console.log("The keyboard type is: " + type); if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { // The physical keyboard is inserted. diff --git a/en/application-dev/faqs/faqs-event-notification.md b/en/application-dev/faqs/faqs-event-notification.md index 06a811e0ca13d1bf8f634a65593a2424ad3999bd..496abb06928728e6275feff3dc423964060701f5 100644 --- a/en/application-dev/faqs/faqs-event-notification.md +++ b/en/application-dev/faqs/faqs-event-notification.md @@ -16,15 +16,15 @@ Reference: [Notification](../reference/apis/js-apis-notification.md#notification Example: -``` +```ts import WantAgent from '@ohos.wantAgent'; async function publishNotification() { let wantAgentInfo = { wants: [ { - bundleName: "com.example.notification", - abilityName: "MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", } ], operationType: WantAgent.OperationType.START_ABILITIES, diff --git a/en/application-dev/faqs/faqs-language.md b/en/application-dev/faqs/faqs-language.md index db7e95d5ede5c3bead52e16bceb16e90c6188b79..22a450b4c8e37dc85a28c2ea3b972b03d6ea16ae 100644 --- a/en/application-dev/faqs/faqs-language.md +++ b/en/application-dev/faqs/faqs-language.md @@ -155,7 +155,9 @@ The global function **encodeURI** is used for URI encoding, and **decodeURI** is Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 -Yes. The **convert** API of the **convertxml** module can be used to convert XML text into JavaScript objects. Reference: [@ohos.convertxml](../reference/apis/js-apis-convertxml.md) +Yes. The **convert** API of the **convertxml** module can be used to convert XML text into JavaScript objects. + +Reference: [@ohos.convertxml](../reference/apis/js-apis-convertxml.md) ## How do I configure application icons to be used across devices? @@ -287,4 +289,4 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 No. Relational database operations cannot be performed in the worker thread. - \ No newline at end of file + \ No newline at end of file diff --git a/en/application-dev/faqs/faqs-ui-ets.md b/en/application-dev/faqs/faqs-ui-ets.md index 074a404683bda39d3e5499c66bb193d97784c4dd..8564d2f0969a2cf6eac9bb2d9ac521e62045d162 100644 --- a/en/application-dev/faqs/faqs-ui-ets.md +++ b/en/application-dev/faqs/faqs-ui-ets.md @@ -165,9 +165,9 @@ Before the window content is loaded, enable listening for the **systemAvoidAreaC Example: -``` -// MainAbility.ts -import window from '@ohos.window'; +```ts +import Window from '@ohos.window'; +import UIAbility from '@ohos.app.ability.UIAbility'; /** * Set the immersive window and obtain the height of the status bar and navigation bar. @@ -187,7 +187,7 @@ async function enterImmersion(mainWindow: window.Window) { statusBarContentColor: "#FF0000" }) } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { // do something async onWindowStageCreate(windowStage: window.WindowStage) { let mainWindow = await windowStage.getMainWindow() @@ -213,7 +213,7 @@ You can obtain the changes in the width and height of a component through **onAr Example: -``` +```ts Column() { Text(this.value) .backgroundColor(Color.Green).margin(30).fontSize(20) @@ -235,7 +235,7 @@ Bind the **\** component to a **Scoller** object and obtain the offset thr Example: -``` +```ts Column() { List({ space: 20, initialIndex: 0,scroller: this.scroller}) { ForEach(this.arr, (item) => { @@ -259,7 +259,7 @@ Column() { Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 -``` +```ts // In versions earlier than 3.1.5.5, obtain the value through router.getParams().key. private value: string = router.getParams().value; // In 3.1.6.5 and later versions, obtain the value through router.getParams()['key']. @@ -299,7 +299,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 The color can be represented in two formats, for example, 0x7F000000 or '\#7F000000'. The first two digits indicate opacity, and the last six digits indicate RGB. -``` +```ts fontColor(0x7F000000) fontColor( '#7F000000' ) ``` diff --git a/en/application-dev/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md index fff002316e8ad2364dedd6c870d3a64ca234a94b..4aa7c9af2c977aac2a987de80bad2b6f164b1215 100644 --- a/en/application-dev/file-management/Readme-EN.md +++ b/en/application-dev/file-management/Readme-EN.md @@ -7,3 +7,4 @@ - File Access Framework - [File Access Framework Overview](file-access-framework-overview.md) +- [FilePicker Guide](filepicker-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/file-management/filepicker-guidelines.md b/en/application-dev/file-management/filepicker-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..8fcf96b2219151a9c197cd1f6bc2e738775646b7 --- /dev/null +++ b/en/application-dev/file-management/filepicker-guidelines.md @@ -0,0 +1,68 @@ +# FilePicker Guide + +FilePicker is a system application preset in OpenHarmony. You can use it to select and save files. For details about the implementation of FilePicker, see [applications_filepicker](https://gitee.com/openharmony/applications_filepicker). + +FilePicker provides the following modes: +- **choose**: Use this mode when an application needs to select and upload or send files (including media resources such as images, and audio and video clips) in the device. When this mode is selected, the FilePicker **choose** mode window will be triggered to display a dialog box for you to select a file. You can select the target file and tap **Upload**. The application will receive the URI of the target file returned by FilePicker. +- **save**: Use this mode when an application needs to download and save files (including media resources such as images and audio and video clips). When this mode is selected, the FilePicker **save** mode window will be triggered to display a dialog box for you to select the destination path of the file to save. You can select the destination path and tap **Save**. The application will receive the URI of the saved file returned by FilePicker. + +## Development Guidelines + +> **NOTE** +> +> FilePicker supports only the applications developed based on the stage model. +> For details about the stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). + +You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-ability-context.md##abilitycontextstartabilityforresult-1) with different parameters to start different FilePicker modes. + +You need to use [Want](../reference/apis/js-apis-application-want.md) to specify **bundleName** and **abilityName** to start FilePicker. For details, see the following sample code. + +You also need to set **Want.parameters** to specify the FilePicker mode to start and the name of the file to save. +- To select a file, set **'startMode': 'choose'**. +- To save a file, set **'startMode': 'save'** and **'saveFile'**. + +You can set **options** of the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) type to specify the dialog box style. The recommended value is **windowMode: 102**, which indicates a floating window. + +> **CAUTION** +> - In the **save** mode, a strong verification is performed on the file path based on the name of the file to save. For details about the file path format, see [File Path Management](medialibrary-filepath-guidelines.md). +> - If a file with the same name exists, a dialog box will be displayed asking you whether to overwrite the existing file. + +ArkTS sample code: +```ts +// Start FilePicker to select a file. +globalThis.context.startAbilityForResult( + { + bundleName: "com.ohos.filepicker", + abilityName: "EntryAbility", + parameters: { + 'startMode': 'choose', //choose or save + } + }, + { windowMode: 102 } +) + +// Start FilePicker to save a file. +globalThis.context.startAbilityForResult( + { + bundleName: "com.ohos.filepicker", + abilityName: "EntryAbility", + parameters: { + 'startMode': 'save', //choose or save + 'saveFile': 'test.jpg', + } + }, + { windowMode: 102 } +) + +// Data returned by FilePicker to startAbilityForResult. +let abilityResult = { + resultCode: resultCode, + want: { + parameters: { + 'startMode': startMode, + 'result': result + } + } +} +globalThis.context.terminateSelfWithResult(abilityResult) +``` diff --git a/en/application-dev/internationalization/Readme-EN.md b/en/application-dev/internationalization/Readme-EN.md index d7042968cf5c6824e49f77911e207e4cbb4be443..6c89740e15daf19fcb712aba339484caad2ed7c3 100644 --- a/en/application-dev/internationalization/Readme-EN.md +++ b/en/application-dev/internationalization/Readme-EN.md @@ -1,6 +1,6 @@ # Internationalization - [Internationalization Overview](international-overview.md) -- [Internationalization Development (intl)](intl-guidelines.md) -- [Internationalization Development (i18n)](i18n-guidelines.md) +- [intl Development](intl-guidelines.md) +- [i18n Development](i18n-guidelines.md) diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 62bf66fd7cabb7e30c765126ddacba639bd951f5..8218f2561376c4119f66be0175c5c9ea16c7d024 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -1,391 +1,732 @@ -# Internationalization Development (I18N) +# i18n Development -This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For more details about APIs and their usage, see [I18N](../reference/apis/js-apis-i18n.md). +The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For more details about APIs and their usage, see [i18n](../reference/apis/js-apis-i18n.md). -## Obtaining System Language and Region Information +The [intl](intl-guidelines.md) module provides basic i18n capabilities through the standard i18n interfaces defined in ECMA 402. It works with the **i18n** module to provide a complete suite of i18n capabilities. -You can use APIs provided in the following table to obtain the system language and region information. +## Obtaining and Setting i18n Information +The system provides APIs to configure information such as the system language, preferred language, country or region, 24-hour clock, and local digit switch. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | -| ohos.i18n | getSystemRegion(): string | Obtains the system region. | -| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | -| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | -| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | -| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | - +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------- | +| System | getDisplayCountry(country:string,locale:string,sentenceCase?:boolean):string9+ | Obtains the localized representation of a country. | +| System | getDisplayLanguage(language:string,locale:string,sentenceCase?:boolean):string9+ | Obtains the localized representation of a language. | +| System | getSystemLanguages():Array9+ | Obtains the system language list. | +| System | getSystemCountries(language: string):Array9+ | Obtains the list of countries and regions supported for the specified language. | +| System | isSuggested(language: string, region?: string): boolean9+ | Checks whether the system language matches the specified region. | +| System | getSystemLanguage():string9+ | Obtains the system language. | +| System | setSystemLanguage(language: string)9+ | Sets the system language. | +| System | getSystemRegion():string9+ | Obtains the system region. | +| System | setSystemRegion(region: string)9+ | Sets the system region. | +| System | getSystemLocale():string9+ | Obtains the system locale. | +| System | setSystemLocale(locale: string)9+ | Sets the system locale. | +| System | is24HourClock():boolean9+ | Checks whether the 24-hour clock is used. | +| System | set24HourClock():boolean9+ | Sets the 24-hour clock. | +| System | addPreferredLanguage(language: string, index?: number)9+ | Adds a preferred language to the specified position on the preferred language list. | +| System | removePreferredLanguage(index: number)9+ | Deletes a preferred language from the specified position on the preferred language list. | +| System | getPreferredLanguageList()9+ | Obtains the preferred language list. | +| System | getFirstPreferredLanguage()9+ | Obtains the first language in the preferred language list. | +| System | getAppPreferredLanguage()9+ | Obtains the preferred language of an application. | +| System | setUsingLocalDigit(flag: boolean)9+ | Sets whether to enable the local digit switch. | +| System | getUsingLocalDigit()9+ | Checks whether the local digit switch is turned on. | +| | isRTL(locale:string):boolean9+ | Checks whether the locale uses a right-to-left (RTL) language.| ### How to Develop +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Obtain and set the system language. + + Call **setSystemLanguage** to set the system language. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call the **getSystemLanguage** API to obtain the system language. + + ```js + try { + I18n.System.setSystemLanguage("en"); // Set the system language to en. + let language = I18n.System.getSystemLanguage(); // language = "en" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` -1. Obtain the system language. +3. Obtain and set the system locale. + + Call **setSystemRegion** to set the system country or region. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call **getSystemRegion** to obtain the system country or region. + + ```js + try { + I18n.System.setSystemRegion("CN"); // Set the system country to CN. + let region = I18n.System.getSystemRegion(); // region = "CN" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` - Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). +4. Obtain and set the system locale. + Call **setSystemLocale** to set the system locale. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) For details about how to set a locale, see [Setting Locale Information](../internationalization/intl-guidelines.md#setting-locale-information). + Call **getSystemLocale** to obtain the system locale. - ```js - var language = i18n.getSystemLanguage(); + ```js + try { + I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN. + let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -2. Obtain the system region. +5. Check whether the locale uses a right-to-left (RTL) language. + + Call **isRTL** to check whether the locale uses an RTL language. - Call the **getSystemRegion** method to obtain the system region. - - ```js - var region = i18n.getSystemRegion(); + ```js + try { + let rtl = I18n.isRTL("zh-CN"); // rtl = false + rtl = I18n.isRTL("ar"); // rtl = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -3. Obtain the system locale. +6. Obtain and set the 24-hour clock. - Call the **getSystemLocale** method to obtain the system locale. - - ```js - var locale = i18n.getSystemLocale(); + Call **set24HourClock** to enable the 24-hour clock. + Call **is24HourClock** to check whether the 24-hour clock is enabled. + + ```js + try { + I18n.System.set24HourClock(true); + let hourClock = I18n.System.is24HourClock(); // hourClock = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -4. Check whether the locale's language is RTL. +7. Obtain the localized representation of a language. + + Call **getDisplayLanguage** to obtain the localized representation of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - Call the **isRTL** method to check whether the locale's language is RTL. + ```js + try { + let language = "en"; + let locale = "zh-CN"; + let sentenceCase = false; + let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` +8. Obtain the localized representation of a country. - ```js - var rtl = i18n.isRTL("zh-CN"); + Call **getDisplayCountry** to obtain the localized representation of a country. **country** indicates the country to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. + + ```js + try { + let country = "US"; + let locale = "zh-CN"; + let sentenceCase = false; + let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S." + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -5. Check whether the system uses a 24-hour clock. +9. Obtain the list of system languages and the list of countries supported by a system language. - Call the **is24HourClock** method to check whether the system uses a 24-hour clock. - - ```js - var hourClock = i18n.is24HourClock(); + Call **getSystemLanguages** to obtain the list of system languages. + Call **getSystemCountries** to obtain the list of countries and regions supported by a system language. + ```js + + try { + let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"] + let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -6. Obtain the localized display of a language. +10. Check whether the language matches a country or region. - Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - - ```js - var language = "en"; - var locale = "zh-CN"; - var sentenceCase = false; - var localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase); + Call **isSuggested** to check whether the language matches a country or region. + + ```js + try { + let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -7. Obtain the localized display of a country. +11. Obtain and set the preferred language. - Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - - ```js - var country = "US"; - var locale = "zh-CN"; - var sentenceCase = false; - var localizedCountry = i18n.getDisplayCountry(country, locale, sentenceCase); + Call **addPreferredLanguage** to add a preferred language to the preferred language list. + Call **removePreferredLanguage** to remove a preferred language from the preferred language list. (**addPreferredLanguage** and **removePreferredLanguage** are system APIs and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call **getPreferredLanguageList** to obtain the preferred language list. + Call **getFirstPreferredLanguage** to obtain the first preferred language in the preferred language list. + Call **getAppPreferredLanguageList** to obtain the preferred language of the application. It is the first language that matches the application resource in the preferred language list. + + ```js + try { + I18n.System.addPreferredLanguage("en-GB", 0); // Set the first language in the preferred language list to en-GB. + let list = I18n.System.getPreferredLanguageList(); // Obtain the preferred language list. Example: list = ["en-GB", ...] + I18n.System.removePreferredLanguage(list.length - 1); // Remove the last preferred language from the preferred language list. + let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB" + let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources. + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` +12. Obtain and set the local digit switch. -## Obtaining Calendar Information + Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.) + Call **getUsingLocalDigit** to check whether the local digit switch is enabled. + Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur". -[Calendar](../reference/apis/js-apis-i18n.md#calendar8) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. +```js +try { + I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. + let status = I18n.System.getUsingLocalDigit(); // status = true +} catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) +} +``` +## Obtain the calendar information. -### Available APIs +[Calendar](../reference/apis/js-apis-i18n.md#calendar8) provides APIs to obtain calendar information, for example, localized representation of the calendar, the start day of a week, and the minimum number of days in the first week of a year. -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getCalendar(locale: string, type?: string): Calendar8+ | Obtains the **Calendar** object for a specific locale and type. | -| ohos.i18n | setTime(date: Date): void8+ | Sets the date for the **Calendar** object. | -| ohos.i18n | setTime(time: number): void8+ | Sets the time for the **Calendar** object. | -| ohos.i18n | set(year: number, month: number, date: number, hour?: number, minute?: number, second?: number): void8+ | Sets the year, month, day, hour, minute, and second for the **Calendar** object. | -| ohos.i18n | setTimeZone(timezone: string): void8+ | Sets the time zone for the **Calendar** object. | -| ohos.i18n | getTimeZone(): string8+ | Obtains the time zone for the **Calendar** object. | -| ohos.i18n | getFirstDayOfWeek(): number8+ | Obtains the first day of a week for the **Calendar** object. | -| ohos.i18n | setFirstDayOfWeek(value: number): void8+ | Sets the first day of a week for the **Calendar** object. | -| ohos.i18n | getMinimalDaysInFirstWeek(): number8+ | Obtains the minimum count of days in the first week of a year. | -| ohos.i18n | setMinimalDaysInFirstWeek(value: number): void8+ | Sets the minimum count of days in the first week of a year. | -| ohos.i18n | getDisplayName(locale: string): string8+ | Obtains the localized display of the **Calendar** object. | -| ohos.i18n | isWeekend(date?: Date): boolean8+ | Checks whether a given date is a weekend. | +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------- | +| | getCalendar(locale:string,type?:string):Calendar8+ | Obtains the **Calendar** object for a specific locale and type.| +| Calendar | setTime(date:Date): void8+ | Sets the date for this **Calendar** object. | +| Calendar | setTime(time:number): void8+ | Sets the date for this **Calendar** object. | +| Calendar | set(year:number,month:number,date:number,hour?:number,minute?:number,second?:number): void8+ | Sets the year, month, day, hour, minute, and second for this **Calendar** object. | +| Calendar | setTimeZone(timezone:string): void8+ | Sets the time zone of this **Calendar** object. | +| Calendar | getTimeZone():string8+ | Obtains the time zone of this **Calendar** object. | +| Calendar | getFirstDayOfWeek():number8+ | Obtains the start day of a week for this **Calendar** object. | +| Calendar | setFirstDayOfWeek(value:number): void8+ | Sets the first day of a week for the **Calendar** object. | +| Calendar | getMinimalDaysInFirstWeek():number8+ | Obtains the minimum number of days in the first week of a year. | +| Calendar | setMinimalDaysInFirstWeek(value:number): void8+ | Sets the minimum number of days in the first week of a year. | +| Calendar | getDisplayName(locale:string):string8+ | Obtains the localized display of the **Calendar** object. | +| Calendar | isWeekend(date?:Date):boolean8+ | Checks whether the specified date in this **Calendar** object is a weekend. | ### How to Develop -1. Instantiate a **Calendar** object. +1. Import the **i18n** module. - Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. + ```js + import I18n from '@ohos.i18n' + ``` + +2. Instantiate a **Calendar** object. + Call **getCalendar** to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - ```js - var calendar = i18n.getCalendar("zh-CN", "gregory"); + ```js + let calendar = I18n.getCalendar("zh-CN", "chinese"); // Create the Calendar object for the Chinese lunar calendar. ``` -2. Set the time for the **Calendar** object. +3. Set the time for the **Calendar** object. + + Call **setTime** to set the time of the **Calendar** object. Two types of parameters are supported. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. - Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. - - ```js - var date1 = new Date(); + ```js + let date1 = new Date(); calendar.setTime(date1); - var date2 = 1000; + let date2 = 1000; calendar.setTime(date2); ``` -3. Set the year, month, day, hour, minute, and second for the **Calendar** object. +4. Set the year, month, day, hour, minute, and second for this **Calendar** object. - Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - - ```js + Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object. + + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` -4. Set and obtain the time zone for the **Calendar** object. - - Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. +5. Set and obtain the time zone for the **Calendar** object. + Call **setTimeZone** and **getTimeZone** to set and obtain the time zone of the **Calendar** object. Note that **setTimeZone** requires an input string to indicate the time zone to be set. - ```js + ```js calendar.setTimeZone("Asia/Shanghai"); - var timezone = calendar.getTimeZone(); + let timezone = calendar.getTimeZone(); // timezone = "China Standard Time" ``` -5. Set and obtain the first day of a week for the **Calendar** object. +6. Set and obtain the first day of a week for the **Calendar** object. - Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. + Call **setFirstDayOfWeek** and **getFirstDayOfWeek** to set and obtain the start day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. - - ```js + ```js calendar.setFirstDayOfWeek(1); - var firstDayOfWeek = calendar.getFirstDayOfWeek(); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` -6. Set and obtain the minimum count of days in the first week for the **Calendar** object. +7. Set and obtain the minimum count of days in the first week for the **Calendar** object. + Call **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** to set and obtain the minimum number of days in the first week for the **Calendar** object. - Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - - ```js + ```js calendar.setMinimalDaysInFirstWeek(3); - var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 ``` -7. Obtain the localized display of the **Calendar** object. +8. Obtain the localized representation of the **Calendar** object. + Call **getDisplayName** to obtain the localized representation of the **Calendar** object. + + ```js + let localizedName = calendar.getDisplayName("zh-CN"); // localizedName = " Lunar Calendar" + ``` - Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. +9. Check whether a date is a weekend. + Call **isWeekend** to determine whether the input date is a weekend. - ```js - var localizedName = calendar.getDisplayName("zh-CN"); + ```js + let date = new Date(2022, 12, 12, 12, 12, 12); + let weekend = calendar.isWeekend(date); // weekend = false ``` -8. Check whether a date is a weekend. +## Formatting a Phone Number + +[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) provides APIs to format phone numbers of different countries or regions and check whether the phone number format is correct. - Call the **isWeekend** method to determine whether the input date is a weekend. +### Available APIs - - ```js - var date = new Date(); - var weekend = calendar.isWeekend(date); +| Class | API | Description | +| --------- | ---------------------------------------- | ----------------------- | +| PhoneNumberFormat | constructor(country:string,options?:PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object.| +| PhoneNumberFormat | isValidNumber(number:string):boolean8+ | Checks whether the value of **number** is a phone number in the correct format.| +| PhoneNumberFormat | format(number:string):string8+ | Formats the value of **number** based on the specified country and style. | +| PhoneNumberFormat | getLocationName(number: string, locale: string): string9+ | Obtains the home location of a phone number. | + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` +2. Instantiate a **PhoneNumberFormat** object. -## Formatting a Phone Number + Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. -[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. + ```js + let phoneNumberFormat = new I18n.PhoneNumberFormat("CN", {type: "E164"}); + ``` +3. Check whether the phone number format is correct. + + Call **isValidNumber** to check whether the format of the input phone number is correct. + + ```js + let validNumber = phoneNumberFormat.isValidNumber("15812341234"); // validNumber = true + ``` + +4. Format a phone number. + + Call **format** to format the input phone number. + + ```js + let formattedNumber = phoneNumberFormat.format("15812341234"); // formattedNumber = "+8615812341234" + ``` + +## Measurement Conversion + +The **I18NUtil** class provides an API to implement measurement conversion. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | -| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | -| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------------------------- | +| I18NUtil | unitConvert(fromUnit:UnitInfo,toUnit:UnitInfo,value:number,locale:string,style?:string):string9+ | Converts one measurement unit into another and formats the unit based on the specified locale and style.| + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Convert a measurement unit. + + Call [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) to convert a measurement unit and format the display result. + + ```js + let fromUnit = {unit: "cup", measureSystem: "US"}; + let toUnit = {unit: "liter", measureSystem: "SI"}; + let number = 1000; + let locale = "en-US"; + let style = "long"; + let converttedUnit = I18n.I18NUtil.unitConvert(fromUnit, toUnit, number, locale, style); // converttedUnit = "236.588 liters" + ``` + +## Alphabet Indexing + +[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) provides APIs to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. + +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | ----------------------- | +| | getInstance(locale?:string):IndexUtil8+ | Instantiates an **IndexUtil** object. | +| IndexUtil | getIndexList():Array<string>8+ | Obtains the index list of the current locale. | +| IndexUtil | addLocale(locale:string): void8+ | Adds the index of a new locale to the index list.| +| IndexUtil | getIndex(text:string):string8+ | Obtains the index of a text object. | ### How to Develop -1. Instantiate a **PhoneNumberFormat** object. +1. Import the **i18n** module. - Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. + ```js + import I18n from '@ohos.i18n' + ``` + +2. Instantiates an **IndexUtil** object. + Call **getInstance** to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - ```js - var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); + + ```js + let indexUtil = I18n.getInstance("zh-CN"); ``` -2. Check whether the phone number format is correct. - Call the **isValidNumber** method to check whether the format of the input phone number is correct. - - ```js - var validNumber = phoneNumberFormat.isValidNumber("15812341234"); +3. Obtain the index list. + + Call **getIndexList** to obtain the alphabet index list of the current locale. + + ```js + let indexList = indexUtil.getIndexList(); // indexList = ["...", "A", "B", "C", ..., "X", "Y", "Z", "..."] ``` -3. Format a phone number. - Call the **format** method of **PhoneNumberFormat** to format the input phone number. - - ```js - var formattedNumber = phoneNumberFormat.format("15812341234"); +4. Add an index. + + Call **addLocale** to add the alphabet index of a new locale to the current index list. + + ```js + indexUtil.addLocale("ar") ``` +5. Obtain the index of a string. -## Measurement Conversion + Call **getIndex** to obtain the alphabet index of a string. -The **unitConvert** API is provided to help you implement measurement conversion. + ```js + let text = "access index"; + let index = indexUtil.getIndex(text); // index = "A" + ``` + +## Obtaining Line Breaks of Text +When a text is displayed in more than one line, use [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs to obtain the line break positions of the text. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | - +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| | getLineInstance(locale:string):BreakIterator8+ | Instantiates a **BreakIterator** object. | +| BreakIterator | setLineBreakText(text:string): void8+ | Sets the text to be processed. | +| BreakIterator | getLineBreakText():string8+ | Obtains the text to be processed. | +| BreakIterator | current():number8+ | Obtains the current position of a **BreakIterator** object in the text being processed. | +| BreakIterator | first():number8+ | Sets a **BreakIterator** object to the first breakable point. | +| BreakIterator | last():number8+ | Sets a **BreakIterator** object to the last breakable point. | +| BreakIterator | next(index?:number):number8+ | Moves a **BreakIterator** object to the break point according to **index**. | +| BreakIterator | previous():number8+ | Moves a **BreakIterator** object to the previous break point. | +| BreakIterator | following(offset:number):number8+ | Moves a **BreakIterator** object to the break point following the position specified by **offset**.| +| BreakIterator | isBoundary(offset:number):boolean8+ | Determines whether a position is a break point. | ### How to Develop -1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result. +1. Import the **i18n** module. - - ```js - var fromUnit = {unit: "cup", measureSystem: "US"}; - var toUnit = {unit: "liter", measureSystem: "SI"}; - var number = 1000; - var locale = "en-US"; - var style = "long"; - i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); - ``` + ```js + import I18n from '@ohos.i18n' + ``` +2. Instantiate a **BreakIterator** object. -## Alphabet Index + Call **getLineInstance** to instantiate a **BreakIterator** object. -[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. + ```js + let locale = "en-US" + let breakIterator = I18n.getLineInstance(locale); + ``` +3. Set and access the text that requires line breaking. -### Available APIs + Call **setLineBreakText** and **getLineBreakText** to set and access the text that requires line breaking. -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getInstance(locale?: string): IndexUtil8+ | Instantiates an **IndexUtil** object. | -| ohos.i18n | getIndexList(): Array<string>8+ | Obtains the index list of the current locale. | -| ohos.i18n | addLocale(locale: string): void8+ | Adds the index of a new locale to the index list. | -| ohos.i18n | getIndex(text: string): string8+ | Obtains the index of **text**. | + ```js + let text = "Apple is my favorite fruit"; + breakIterator.setLineBreakText(text); + let breakText = breakIterator.getLineBreakText(); // breakText = "Apple is my favorite fruit" + ``` +4. Obtain the current position of the **BreakIterator** object. -### How to Develop + Call **current** to obtain the current position of the **BreakIterator** object in the text being processed. -1. Instantiate an **IndexUtil** object. + ```js + let pos = breakIterator.current(); // pos = 0 + ``` - Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. +5. Set the position of a **BreakIterator** object. + The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. - ```js - var indexUtil = i18n.getInstance("zh-CN"); + ```js + let firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text (firstPos = 0). + let lastPos = breakIterator.last(); // Sets a BreakIterator object to the last break point, that is, the position after the text end (lastPos = 26). + // Move a BreakIterator object forward or backward by a certain number of break points. + // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. + // If the object is moved out of the text length range, **-1** is returned. + let nextPos = breakIterator.next(-2); // nextPos = 12 + let previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, **-1** is returned. Example: previousPos = 9 + // Move a BreakIterator object to the break point following the position specified by **offset**. If the object is moved out of the text length range, **-1** is returned. + let followingPos = breakIterator.following(10); // Example: followingPos = 12 ``` -2. Obtain the index list. +6. Determine whether a position is a break point. - Call the **getIndexList** method to obtain the alphabet index list of the current locale. - - ```js - var indexList = indexUtil.getIndexList(); + Call **isBoundary** to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. + + ```js + let isboundary = breakIterator.isBoundary(5); // isboundary = false ``` -3. Add an index. +## Obtaining the Time Zone - Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - - ```js - indexUtil.addLocale("ar") +[TimeZone](../reference/apis/js-apis-i18n.md#timezone) provides APIs to obtain time zone information, such as the time zone ID, localized representation, and time zone offset. + +### Available APIs + +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| | getTimeZone(zoneID?: string): TimeZone7+ | Obtains a **TimeZone** object. | +| TimeZone | getID(): string7+ | Obtains the time zone ID. | +| TimeZone | getDisplayName(locale?: string, isDST?: boolean): string7+ | Obtains the localized representation of the time zone. | +| TimeZone | getRawOffset(): number7+ | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone. | +| TimeZone | getOffset(date?: number): number7+ | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone at a certain time point. | +| TimeZone | getAvailableIDs(): Array9+ | Obtains the list of time zone IDs supported by the system. | +| TimeZone | getAvailableZoneCityIDs(): Array9+ | Obtains the list of time zone city IDs supported by the system. | +| TimeZone | getCityDisplayName(cityID: string, locale: string): string9+ | Obtains the localized representation of a time zone city in the specified locale. | +| TimeZone | getTimezoneFromCity(cityID: string): TimeZone9+ | Obtains the **TimeZone** object corresponding to the specified time zone ID.| + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` -4. Obtain the index of a string. +2. Instantiate the **TimeZone** object, and obtain the time zone information. - Call the **getIndex** method to obtain the alphabet index of a string. - - ```js - var text = "access index"; - indexUtil.getIndex(text); + Call **getTimeZone** to obtain the **TimeZone** object. + + ```js + let timezone = I18n.getTimeZone(); // If you use the default settings, you'll obtain the TimeZone object corresponding to the system time zone. ``` + Obtain the time zone ID, localized representation, time zone offset, and time zone offset at a certain time point. + + ```js + let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "China Standard Time" + let rawOffset = timezone.getRawOffset(); // rawOffset = 28800000 + let offset = timezone.getOffset(new Date().getTime()); // offset = 28800000 + ``` -## Obtaining Line Breaks of Text +3. Obtain the list of time zone IDs supported by the system. + + Call **getAvailableIDs** to obtain the list of time zone IDs supported by the system. + You can use the time zone ID in the time zone ID list as an input parameter of the **getTimeZone** API to create a **TimeZone** object. + + ```js + let timezoneIDs = I18n.TimeZone.getAvailableIDs(); // timezoneIDs = ["America/Adak", ...], which contains 24 time zone IDs in total + let timezone = I18n.getTimeZone(timezoneIDs[0]); + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "Hawaii-Aleutian Standard Time" + ``` + +4. Obtain the list of time zone city IDs supported by the system. + + Call **getAvailableZoneCityIDs** to obtain the list of time zone city IDs supported by the system. + Call **getCityDisplayName** to obtain the localized representation of the time zone city ID. + Call **getTimezoneFromCity** to create a **TimeZone** object based on the time zone city ID. -When a text is displayed in more than one line, [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs are used to obtain the line break positions of the text. + ```js + let zoneCityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); // ["Auckland", "Magadan", ...] + let cityDisplayName = I18n.TimeZone.getCityDisplayName(zoneCityIDs[0], "zh-Hans"); // cityDisplayName = "Auckland (New Zealand)" + let timezone = I18n.TimeZone.getTimezoneFromCity(zoneCityIDs[0]); + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "New Zealand Standard Time" + ``` + +## Obtain the **Transliterator** object. +Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to create a **Transliterator** object and obtain the transliterated string. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getLineInstance(locale: string): BreakIterator8+ | Instantiates a **BreakIterator** object. | -| ohos.i18n | setLineBreakText(text: string): void8+ | Sets the text to be processed. | -| ohos.i18n | getLineBreakText(): string8+ | Obtains the text to be processed. | -| ohos.i18n | current(): number8+ | Obtains the current position of a **BreakIterator** object in the text being processed. | -| ohos.i18n | first(): number8+ | Sets a **BreakIterator** object to the first breakable point. | -| ohos.i18n | last(): number8+ | Sets a **BreakIterator** object to the last breakable point. | -| ohos.i18n | next(index?: number): number8+ | Moves a **BreakIterator** object to the break point according to **index**. | -| ohos.i18n | previous(): number8+ | Moves a **BreakIterator** object to the previous break point. | -| ohos.i18n | following(offset: number): number8+ | Moves a **BreakIterator** object to the break point following the position specified by **offset**. | -| ohos.i18n | isBoundary(offset: number): boolean8+ | Determines whether a position is a break point. | +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| Transliterator | getAvailableIDs():Array9+ | Obtains the transliterator ID list. | +| Transliterator | getInstance(): Transliterator9+ | Creates a **Transliterator** object. | +| Transliterator | transform(text: string): string9+ | Obtains a transliterated string. | +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Obtains the transliterator ID list. + + Call **getAvailableIDs** to obtain the transliterator ID list. + An ID is in the **source-destination** format. For example, **ASCII-Latin** means to convert the transliterator ID from ASCII to Latin. + + ```js + let ids = I18n.Transliterator.getAvailableIDs(); // ids = ["ASCII-Latin", "Accents-Any", ... ], 671 languages in total + ``` + +3. Create a **Transliterator** object, and obtain the transliterated string. + + You can use the ID in the transliterator ID list as an input parameter of the **getInstance** API to create a **Transliterator** object. + Call **transform** to obtain the transliterated string. + + ```js + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); // Any-Latn means to convert any text to Latn text. + let transformText = transliterator.transform ("Hello"); // transformText = "nǐ hǎo" + ``` + +## Obtaining the Character Type + +[Unicode](../reference/apis/js-apis-i18n.md#unicode9) provides APIs to obtain character information, for example, whether a character is a digit or a space. + +### Available APIs + +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| Unicode | isDigit(char: string): boolean9+ | Checks whether the input character is a digit. | +| Unicode | isSpaceChar(char: string): boolean9+ | Checks whether the input character is a space. | +| Unicode | isWhitespace(char: string): boolean9+ | Checks whether the input character is a white space. | +| Unicode | isRTL(char: string): boolean9+ | Checks whether the input character is of the RTL language. | +| Unicode | isIdeograph(char: string): boolean9+ | Checks whether the input character is an ideographic character. | +| Unicode | isLetter(char: string): boolean9+ | Checks whether the input character is a letter. | +| Unicode | isLowerCase(char: string): boolean9+ | Checks whether the input character is a lowercase letter. | +| Unicode | isUpperCase(char: string): boolean9+ | Checks whether the input character is an uppercase letter. | +| Unicode | getType(char: string): string9+ | Obtains the type of a character.| ### How to Develop -1. Instantiate a **BreakIterator** object. +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` - Call the **getLineInstance** method to instantiate a **BreakIterator** object. +2. Check the input character has a certain attribute. + Check whether the input character is a digit. - ```js - var locale = "en-US" - var breakIterator = i18n.getLineInstance(locale); + ```js + let isDigit = I18n.Unicode.isDigit("1"); // isDigit = true + isDigit = I18n.Unicode.isDigit("a"); // isDigit = false ``` -2. Set and access the text that requires line breaking. + Check whether the input character is a space. - Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking. + ```js + let isSpaceChar = I18n.Unicode.isSpaceChar(" "); // isSpaceChar = true + isSpaceChar = I18n.Unicode.isSpaceChar("\n"); // isSpaceChar = false + ``` - - ```js - var text = "Apple is my favorite fruit"; - breakIterator.setLineBreakText(text); - var breakText = breakIterator.getLineBreakText(); + Check whether the input character is a white space. + + ```js + let isWhitespace = I18n.Unicode.isWhitespace(" "); // isWhitespace = true + isWhitespace = I18n.Unicode.isWhitespace("\n"); // isWhitespace = true + ``` + + Check whether the input character is of the RTL language. + + ```js + let isRTL = I18n.Unicode.isRTL(""); // isRTL = true (Arabic characters are written from left to right.) + isRTL = I18n.Unicode.isRTL("a"); // isRTL = false ``` -3. Obtain the current position of the **BreakIterator** object. + Check whether the input character is an ideographic character. - Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. + ```js + let isIdeograph = I18n.Unicode.isIdeograph("Hello"); // isIdeograph = true + isIdeograph = I18n.Unicode.isIdeograph("a"); // isIdeograph = false + ``` + Check whether the input character is a letter. - ```js - var pos = breakIterator.current(); + ```js + let isLetter = I18n.Unicode.isLetter("a"); // isLetter = true + isLetter = I18n.Unicode.isLetter("."); // isLetter = false ``` -4. Set the position of a **BreakIterator** object. + Check whether the input character is a lowercase letter. - The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. + ```js + let isLowerCase = I18n.Unicode.isLowerCase("a"); // isLetter = true + isLowerCase = I18n.Unicode.isLowerCase("A"); // isLetter = false + ``` - - ```js - var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text. - var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end. - // Move a BreakIterator object forward or backward by a certain number of break points. - // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. - // When the object is moved out of the text length range, -1 is returned. - var nextPos = breakIterator.next(-2); - var previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned. - // Move a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned. - var followingPos = breakIterator.following(10); + Check whether the input character is an uppercase letter. + + ```js + let isUpperCase = I18n.Unicode.isUpperCase("a"); // isUpperCase = false + isUpperCase = I18n.Unicode.isUpperCase("A"); // isUpperCase = true + ``` + +3. Obtain the character type. + + Call **getType** to obtain the character type. + + ```js + let type = I18n.Unicode.getType("a"); // type = U_LOWER_CASE_LETTER ``` -5. Determine whether a position is a break point. +## Obtaining the Sequence of Year, Month, and Day in a Date - Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| I18NUtil | getDateOrder(locale: string): string9+ | Checks the sequence of year, month, and day in a date. | + +### How to Develop - ```js - var isboundary = breakIterator.isBoundary(5); +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` - ``` \ No newline at end of file +2. Check the sequence of year, month, and day in a date. + + Call **getDateOrder** to obtain the sequence of year, month, and day in the date of the specified locale. + The API returns a string consisting of three parts, **y**, **L**, and **d**, which indicate the year, month, and day, respectively. The three parts are separated by using a hyphen (-), for example, **y-L-d**. + + ```js + let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" indicates that the sequence of year, month, and day in Chinese is year-month-day. + ``` diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index f123a0b29a64a10b683f9fb90d163790e4f0524e..609af84500cecb0ce5bda8409216b6957182885f 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -1,38 +1,42 @@ -# Internationalization Development (Intl) +# intl Development -This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. For more details about APIs and their usage, see [Intl](../reference/apis/js-apis-intl.md). +The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. For more details about APIs and their usage, see [intl](../reference/apis/js-apis-intl.md). -> **NOTE** -> -> In the code snippets in this document, **intl** refers to the name of the imported module. +The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. ## Setting Locale Information -Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minimize locale information. - +[Locale](../reference/apis/js-apis-intl.md#locale) provides APIs to maximize or minimize the locale information. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | -| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | -| ohos.intl | toString(): string | Converts locale information into a string. | -| ohos.intl | maximize(): Locale | Maximizes locale information. | -| ohos.intl | minimize(): Locale | Minimizes locale information. | - +| Locale | constructor()8+ | Instantiates a **Locale** object.| +| Locale | constructor(locale:string,options?:LocaleOptions) | Instantiates a **Locale** object based on the locale parameter and options.| +| Locale | toString():string | Converts locale information into a string.| +| Locale | maximize():Locale | Maximizes locale information.| +| Locale | minimize():Locale | Minimizes locale information.| ### How to Develop -1. Instantiate a **Locale** object. +1. Import the **intl** module. + + Importing an incorrect bundle can lead to unexpected API behavior. + + ```js + import Intl from '@ohos.intl' + ``` + +2. Instantiates a **Locale** object. - Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md#localeoptions) list. + Create a **Locale** object using the **Locale** constructor. This API receives a string representing the locale and an optional [attribute](../reference/apis/js-apis-intl.md#localeoptions) list. (Note that **intl** is the name of the imported module.) A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-). - Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese. - Script: optional. It is represented by a four-letter code as defined in ISO-15924. The first letter is in uppercase, and the remaining three letters are in lowercase. For example, **Hant** represents the traditional Chinese, and **Hans** represents the simplified Chinese. - Country or region: optional. It is represented by two-letter code as defined in ISO-3166. Both letters are in uppercase. For example, **CN** represents China, and **US** represents the United States. - - Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the Latin numbering system and Chinese calendar system are used. Extensions can also be passed via the second parameter. + - Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the latn digital system and chinese calendar system are used. Extensions can also be passed via the second parameter. | Extended Parameter ID| Description| | -------- | -------- | | ca | Calendar algorithm.| @@ -40,305 +44,346 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim | hc | Hour cycle.| | nu | Numbering system.| | kn | Whether numeric collation is used when sorting or comparing strings.| - | kf | Whether upper case or lower case is considered when sorting or comparing strings.| + | kf | Whether capitalization is considered when sorting or comparing strings.| ```js - var locale = "zh-CN"; - var options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; - var localeObj = new intl.Locale(locale, options); + let locale = "zh-CN"; + let options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; + let localeObj = new Intl.Locale(locale, options); ``` -2. Obtain the string representing a **Locale** object. +3. Obtain the string representing a **Locale** object. - Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. - + Call **toString** to obtain the string representing a **Locale** object, including the language, region, and other options. + ```js - var localeStr = localeObj.toString(); + let localeStr = localeObj.toString(); // localeStr = "zh-CN-u-ca-chinese-co-pinyin-kf-false ``` -3. Maximize locale information. +4. Maximize locale information. - Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. - + Call **maximize** to maximize locale information; that is, supplement the missing script and region information. + ```js - var maximizedLocale = localeObj.maximize(); + let maximizedLocale = localeObj.maximize(); + let maximizedLocaleStr = maximizedLocale.toString(); // localeStr = "zh-Hans-CN-u-ca-chinese-co-pinyin-kf-false ``` -4. Minimize locale information. +5. Minimize locale information. - Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. - + Call **minimize** to minimize locale information; that is, delete the unnecessary script and region information. + ```js - var minimizedLocale = localeObj.minimize(); + let minimizedLocale = localeObj.minimize(); + let minimizedLocaleStr = minimizedLocale.toString(); // zh-u-ca-chinese-co-pinyin-kf-false ``` - ## Formatting the Date and Time -Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to format the date and time for a specific locale. - +[DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) provides APIs to format the date and time for the specified locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | - +| DateTimeFormat | constructor()8+ | Creates a **DateTimeFormat** object.| +| DateTimeFormat | constructor(locale:string\|Array<string>,options?:DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes.| +| DateTimeFormat | format(date:Date):string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object.| +| DateTimeFormat | formatRange(startDate:Date,endDate:Date):string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object.| +| DateTimeFormat | resolvedOptions():DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object.| ### How to Develop -1. Instantiate a **DateTimeFormat** object. - - Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var dateTimeFormat = new intl.DateTimeFormat(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). - +2. Instantiate a **DateTimeFormat** object. + + Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. + ```js - var options = {dateStyle: "full", timeStyle: "full"}; - var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options); + let dateTimeFormat = new Intl.DateTimeFormat(); ``` -2. Format the date and time. - - Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. + Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). ```js - var date = new Date(); - var formatResult = dateTimeFormat.format(date); + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); ``` -3. Format a period. +3. Format the date and time. - Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. - + Call **format** to format a **Date** object. A string is returned as the formatting result. + ```js - var startDate = new Date(2021, 11, 17, 3, 24, 0); - var endDate = new Date(2021, 11, 18, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.formatRange(startDate, endDate); + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); + let date = new Date(2022, 12, 12, 12, 12, 12); + let formatResult = dateTimeFormat.format(date); // formatResult = "January 12, 2023, Thursday, 12:12:12 pm, China Standard Time" ``` -4. Obtain attributes of the **DateTimeFormat** object. +4. Format a period. - Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. - + Call **formatRange** to format a period. This API requires the input of two **Date** objects, which respectively indicate the start date and end date of a period. A string is returned as the formatting result. + ```js - var options = dateTimeFormat.resolvedOptions(); + let startDate = new Date(2021, 11, 17, 3, 24, 0); + let endDate = new Date(2021, 11, 18, 3, 24, 0); + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formatRangeResult = datefmt.formatRange(startDate, endDate); // formatRangeResult = "17/12/2021-18/12/2021" ``` +5. Access the attributes of the **DateTimeFormat** object. -## Formatting Numbers + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **DateTimeFormat** object. + + ```js + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); + let resolvedOptions = dateTimeFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "calendar": "gregorian", "dateStyle":"full", "timeStyle":"full", "timeZone": "CST"} + ``` -Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to format numbers for a specific locale. +## Number Formatting +[NumberFormat](../reference/apis/js-apis-intl.md#numberformat) provides APIs to implement the number formatting specific to a locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | - +| NumberFormat | constructor()8+ | Creates a **NumberFormat** object for the specified locale.| +| NumberFormat | constructor(locale:string\|Array<string>,options?:NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes.| +| NumberFormat | format(number:number):string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object.| +| NumberFormat | resolvedOptions():NumberOptions | Obtains the attributes of the **NumberFormat** object.| ### How to Develop -1. Instantiate a **NumberFormat** object. - - Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var numberFormat = new intl.NumberFormat(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). - +2. Instantiate a **NumberFormat** object. + + Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **NumberFormat** object (**intl** is the name of the imported module). + ```js - var options = {compactDisplay: "short", notation: "compact"}; - var numberFormat = new intl.NumberFormat("zh-CN", options); + let numberFormat = new Intl.NumberFormat(); ``` -2. Format a number. - - Call the **format** method to format a number. A string is returned as the formatting result. + Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). ```js - var number = 1234.5678 - var formatResult = numberFormat.format(number); + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); ``` -3. Obtain attributes of the **NumberFormat** object. +3. Format a number. - Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. - + Call **format** to format a number. A string is returned as the formatting result. + ```js - var options = numberFormat.resolvedOptions(); + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); + let number = 1234.5678 + let formatResult = numberFormat.format(number); // formatResult = "1235" ``` +4. Access the attributes of the **NumberFormat** object. -## Sorting Strings + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **NumberFormat** object. + + ```js + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); + let resolvedOptions = numberFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "compactDisplay": "short", "notation": "compact", "numberingSystem": "Latn"} + ``` -Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. +## String Sorting +Users in different regions have different requirements for string sorting. [Collator](../reference/apis/js-apis-intl.md#collator8) provides APIs to sort character strings specific to a locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **Collator** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | -| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | - +| Collator | constructor()8+ | Creates a **Collator** object.| +| Collator | constructor(locale:string\|Array<string>,options?:CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes.| +| Collator | compare(first:string,second:string):number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object.| +| Collator | resolvedOptions():CollatorOptions8+ | Obtains the attributes of the **Collator** object.| ### How to Develop -1. Instantiate a **Collator** object. - - Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var collator = new intl.Collator(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). - +2. Instantiate a **Collator** object. + + Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **Collator** object (**intl** is the name of the imported module). + ```js - var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); + let collator = new Intl.Collator(); ``` -2. Compare two strings. - - Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'. ```js - var str1 = "first string"; - var str2 = "second string"; - var compareResult = collator.compare(str1, str2); + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); ``` -3. Obtain attributes of the **Collator** object. +3. Compare two strings. - Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. - + Call **compare** to compare two input strings. This API returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. + ```js - var options = collator.resolvedOptions(); + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); + let str1 = "first string"; + let str2 = "second string"; + let compareResult = collator.compare(str1, str2); // compareResult = -1 + str1 = "first"; + str2 = "First"; + compareResult = collator.compare(str1, str2); // compareResult = -1 ``` +4. Access the attributes of the **Collator** object. -## Determining the Singular-Plural Type + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **Collator** object. + + ```js + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); + let options = collator.resolvedOptions(); // options = {"localeMatcher": "best fit", "locale": "zh-CN", "usage": "sort", "sensitivity": "variant", "ignorePunctuation": "false", "numeric": false, "caseFirst": "false", "collation": "default"} + ``` -Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number. +## Determining the Singular-Plural Type +According to grammars in certain languages, the singular or plural form of a noun depends on the number prior to the noun. [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) provides APIs to determine the singular-plural type for a specific locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | -| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | +| PluralRules | constructor()8+ | Creates a **PluralRules** object.| +| PluralRules | constructor(locale:string\|Array<string>,options?:PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes.| +| PluralRules | select(n:number):string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object.| ### How to Develop -1. Instantiate a **PluralRules** object. - - Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var pluralRules = new intl.PluralRules(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). - +2. Instantiate a **PluralRules** object. + + Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **PluralRules** object (**intl** is the name of the imported module). + ```js - var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); + let pluralRules = new Intl.PluralRules(); ``` -2. Determine the singular-plural type. - - Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). ```js - var number = 1234.5678 - var categoryResult = plurals.select(number); + let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); ``` +3. Determine the singular-plural type. -## Formatting the Relative Time + Call **select** to determine the singular-plural type for an input number. This API returns a string as the category of the input number, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. + + ```js + let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); + let number = 1234.5678 + let categoryResult = pluralRules.select(number); // categoryResult = "other" + ``` -Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) APIs to format the relative time for a specific locale. +## Formatting Relative Time +[RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) provides APIs to format the relative time for a specific locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | - +| RelativeTimeFormat | constructor()8+ | Creates a **RelativeTimeFormat** object.| +| RelativeTimeFormat | constructor(locale:string\|Array<string>,options?:RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes.| +| RelativeTimeFormat | format(value:number,unit:string):string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object.| +| RelativeTimeFormat | formatToParts(value:number,unit:string):Array<object>8+ | Obtains each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object.| +| RelativeTimeFormat | resolvedOptions():RelativeTimeFormatResolvedOptions8+ | Obtains the attributes of the **RelativeTimeFormat** object.| ### How to Develop -1. Instantiate a **RelativeTimeFormat** object. +1. Import the **intl** module. - Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object. + Importing an incorrect bundle can lead to unexpected API behavior. + + ```js + import Intl from '@ohos.intl' + ``` + +2. Instantiate a **RelativeTimeFormat** object. + Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **RelativeTimeFormat** object (**intl** is the name of the imported module). ```js - var relativeTimeFormat = new intl.RelativeTimeFormat(); + let relativeTimeFormat = new Intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). ```js - var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); ``` -2. Format the relative time. +3. Format the relative time. - Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. - + Call **format** to format the relative time. This API receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. A string is returned as the formatting result. + ```js - var number = 2; - var unit = "year" - var formatResult = relativeTimeFormat.format(number, unit); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let number = 2; + let unit = "year" + let formatResult = relativeTimeFormat.format(number, unit); // 2 years later ``` -3. Obtain each part of the relative time format. +4. Obtain each part of the relative time format. - Upon obtaining each part of the relative time format, customize the relative time formatting result. - + On obtaining each part of the relative time format, customize the relative time formatting result. + ```js - var number = 2; - var unit = "year" - var formatResult = relativeTimeFormat.formatToParts(number, unit); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let number = 2; + let unit = "year" + let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}] ``` -4. Obtain attributes of the **RelativeTimeFormat** object. +5. Access the attributes of the **RelativeTimeFormat** object. - Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). - + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **RelativeTimeFormat** object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). + ```js - var options = numberFormat.resolvedOptions(); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let options = relativeTimeFormat.resolvedOptions(); // options = {"locale": "zh-CN", "style": "long", "numeric": "always", "numberingSystem": "latn"} ``` ## Samples diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md index 3dde56c84f321a6200c45b1839eccdabcba942aa..f4f5ac69bc57146d6ee63dde171da7628e0a108d 100644 --- a/en/application-dev/napi/mindspore-lite-guidelines.md +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -15,7 +15,6 @@ Before getting started, you need to understand the following basic concepts: **Float16 inference**: a mode in which Float16 is used for inference. Float16, also called half-precision, uses 16 bits to represent a number. - ## Available APIs APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. ### Context APIs @@ -54,6 +53,33 @@ The following figure shows the development process for MindSpore Lite model infe **Figure 1** Development process for MindSpore Lite model inference ![how-to-use-mindspore-lite](figures/01.png) +Before moving to the main process, you need to reference related header files and compile functions to generate random input. + +Example code: + +```c +#include +#include +#include "mindspore/model.h" + +// Generate random input. +int GenerateInputDataWithRandom(OH_AI_TensorHandleArray inputs) { + for (size_t i = 0; i < inputs.handle_num; ++i) { + float *input_data = (float *)OH_AI_TensorGetMutableData(inputs.handle_list[i]); + if (input_data == NULL) { + printf("MSTensorGetMutableData failed.\n"); + return OH_AI_STATUS_LITE_ERROR; + } + int64_t num = OH_AI_TensorGetElementNum(inputs.handle_list[i]); + const int divisor = 10; + for (size_t j = 0; j < num; j++) { + input_data[j] = (float)(rand() % divisor) / divisor; // 0--0.9f + } + } + return OH_AI_STATUS_SUCCESS; +} +``` + The development process consists of the following main steps: 1. Prepare the required model. @@ -101,8 +127,8 @@ The development process consists of the following main steps: return OH_AI_STATUS_LITE_ERROR; } - // Load and build the model. The model type is OH_AI_ModelTypeMindIR. - int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_ModelTypeMindIR, context); + // Load and build the model. The model type is OH_AI_MODELTYPE_MINDIR. + int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_MODELTYPE_MINDIR, context); if (ret != OH_AI_STATUS_SUCCESS) { printf("OH_AI_ModelBuildFromFile failed, ret: %d.\n", ret); OH_AI_ModelDestroy(&model); @@ -193,7 +219,7 @@ The development process consists of the following main steps: dl ) ``` - - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.cmake"`. + - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.camke"`. - The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`. @@ -213,4 +239,4 @@ The development process consists of the following main steps: Tensor name: Softmax-65, tensor size is 4004 ,elements num: 1001. output data is: 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 - ``` + ``` \ No newline at end of file diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index 188b4f1336e2c56562f594e42dc26cabf8a8fc55..5113c413d523b9d58363b78ac94ba42cc1954e9d 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -1,12 +1,14 @@ # Using Native APIs in Application Projects -OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. Currently, the **ace_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository. +OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see **libnapi.ndk.json** in the ace_napi repository. ## How to Develop -The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development. +The DevEco Studio has a default project that uses NAPIs. -You can `import` the native .so that contains the JS processing logic. For example, `import hello from 'libhello.so'` to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the `hello` object of the application to call the native capability. +You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development. + +You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability. ## Development Guidelines @@ -17,7 +19,7 @@ You can `import` the native .so that contains the JS processing logic. For examp ### .so Naming Rules -Each module has a .so file. For example, if the module name is `hello`, name the .so file `libhello.so`. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. +Each module has a .so file. For example, if the module name is **hello**, name the .so file **libhello.so**. The **nm_modname** field in **napi_module** must be **hello**, which is the same as the module name. The sample code for importing the .so file is **import hello from 'libhello.so'**. ### JS Objects and Threads @@ -28,7 +30,7 @@ The Ark engine prevents NAPIs from being called to operate JS objects in non-JS ### Importing Header Files -Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, when only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found. +Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, if only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found. ### napi_create_async_work @@ -50,11 +52,11 @@ napi_status napi_create_async_work(napi_env env, -## Example 1: Encapsulating Synchronous and Asynchronous APIs for the Storage Module +## Encapsulating Synchronous and Asynchronous APIs for the Storage Module ### Overview -This example shows how to encapsulate the synchronous and asynchronous APIs of the storage module. The storage module implements the functions of storing, obtaining, deleting, and clearing data. +This example shows how to encapsulate the synchronous and asynchronous APIs of the **Storage** module. The **Storage** module implements the functions of storing, obtaining, deleting, and clearing data. ### API Declaration @@ -79,11 +81,11 @@ export default storage; ### Implementation -You can obtain the complete code from `sample/native_module_storage/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. +You can obtain the complete code from sample/native_module_storage/ in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. -#### Registering the Module +**1. Register the module.** -Register four synchronous APIs (`getSync`, `setSync`, `removeSync`, and`clearSync`) and four asynchronous APIs (`get`, `set`, `remove`, and `clear`). +Register four synchronous APIs (**getSync**, **setSync**, **removeSync**, and **clearSync**) and four asynchronous APIs (**get**, **set**, **remove**, and **clear**). ```c++ /*********************************************** @@ -122,9 +124,9 @@ extern "C" __attribute__((constructor)) void StorageRegister() } ``` -#### Implementing getSync +**2. Implement getSync.** -The **getSync** function registered for the storage module is **JSStorageGetSync**. Obtain data from `gKeyValueStorage`, create a string object, and return it. +The **getSync** function registered for the **Storage** module is **JSStorageGetSync**. Obtain data from **gKeyValueStorage**, create a string object, and return the object created. ```c static napi_value JSStorageGetSync(napi_env env, napi_callback_info info) @@ -168,9 +170,9 @@ static napi_value JSStorageGetSync(napi_env env, napi_callback_info info) } ``` -#### Implementing get +**3. Implement get().** -The `get` function registered for the storage module is `JSStorageGet`. +The **get** function registered for the **Storage** module is **JSStorageGet**. ```c static napi_value JSStorageGet(napi_env env, napi_callback_info info) @@ -268,7 +270,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info) } ``` -### JS Sample Code +**JS Sample Code** ```js import storage from 'libstorage.so'; @@ -292,11 +294,11 @@ export default { -## Example 2: Binding Native and JS Objects for the NetServer Module +## Binding Native and JS Objects for the NetServer Module ### Overview -This example shows how to implement the `on/off/once` method and bind C++ and JS objects using the **wrap** API. The NetServer module implements the network service. +This example shows how to implement the **on**, **off**, and **once** methods and bind C++ and JS objects using **wrap()**. The **NetServer** module implements the network service. ### API Declaration @@ -312,9 +314,9 @@ export class NetServer { ### Implementation -You can obtain the complete code from `sample/native_module_netserver/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. +You can obtain the complete code from **sample/native_module_netserver/** in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. -#### Registering the Module +**1. Register the module.** ```c static napi_value NetServer::Export(napi_env env, napi_value exports) @@ -338,7 +340,7 @@ static napi_value NetServer::Export(napi_env env, napi_value exports) } ``` -#### Binding C++ and JS Objects in a Constructor +**2. Bind C++ and JS objects in a constructor.** ```c napi_value NetServer::JS_Constructor(napi_env env, napi_callback_info cbinfo) @@ -365,7 +367,7 @@ napi_value NetServer::JS_Constructor(napi_env env, napi_callback_info cbinfo) } ``` -#### Obtaining the C++ Object from the JS Object +**3. Obtain a C++ object from a JS object.** ```c napi_value NetServer::JS_Start(napi_env env, napi_callback_info cbinfo) @@ -398,7 +400,7 @@ napi_value NetServer::JS_Start(napi_env env, napi_callback_info cbinfo) } ``` -After `netServer->Start` is executed, call back the `start` event registered by `on`. +After **netServer->Start** is executed, call back the **start** event registered by **on()**. ```c int NetServer::Start(int port) @@ -435,7 +437,7 @@ int NetServer::Start(int port) } ``` -#### Registering Events (on) +**4. Call on() to register an event observer.** ```c napi_value NetServer::JS_On(napi_env env, napi_callback_info cbinfo) @@ -475,7 +477,7 @@ napi_value NetServer::JS_On(napi_env env, napi_callback_info cbinfo) } ``` -### JS Sample Code +**JS Sample Code** ```javascript import { NetServer } from 'libnetserver.so'; @@ -491,7 +493,7 @@ export default { -## Example 3: Calling Back a JS API in a Non-JS Thread +## Calling Back a JS API in a Non-JS Thread ### Overview @@ -499,11 +501,11 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp ### Implementation -You can obtain the complete code from `sample/native_module_callback/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. +You can obtain the complete code from **sample/native_module_callback/** in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. -#### Registering the Module +**1. Register the module.** -Register the `test` API to pass in a parameter. +Register the **test** API to pass in a parameter. ```c++ /*********************************************** @@ -536,7 +538,7 @@ extern "C" __attribute__((constructor)) void CallbackTestRegister() } ``` -#### Obtaining the Loop in env and Throwing the Task to the JS Thread +**2. Obtain the loop in env and throw the task to a JS thread.** ```c++ #include @@ -627,7 +629,7 @@ static napi_value JSTest(napi_env env, napi_callback_info info) } ``` -### JS Sample Code +**JS Sample Code** ```js import callback from 'libcallback.so'; diff --git a/en/application-dev/notification/Readme-EN.md b/en/application-dev/notification/Readme-EN.md index dccfc8dbc4c59611db4aa53ff8a5a295cbba4d46..bf85581053f30d6aa56e0218c51339ef6ee3f268 100644 --- a/en/application-dev/notification/Readme-EN.md +++ b/en/application-dev/notification/Readme-EN.md @@ -1,9 +1,10 @@ -# Common Event and Notification +# Notification + +- [Notification Overview](notification-overview.md) +- [Notification Subscription (Open Only to System Applications)](notification-subscription.md) +- [Enabling Notification](notification-enable.md) +- Publishing a Notification + - [Publishing a Basic Notification](text-notification.md) + - [Publishing a Progress Notification](progress-bar-notification.md) + - [Adding a WantAgent Object to a Notification](notification-with-wantagent.md) -- [Common Event and Notification Overview](notification-brief.md) -- [Common Event Development](common-event.md) -- [Notification Development](notification-guidelines.md) -- Agent-Powered Scheduled Reminder - - [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md) - - [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md) -- [Debugging Assistant Usage](assistant-guidelines.md) diff --git a/en/application-dev/notification/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md deleted file mode 100644 index 5d83cf443c0f629fcb471a6c12ccd3069ac2e593..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/assistant-guidelines.md +++ /dev/null @@ -1,134 +0,0 @@ -# Debugging Assistant Usage - -The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell. - -## cem Debugging Assistant - -### publish - -* Function - - Publishes a common event. - -* Usage - - `cem publish []` - - The table below describes the available options. - - | Option | Description | - | ------------ | ------------------------------------------ | - | -e/--event | Indicates the name of the common event to publish. Mandatory. | - | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published. | - | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | - | -c/--code | Indicates the result code of the common event. Optional. | - | -d/--data | Indicates the data carried in the common event. Optional. | - | -h/--help | Indicates the help Information | - -* Example - - `cem publish --event "testevent"` - - Publish a common event named **testevent**. - - ![cem-publish-event](figures/cem-publish-event.png) - - - - `cem publish -e "testevent" -s -o -c 100 -d "this is data" ` - - Publish a sticky, ordered common event named **testevent**. The result code of the event is **100** and the data carried is **this is data**. - - ![cem-publish-all](figures/cem-publish-all.png) - -### dump - -* Function - - Displays information about common events. - -* Usage - - `cem dump []` - - The table below describes the available options. - - | Option | Description | - | ---------- | -------------------------------------------- | - | -a/--all | Displays information about all common events that have been sent since system startup. | - | -e/--event | Displays information about a specific event. | - | -h/--help | Displays the help information. | - -* Example - -​ `cem dump -e "testevent"` - -​ Display information about the common event testevent. - -​ ![cem-dump-e](figures/cem-dump-e.png) - -### help - -* Function - - Displays the help information. - -* Usage - - `cem help` - -* Example - - ![cem-help](figures/cem-help.png) - - - -## anm Debugging Assistant - -### dump - -* Function - - Displays information about notifications. - -* Usage - - `anm dump []` - - The table below describes the available options. - - | Option | Description | - | ---------------- | ---------------------------------------- | - | -A/--active | Displays information about all active notifications. | - | -R/--recent | Displays information about the recent notifications. | - | -D/--distributed | Displays information about distributed notifications from other devices. | - | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional. | - | -h/--help | Displays the help information. | - -* Example - - `anm dump -A` - - Display information about all active notifications. - - ![anm-dump-A](figures/anm-dump-A.png) - - - - `anm dump --setRecentCount 10` - - Set the number of the cached recent notifications to be displayed to **10**. - -### help - -* Function - - Displays the help information. - -* Usage - - `anm help` - -* Example - - ![anm-help](figures/anm-help.png) diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md deleted file mode 100644 index dfb611ea572b80486756faaa4b004513cd6858a7..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/common-event.md +++ /dev/null @@ -1,172 +0,0 @@ -# Common Event Development -## Introduction -OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. - -Common events are classified into system common events and custom common events. - -+ System common events: The system sends an event based on system policies to the apps that have subscribed to this event when it occurs. This type of event is typically system events published by key system services, such as HAP installation, update, and uninstallation. - -+ Custom common event: customized by applications to implement cross-application event communication. - -Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application. - -## Common Event Subscription Development - -### When to Use -You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#support). - -### Available APIs -| API | Description| -| ---------------------------------------------------------------------------------------------- | ----------- | -| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| -| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | -| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| - -### How to Develop -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). - -```js -// Used to save the created subscriber object for subsequent subscription and unsubscription. -private subscriber = null - -// Subscriber information -var subscribeInfo = { - events: ["event"], -} -``` - -3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. - -```js -// Callback for subscriber creation. -commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { - if (err.code) { - console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]CreateSubscriber") - this.subscriber = subscriber - this.result = "Create subscriber succeed" - } -}) -``` - -4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). - -```js -// Callback for common event subscription. -if (this.subscriber != null) { - commonEvent.subscribe(this.subscriber, (err, data) => { - if (err.code) { - console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data)) - this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code - } - }) - this.result = "Subscribe succeed" -} else { - prompt.showToast({ message: "Need create subscriber" }) -} -``` - -## Common Event Publishing Development - -### When to Use -You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. - -### Available APIs -| API | Description| -| ---------------------------------- | ------ | -| publish(event: string, callback: AsyncCallback) | Publishes a common event.| -| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| - -### How to Develop -#### Development for Publishing a Common Event -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Pass in the common event name and callback, and publish the event. - -```js -// Publish a common event. -commonEvent.publish("event", (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish1") - } -}) -``` - -#### Development for Publishing a Common Event with Given Attributes -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent' -``` - -2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). - -```js -// Attributes of a common event. -var options = { - code: 1, // Result code of the common event - data: "initial data";// Result data of the common event -} -``` - -3. Pass in the common event name, attributes of the common event, and callback, and publish the event. - -```js -// Publish a common event. -commonEvent.publish("event", options, (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish2") - } -}) -``` - -## Common Event Unsubscription Development - -### When to Use -You can use the **unsubscribe** API to unsubscribe from a common event. - -### Available APIs -| API | Description| -| ---------------------------------- | ------ | -| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| - -### How to Develop -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#common-event-subscription-development). -3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. - -```js -if (this.subscriber != null) { - commonEvent.unsubscribe(this.subscriber, (err) => { - if (err.code) { - console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]Unsubscribe") - this.subscriber = null - this.result = "Unsubscribe succeed" - } - }) -} -``` diff --git a/en/application-dev/notification/figures/anm-dump-A.png b/en/application-dev/notification/figures/anm-dump-A.png deleted file mode 100644 index 368e6f2d810976486e786a4c8f0603a87ad48540..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/anm-dump-A.png and /dev/null differ diff --git a/en/application-dev/notification/figures/anm-help.png b/en/application-dev/notification/figures/anm-help.png deleted file mode 100644 index d80ac8e76a70c2be383f0a05a12e3e707dcf242b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/anm-help.png and /dev/null differ diff --git a/en/application-dev/notification/figures/ans.png b/en/application-dev/notification/figures/ans.png deleted file mode 100644 index 8be552d2acedbef962326365fb2d19ded3838c14..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/ans.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-dump-e.png b/en/application-dev/notification/figures/cem-dump-e.png deleted file mode 100644 index c2422ba0e51011174c333985ad7647f170e0f126..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-dump-e.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-help.png b/en/application-dev/notification/figures/cem-help.png deleted file mode 100644 index 8ca4bc0605f9c1f75a8cb45f8ab77c9c5d6f04e4..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-help.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-publish-all.png b/en/application-dev/notification/figures/cem-publish-all.png deleted file mode 100644 index 99526e1f7245d101914354e2a89d5e97d710c27f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-publish-all.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-publish-event.png b/en/application-dev/notification/figures/cem-publish-event.png deleted file mode 100644 index f0ca7e73093f1be72c743bd7c08467f11e2a0e05..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-publish-event.png and /dev/null differ diff --git a/en/application-dev/notification/figures/ces.png b/en/application-dev/notification/figures/ces.png deleted file mode 100644 index b1aa5438a19ac79899e0f45791f3e1a79e4242dc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/ces.png and /dev/null differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001416585590.png b/en/application-dev/notification/figures/en-us_image_0000001416585590.png new file mode 100644 index 0000000000000000000000000000000000000000..9da6812580fd6c7d785391c652104ef0698ce2bc Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416585590.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001416745530.png b/en/application-dev/notification/figures/en-us_image_0000001416745530.png new file mode 100644 index 0000000000000000000000000000000000000000..7a6fd0d9304abef2eb240a3c78a93b73bb9237af Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416745530.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062434.png b/en/application-dev/notification/figures/en-us_image_0000001417062434.png new file mode 100644 index 0000000000000000000000000000000000000000..07db3298f0db1c3357624b44d271dc1e6f97ea9e Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062434.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062446.png b/en/application-dev/notification/figures/en-us_image_0000001417062446.png new file mode 100644 index 0000000000000000000000000000000000000000..c197fd6293f41890b2bfcf17a28a1477e8aa6d96 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062446.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462297.png b/en/application-dev/notification/figures/en-us_image_0000001466462297.png new file mode 100644 index 0000000000000000000000000000000000000000..a07d9e818677e9364ad3239e61ce198471b68603 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462297.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462305.png b/en/application-dev/notification/figures/en-us_image_0000001466462305.png new file mode 100644 index 0000000000000000000000000000000000000000..740f4b79a9ee234008cad6cf3616a8f213569476 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462305.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582017.png b/en/application-dev/notification/figures/en-us_image_0000001466582017.png new file mode 100644 index 0000000000000000000000000000000000000000..1652d9111be2a27863fe2322c4feb577bab22ae9 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582017.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582045.png b/en/application-dev/notification/figures/en-us_image_0000001466582045.png new file mode 100644 index 0000000000000000000000000000000000000000..4040452a87bc69ae8fa0eb9b55ca77ac32bdb2d8 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582045.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782025.png b/en/application-dev/notification/figures/en-us_image_0000001466782025.png new file mode 100644 index 0000000000000000000000000000000000000000..d8e45c1746ab419a8056f9493c8796cfb734d2d0 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782025.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782033.png b/en/application-dev/notification/figures/en-us_image_0000001466782033.png new file mode 100644 index 0000000000000000000000000000000000000000..218e5fcef6d163113c9037028215297ef626fcfa Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782033.png differ diff --git a/en/application-dev/notification/figures/notification-with-wantagent.png b/en/application-dev/notification/figures/notification-with-wantagent.png new file mode 100644 index 0000000000000000000000000000000000000000..234ef895c918404598cf7640f9d072de2bb2d0d0 Binary files /dev/null and b/en/application-dev/notification/figures/notification-with-wantagent.png differ diff --git a/en/application-dev/notification/figures/notification.png b/en/application-dev/notification/figures/notification.png deleted file mode 100644 index 18dcb99b0c531a19698f749105d88db91043837a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/notification.png and /dev/null differ diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md deleted file mode 100644 index 75237412fdf29d88843a9f23fa653f64f2de7c86..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/notification-brief.md +++ /dev/null @@ -1,20 +0,0 @@ -# Common Event and Notification Overview - -The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more. - -Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. - -![ces](figures/ces.png) - -- System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events. -- Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications. - -The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: - -- Display received SMS messages and instant messages. -- Display push messages of applications, such as advertisements, version updates, and news notifications. -- Display ongoing events, such as music playback, navigation information, and download progress. - -Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions. - -![ans](figures/ans.png) diff --git a/en/application-dev/notification/notification-enable.md b/en/application-dev/notification/notification-enable.md new file mode 100644 index 0000000000000000000000000000000000000000..12aa4f41eb1570d707b4c65310cefe6aa45e1b17 --- /dev/null +++ b/en/application-dev/notification/notification-enable.md @@ -0,0 +1,49 @@ +# Enabling Notification + + +To publish a notification, you must have notification enabled for your application. You can call the [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) API to display a dialog box prompting the user to enable notification for your application. Note that the dialog box is displayed only when the API is called for the first time. + + **Figure 1** Dialog box prompting the user to enable notification + +![en-us_image_0000001416585590](figures/en-us_image_0000001416585590.png) + + +- Touching **allow** enables notification for the application, and touching **ban** keeps notification disabled. + +- The dialog box will not be displayed again when [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) is called later. The user can manually enable notification as follows. + + | 1. Swipe down from the upper left corner of the device screen to access the notification panel. | 2. Touch the **Settings** icon in the upper right corner. On the notification screen, locate the target application.| 3. Toggle on **Allow notifications**. | + | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | + | ![en-us_image_0000001417062434](figures/en-us_image_0000001417062434.png) | ![en-us_image_0000001466462297](figures/en-us_image_0000001466462297.png) | ![en-us_image_0000001466782025](figures/en-us_image_0000001466782025.png) | + + +## Available APIs + +For details about the APIs, see [@ohos.notificationManager](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification). + +**Table 1** Notification APIs + +| Name | Description | +| -------- | -------- | +| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback<boolean>): void | Checks whether notification is enabled.
**NOTE**
This is a system API and cannot be called by third-party applications. | +| setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback<void>): void | Sets whether to enable notification. Notification can be enabled or disabled in **Notifications** of the target application under **Settings** > **Apps & services** > **Apps**.
**NOTE**
This is a system API and cannot be called by third-party applications.| +| requestEnableNotification(callback: AsyncCallback<void>): void | Requests notification to be enabled. When called for the first time, this API displays a dialog box prompting the user to enable notification. | + + +## How to Develop + +1. Import the **NotificationManager** module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +2. Call the API to request notification to be enabled. + + ```ts + notificationManager.requestEnableNotification().then(() => { + console.info(`[ANS] requestEnableNotification success`); + }).catch((err) => { + console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`); + }); + ``` diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md deleted file mode 100644 index fb73f274202aafd9ff852201ca2fb8c5116aba50..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/notification-guidelines.md +++ /dev/null @@ -1,258 +0,0 @@ - - -# Notification Development - -## When to Use - -OpenHarmony uses the Advanced Notification Service (ANS) to manage notifications, with support for various notification types, including text, long text, multi-text, image, social, and media. All system services and applications can send notifications through the notification API. Users can view all notifications on the system UI. - -Below are some typical use cases for notifications: - -- Display received SMS messages and instant messages. -- Display push messages of applications, such as advertisements and version updates. -- Display ongoing events, such as navigation information and download progress. - - - -## Notification Service Process - -The notification service process involves the ANS subsystem, notification sender, and notification subscriber. - -A notification is generated by the notification sender and sent to the ANS through inter-process communication (IPC). The ANS then distributes the notification to the notification subscriber. - -System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the ANS for storage in the memory and database. - -![1648113187545](figures/notification.png) - - - -## Available APIs - -Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md). - -**Table 1** APIs for notification enabling - -| API | Description | -| ------------------------------------------------------------ | ---------------- | -| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.| -| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. | - -If the notification function of an application is disabled, it cannot send notifications. - - - -**Table 2** APIs for notification subscription - -| API | Description | -| ------------------------------------------------------------ | ---------------- | -| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void | Subscribes to a notification with the subscription information specified.| -| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Subscribes to all notifications. | -| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Unsubscribes from a notification. | - -The subscription APIs support subscription to all notifications and notifications from specific applications. - - - -**Table 3** Notification subscription callbacks - -| API | Description | -| ------------------------------------------------ | ---------------- | -| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | -| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | -| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.| -| onConnect?:() => void; | Callback for subscription. | -| onDisconnect?:() => void; | Callback for unsubscription. | - - - -**Table 4** APIs for notification sending - -| API | Description | -| ------------------------------------------------------------ | ------------------------ | -| publish(request: NotificationRequest, callback: AsyncCallback\): void | Publishes a notification. | -| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void | Publishes a notification to the specified user. | -| cancel(id: number, label: string, callback: AsyncCallback\): void | Cancels a specified notification. | -| cancelAll(callback: AsyncCallback\): void; | Cancels all notifications published by the application.| - -The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. - - - -## Development Guidelines - -The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications. - -### Modules to Import - -```js -import Notification from '@ohos.notification'; -``` - - - -### Subscribing to Notifications - -The notification recipient preferentially initiates a notification subscription request to the notification subsystem. - -```js -var subscriber = { - onConsume: function (data) { - let req = data.request; - console.info('===>onConsume callback req.id: ' + req.id); - }, - onCancel: function (data) { - let req = data.request; - console.info('===>onCancel callback req.id: : ' + req.id); - }, - onUpdate: function (data) { - console.info('===>onUpdate in test===>'); - }, - onConnect: function () { - console.info('===>onConnect in test===>'); - }, - onDisconnect: function () { - console.info('===>onDisConnect in test===>'); - }, - onDestroy: function () { - console.info('===>onDestroy in test===>'); - }, - }; - - Notification.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. - if (err.code) { - console.error('===>failed to subscribe because ' + JSON.stringify(err)); - return; - } - console.info('===>subscribeTest success : ' + JSON.stringify(data)); - }); -``` - - - -### Publishing Notifications - -##### Enabling Notification - -Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature. - -```js -Notification.requestEnableNotification().then((data) => { - console.info('===>requestEnableNotification success'); -}).catch((err) => { - console.error('===>requestEnableNotification failed because ' + JSON.stringify(err)); -}); -``` - - - -##### Publishing Notifications - -To publish a notification, create a **NotificationRequest** object and set attributes such as the notification type, title, and content. In the following examples, a normal text notification and a notification containing a **WantAgent** are being published. - -Normal text notification: - -```js -// Create a NotificationRequest object. -var notificationRequest = { - id: 1, - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "test_title", - text: "test_text", - additionalText: "test_additionalText" - } - } -} - -// Publish the notification. -Notification.publish(notificationRequest).then((data) => { - console.info('===>publish promise success req.id : ' + notificationRequest.id); -}).catch((err) => { - console.error('===>publish promise failed because ' + JSON.stringify(err)); -}); -``` - - - -Notification containing **WantAgent**: - -For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md). - -- Create a **WantAgent** object. - -```js -import wantAgent from '@ohos.wantAgent'; - -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - bundleName: 'ohos.samples.eTSNotification', - abilityName: 'ohos.samples.eTSNotification.MainAbility', - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -// WantAgent object -var WantAgent; - -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("===>getWantAgentCallback===>"); - if (err.code == 0) { - WantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} - -// Obtain the WantAgent object. -wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) -``` - -- Publish the notification. - -```js -// Create a NotificationRequest object. -var notificationRequest = { - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "AceApplication_Title", - text: "AceApplication_Text", - additionalText: "AceApplication_AdditionalText" - }, - }, - id: 1, - label: 'TEST', - wantAgent: WantAgent, - slotType: Notification.SlotType.OTHER_TYPES, - deliveryTime: new Date().getTime() -} - -// Publish the notification. -Notification.publish(notificationRequest).then((data) => { - console.info('===>publish promise success req.id : ' + notificationRequest.id); -}).catch((err) => { - console.error('===>publish promise failed because ' + JSON.stringify(err)); -}); -``` - - - -- Cancel the notification. - -An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself. - -```js -// cancel callback -function cancelCallback(err) { - console.info("===>cancelCallback===>"); -} - -Notification.cancel(1, "label", cancelCallback) -``` diff --git a/en/application-dev/notification/notification-overview.md b/en/application-dev/notification/notification-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6bef8be8fd446e62b3e3da04582b467c9ddc5961 --- /dev/null +++ b/en/application-dev/notification/notification-overview.md @@ -0,0 +1,27 @@ +# Notification Overview + + +## Introduction + +All system applications and services can publish notifications through the notification APIs. Users can view the notifications in the notification panel or click a notification to open the publishing application. + +Below are some typical use cases for notifications: + +- Display received SMS messages and instant messages. + +- Display push messages, such as advertisements and version updates. + +- Display ongoing events, such as the download progress. + +The Advanced Notification Service (ANS) in OpenHarmony is used to manage notifications of various types, such as basic notifications, progress notifications, and reminders published through the background agent. + + +## Notification Service Process + +The notification service process involves the notification subsystem, notification sender, and notification subscriber. + +A notification is generated by the notification sender and sent to the notification subsystem through [inter-process communication (IPC)](../connectivity/ipc-rpc-overview.md). The notification subsystem then distributes the notification to the notification subscriber. + +System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the notification subsystem for storage in the memory and database. + +![en-us_image_0000001466582017](figures/en-us_image_0000001466582017.png) diff --git a/en/application-dev/notification/notification-subscription.md b/en/application-dev/notification/notification-subscription.md new file mode 100644 index 0000000000000000000000000000000000000000..a633a2bb955bcf877fbe4befb8b40ad103d7e7e6 --- /dev/null +++ b/en/application-dev/notification/notification-subscription.md @@ -0,0 +1,82 @@ +# Notification Subscription (Open Only to System Applications) + + +To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application. + + +You can use the **NotificationSubscriber** object to provide callbacks for subscription events, such as subscription success, notification reception, notification cancellation, and subscription cancellation. + + +## Available APIs + +The major APIs for notification subscription are described as follows. For details about the APIs, see [@ohos.notificationSubscribe](../reference/apis/js-apis-notificationSubscribe.md). + +**Table 1** Major APIs for notification subscription + +| Name | Description| +| -------- | -------- | +| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback<void>): void | Subscribes to notifications from a specific application.| +| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Subscribes to notifications from all applications. | + +**Table 2** Callbacks for notification subscription + +| Name | Description| +| -------- | -------- | +| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | +| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | +| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates. | +| onConnect?:() => void; | Callback for subscription. | +| onDisconnect?:() => void; | Callback for unsubscription. | +| onDestroy?:() => void | Callback for disconnecting from the notification subsystem. | +| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) => void | Callback for the Do Not Disturb (DNT) time changes.| +| onEnabledNotificationChanged?:(callbackData: EnabledNotificationCallbackData) => void | Callback for notification switch changes. | + + +## How to Develop + +1. Request the **ohos.permission.NOTIFICATION_CONTROLLER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Import the **notificationSubscribe** module. + + ```ts + import notificationSubscribe from '@ohos.notificationSubscribe'; + ``` + +3. Create a **subscriber** object. + + ```ts + let subscriber = { + onConsume: function (data) { + let req = data.request; + console.info('[ANS] onConsume callback req.id: ' + req.id); + }, + onCancel: function (data) { + let req = data.request; + console.info('[ANS] onCancel callback req.id: : ' + req.id); + }, + onUpdate: function (data) { + console.info('[ANS] onUpdate in test'); + }, + onConnect: function () { + console.info('[ANS] onConnect in test'); + }, + onDisconnect: function () { + console.info('[ANS] onDisConnect in test'); + }, + onDestroy: function () { + console.info('[ANS] onDestroy in test'); + }, + }; + ``` + +4. Initiate notification subscription. + + ```ts + notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. + if (err) { + console.error(`[ANS] failed to subscribe, error[${err}]`); + return; + } + console.info(`[ANS] subscribeTest success : + ${data}`); + }); + ``` diff --git a/en/application-dev/notification/notification-with-wantagent.md b/en/application-dev/notification/notification-with-wantagent.md new file mode 100644 index 0000000000000000000000000000000000000000..d8f0321d28738749d6ed6073e49f26181c22e706 --- /dev/null +++ b/en/application-dev/notification/notification-with-wantagent.md @@ -0,0 +1,121 @@ +# Adding a WantAgent Object to a Notification + +A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsulates an intention to start a specified ability, release a common event, and more. In OpenHarmony, a **WantAgent** object can be passed in a notification from the publisher to the subscriber, so as to trigger the intention specified. For example, you may want the user to start a specific ability by touching the notification published by your application. In this case, you can add a **WantAgent** object that encapsulates such an action to the notification. After receiving the **WantAgent** object, the system triggers it once the user touches the notification from the notification panel, starting the specified ability. + +Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered. + + **Figure 1** Publishing a notification with a WantAgent object +![notification-with-wantagent](figures/notification-with-wantagent.png) + + +## Available APIs + +For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). + +| Name| Description| +| -------- | -------- | +| getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void | Creates a **WantAgent** object.| +| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void | Triggers a **WantAgent** object.| +| cancel(agent: WantAgent, callback: AsyncCallback<void>): void | Cancels a **WantAgent** object.| +| getWant(agent: WantAgent, callback: AsyncCallback<Want>): void | Obtains a **WantAgent** object.| +| equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void | Checks whether two **WantAgent** objects are equal. | + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the modules. + + ```typescript + import notificationManager from '@ohos.notificationManager'; + import wantAgent from '@ohos.app.ability.wantAgent'; + ``` + +3. Create a **WantAgentInfo** object. + + Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component. + + ```typescript + let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations. + + // Set the action type through operationType of WantAgentInfo. + let wantAgentInfo = { + wants: [ + { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: '', + entities: [], + uri: '', + parameters: {} + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] + }; + ``` + + Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md). + + ```typescript + let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations. + + // Set the action type through operationType of WantAgentInfo. + let wantAgentInfo = { + wants: [ + { + action: 'event_name', // Set the action name. + parameters: {}, + } + ], + operationType: wantAgent.OperationType.SEND_COMMON_EVENT, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], + } + ``` + +4. Invoke the [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) API to create a **WantAgent** object. + + ```typescript + // Create a WantAgent object. + wantAgent.getWantAgent(wantAgentInfo, (err, data) => { + if (err) { + console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err)); + return; + } + console.info('[WantAgent]getWantAgent success'); + wantAgentObj = data; + }); + ``` + +5. Create a **NotificationRequest** object and publish a notification that carries the **WantAgent** object. + + ```typescript + // Create a NotificationRequest object. + let notificationRequest = { + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: 'Test_Title', + text: 'Test_Text', + additionalText: 'Test_AdditionalText', + }, + }, + id: 1, + label: 'TEST', + wantAgent: wantAgentObj, + } + + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + +6. When the user touches the notification from the notification panel, the system automatically triggers the action specified in the **WantAgent** object. diff --git a/en/application-dev/notification/progress-bar-notification.md b/en/application-dev/notification/progress-bar-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..de430008e3048532e9afea94d83a62dd2f8342c1 --- /dev/null +++ b/en/application-dev/notification/progress-bar-notification.md @@ -0,0 +1,69 @@ +# Publishing a Progress Notification + + +The progress notification is a commonly used notification type, mainly used to display the progress of an ongoing operation, such as file downloading. When publishing a progress notification through the notification subsystem, you can use the readily available template by specifying the related attributes, such as the template name and template data. + +In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data. + + +## Available APIs + +| Name| Description| +| -------- | -------- | +| isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result.
Only the progress-type template is supported.| + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +3. Check whether a specific template is supported. In this example, the template of the **downloadTemplate** type is checked. + + ```ts + notificationManager.isSupportTemplate('downloadTemplate').then((data) => { + console.info(`[ANS] isSupportTemplate success`); + let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite. + // ... + }).catch((err) => { + console.error(`[ANS] isSupportTemplate failed, error[${err}]`); + }); + ``` + + > **NOTE** + > + > Proceed with the step below only when the specified template is supported. +4. Create a **NotificationRequest** object and publish a progress notification. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText' + } + }, + // Create a progress template. The name field has a fixed value of downloadTemplate. + template: { + name: 'downloadTemplate', + data: { title: 'File Title', fileName: 'music.mp4', progressValue: 45 } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success `); + }); + ``` diff --git a/en/application-dev/notification/text-notification.md b/en/application-dev/notification/text-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..ddbc5478cee37208da33d2acecb71417deaccdc2 --- /dev/null +++ b/en/application-dev/notification/text-notification.md @@ -0,0 +1,160 @@ +# Publishing a Basic Notification + + +You can publish basic notifications to send SMS messages, prompt messages, and advertisements. Available content types of basic notifications include normal text, long text, multi-line text, and picture-attached. + + + **Table 1** Basic notification content types + +| Type| Description| +| -------- | -------- | +| NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification.| +| NOTIFICATION_CONTENT_LONG_TEXT | Long text notification.| +| NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| +| NOTIFICATION_CONTENT_PICTURE | Picture-attached notification.| + + +Notifications are displayed in the notification panel, which is the only system subscriber to notifications. Below you can see two examples of the basic notification. + +**Figure 1** Examples of the basic notification +![en-us_image_0000001466462305](figures/en-us_image_0000001466462305.png) + + +## Available APIs + +The following table describes the APIs for notification publishing. You specify the notification type by setting the [NotificationRequest](../reference/apis/js-apis-notificationManager.md#notificationrequest) parameter in the APIs. + +| Name| Description| +| -------- | -------- | +| publish(request: NotificationRequest, callback: AsyncCallback<void>): void | Publishes a notification. | +| cancel(id: number, label: string, callback: AsyncCallback<void>): void | Cancels a notification. | +| cancelAll(callback: AsyncCallback<void>): void; | Cancels all notifications published by the application.| + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +3. Create a **NotificationRequest** object and publish a progress notification. + - A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification + normal: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + } + } + } + + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the normal text notification. + ![en-us_image_0000001466782033](figures/en-us_image_0000001466782033.png) + - In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification + longText: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + longText: 'test_longText', + briefText: 'test_briefText', + expandedTitle: 'test_expandedTitle', + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the long-text notification. + ![en-us_image_0000001416745530](figures/en-us_image_0000001416745530.png) + - In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification + multiLine: { + title: 'test_title', + text: 'test_text', + briefText: 'test_briefText', + longTitle: 'test_longTitle', + lines: ['line_01', 'line_02', 'line_03', 'line_04'], + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the multi-line notification. + ![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png) + - In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB. + + ```ts + let notificationPicture: PixelMap = undefined; // Obtain the pixel map information. + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE, + picture: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + briefText: 'test_briefText', + expandedTitle: 'test_expandedTitle', + picture: notificationPicture + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success `); + }); + ``` + + Below is an example of the picture-attached notification. + ![en-us_image_0000001466582045](figures/en-us_image_0000001466582045.png) diff --git a/en/application-dev/quick-start/figures/02.png b/en/application-dev/quick-start/figures/02.png index 19dd76ca232282b19883dde63075c5d155e7db70..eef374a1fd63f2b1e4d72e3323e7f4c23f5705fb 100644 Binary files a/en/application-dev/quick-start/figures/02.png and b/en/application-dev/quick-start/figures/02.png differ diff --git a/en/application-dev/quick-start/figures/04.png b/en/application-dev/quick-start/figures/04.png index cf23d17c7ee8552e30a5b234c97862b51981dcf8..1190d1e5aa631b12171632d258e4c4fae32e9bba 100644 Binary files a/en/application-dev/quick-start/figures/04.png and b/en/application-dev/quick-start/figures/04.png differ diff --git a/en/application-dev/quick-start/figures/07.png b/en/application-dev/quick-start/figures/07.png index 0f34d01d824ae1780c73cade9a39fff5f4b9b84e..17f2b060d300667ff250935b6a37485843e854ce 100644 Binary files a/en/application-dev/quick-start/figures/07.png and b/en/application-dev/quick-start/figures/07.png differ diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 7ec2ef1b9e52f9d3e4e53a0caa9bcfd5a9498c9f..80d0336aa005712ce116d5eb131ab299c1bff006 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -196,21 +196,22 @@ - Security - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) + - [@ohos.security.cert (Certificate)](js-apis-cert.md) - [@ohos.security.cryptoFramework (Crypto Framework)](js-apis-cryptoFramework.md) - [@ohos.security.huks (HUKS)](js-apis-huks.md) - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - Data Management - - [@ohos.data.dataAbility ](js-apis-data-ability.md) - - [@ohos.data.dataShare](js-apis-data-dataShare.md) - - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - - [@ohos.data.preferences](js-apis-data-preferences.md) - - [@ohos.data.rdb](js-apis-data-rdb.md) - - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md) + - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) + - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) + - [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md) + - [@ohos.data.dataShareResultSet (DataShare Result Set)](js-apis-data-DataShareResultSet.md) + - [@ohos.data.distributedDataObject (Distributed Data Object)](js-apis-data-distributedobject.md) + - [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md) + - [@ohos.data.preferences (Preferences)](js-apis-data-preferences.md) + - [@ohos.data.rdb (RDB)](js-apis-data-rdb.md) + - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - data/rdb - [resultSet](js-apis-data-resultset.md) - File Management @@ -325,7 +326,7 @@ - [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md) - Language Base Class Library - - [@ohos.buffer](js-apis-buffer.md) + - [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.process](js-apis-process.md) - [@ohos.uri](js-apis-uri.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md index b3476c86cce52d57a0d54c6b01c1fbed71076ef9..13fa28f551fe677055c589c11a0b4a1b581757b5 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @@ -1,10 +1,10 @@ # BundleStatusCallback -The **BundleStatusCallback** module provides bundle callback information, which is obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md). +The **BundleStatusCallback** module provides callbacks for bundle status changes. The changes can be obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md). > **NOTE** > -> This module is deprecated since API version 9. You are advised to use [bundleMonitor](js-apis-bundleMonitor.md) instead. +> 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. ## BundleStatusCallback(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index 40725aefbf65838c8da46d75a13368c68118df0d..f45268cb699527ed412518bdee3b5f8b41f6520f 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -1,4 +1,4 @@ -# @ohos.bundle.innerBundleManager +# @ohos.bundle.innerBundleManager (innerBundleManager) The **innerBundleManager** module provides APIs for the **Home Screen** application. @@ -22,7 +22,7 @@ SystemCapability.BundleManager.BundleFramework getLauncherAbilityInfos(bundleName: string, userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; Obtains the launcher ability information based on a given bundle name. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetlauncherabilityinfo9) instead. **Required permissions** @@ -38,11 +38,11 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The value must be greater than or equal to 0.| -| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| bundleName | string | Yes | Bundle name. | +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information.| ## innerBundleManager.getLauncherAbilityInfos(deprecated) @@ -50,7 +50,7 @@ This is a system API and cannot be called by third-party applications. getLauncherAbilityInfos(bundleName: string, userId: number) : Promise<Array<LauncherAbilityInfo>> Obtains the launcher ability information based on a given bundle name. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetlauncherabilityinfo9) instead. **Required permissions** @@ -66,9 +66,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ----------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ----------------------------- | +| bundleName | string | Yes | Bundle name. | | userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** @@ -82,7 +82,7 @@ This is a system API and cannot be called by third-party applications. on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback, callback: AsyncCallback<string>) : void; Registers a callback to receive bundle status changes. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#on](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.on](js-apis-bundleMonitor.md#bundlemonitoron) instead. **Required permissions** @@ -109,7 +109,7 @@ This is a system API and cannot be called by third-party applications. on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback) : Promise<string> Registers a callback to receive bundle status changes. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#on](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.on](js-apis-bundleMonitor.md#bundlemonitoron) instead. **Required permissions** @@ -141,7 +141,7 @@ This is a system API and cannot be called by third-party applications. off(type:"BundleStatusChange", callback: AsyncCallback<string>) : void; Deregisters the callback that receives bundle status changes. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#off](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.off](js-apis-bundleMonitor.md#bundlemonitoroff) instead. **Required permissions** @@ -167,7 +167,7 @@ This is a system API and cannot be called by third-party applications. off(type:"BundleStatusChange") : Promise<string> Deregisters the callback that receives bundle status changes. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#off](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.off](js-apis-bundleMonitor.md#bundlemonitoroff) instead. **Required permissions** @@ -198,7 +198,7 @@ This is a system API and cannot be called by third-party applications. getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; Obtains the information about all launcher abilities. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetalllauncherabilityinfo9) instead. **Required permissions** @@ -224,7 +224,7 @@ This is a system API and cannot be called by third-party applications. getAllLauncherAbilityInfos(userId: number) : Promise<Array<LauncherAbilityInfo>> Obtains the information about all launcher abilities. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetalllauncherabilityinfo9) instead. **Required permissions** @@ -255,7 +255,7 @@ This is a system API and cannot be called by third-party applications. getShortcutInfos(bundleName :string, callback: AsyncCallback<Array<ShortcutInfo>>) : void; Obtains the shortcut information based on a given bundle name. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getShortcutInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getShortcutInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetshortcutinfo9) instead. **Required permissions** @@ -273,7 +273,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| bundleName | string | Yes | Bundle name. | | callback | AsyncCallback\> | Yes | Callback used to return an array of the shortcut information.| ## innerBundleManager.getShortcutInfos(deprecated) @@ -281,7 +281,7 @@ This is a system API and cannot be called by third-party applications. getShortcutInfos(bundleName : string) : Promise<Array<ShortcutInfo>> Obtains the shortcut information based on a given bundle name. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getShortcutInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getShortcutInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetshortcutinfo9) instead. **Required permissions** @@ -299,7 +299,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md index 493b263bd25d74fa7cfa5d9c59a45659fb4b5740..eda69bbe8857d6d787753bc91247dcde124f9633 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -1,4 +1,4 @@ -# distributedBundle +# @ohos.distributedBundle (Distributed Bundle Management) The **distributedBundle** module manages distributed bundles. @@ -26,7 +26,7 @@ For details, see [Permission Levels](../../security/accesstoken-overview.md#perm ## distributedBundle.getRemoteAbilityInfodeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void; @@ -55,7 +55,7 @@ This is a system API and cannot be called by third-party applications. ## distributedBundle.getRemoteAbilityInfodeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo> @@ -87,7 +87,7 @@ This is a system API and cannot be called by third-party applications. ## distributedBundle.getRemoteAbilityInfosdeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void; @@ -116,7 +116,7 @@ This is a system API and cannot be called by third-party applications. ## distributedBundle.getRemoteAbilityInfosdeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>> diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 83cf9c77d2899e1c0c0969be8199c602e4374816..5908fc527c4d6f1c1a3391671a0ac9dcc4b41d6f 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1,4 +1,4 @@ -# @ohos.bundle +# @ohos.bundle (Bundle) The **bundle** module provides APIs for obtaining information about an application, including [bundle information](js-apis-bundle-BundleInfo.md), [application information](js-apis-bundle-ApplicationInfo.md), and [ability information](js-apis-bundle-AbilityInfo.md). It also provides APIs to obtain and set the application disabling state. @@ -15,10 +15,11 @@ import bundle from '@ohos.bundle'; | Required Permissions | Permission Level | Description | |--------------------------------------------|--------------|---------------| -| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle. | +| ohos.permission.CHANGE_ABILITY_ENABLED_STATE | system_basic | Permission to enable or disable an application or ability.| +| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle.| | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles. | | ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall bundles. | -| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status.| +| ohos.permission.REMOVE_CACHE_FILES | system_basic | Permission to clear cache files of a bundle.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -44,7 +45,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | 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. | @@ -90,9 +91,9 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -133,8 +134,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -172,20 +173,21 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** | Type | Description | | --------------------------- | -------------------------- | -| Promise> | Promise used to return the information of all available bundles.| +| Promise> | Promise used to return the information of all bundles.| **Example** ```ts let bundleFlag = 0; let userId = 100; + bundle.getAllBundleInfo(bundleFlag, userId) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -215,7 +217,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | **Example** @@ -252,7 +254,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | |------------|-------------------------------------------------------------------|-----|---------------------------------------------------------------------| -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | | @@ -294,9 +296,9 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- |---------------------------------------------------------------------| -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| options | [BundleOptions](#bundleoptions) | No | Options that contain the user ID. | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| +| options | [BundleOptions](#bundleoptionsdeprecated) | No | Options that contain the user ID. | **Return value** @@ -310,7 +312,7 @@ SystemCapability.BundleManager.BundleFramework let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { - "userId" : 100 + "userId": 100 }; bundle.getBundleInfo(bundleName, bundleFlags, options) .then((data) => { @@ -340,11 +342,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------------------------------- | ---- |---------------------------------------------------------------------| -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -360,7 +362,6 @@ bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { }) ``` - ## bundle.getBundleInfodeprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo) instead. @@ -383,9 +384,9 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| +| options | [BundleOptions](#bundleoptionsdeprecated) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -394,7 +395,7 @@ SystemCapability.BundleManager.BundleFramework let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { - "userId" : 100 + "userId": 100 }; bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { if (err) { @@ -504,7 +505,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -545,7 +546,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** @@ -589,7 +590,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- |--------------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -629,9 +630,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------- | ---- |------------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ----------------------------------------------- | +| bundleName | string | Yes | Bundle name. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| **Return value** @@ -720,7 +721,7 @@ let flag = bundle.BundleFlag.GET_ABILITY_INFO_WITH_PERMISSION; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.getAbilityInfo(want, flag, userId).then((abilityInfo) => { @@ -760,7 +761,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | | permissionName | string | Yes | Name of the permission. | -| callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef)> | Yes | Callback used to return the permission details.| +| callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef.md)> | Yes | Callback used to return the permission details.| **Example** @@ -805,7 +806,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | ------------------------------------------------------ | ------------------------------------------------------ | -| Promise<[PermissionDef](js-apis-bundle-PermissionDef)> | Promise used to return the permission details.| +| Promise<[PermissionDef](js-apis-bundle-PermissionDef.md)> | Promise used to return the permission details.| **Example** @@ -838,7 +839,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -880,7 +881,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the application information. | @@ -919,7 +920,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -952,11 +953,11 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The absolute path of the application and the data directory sandbox path are supported.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| **Return value** -| Type | Description | -| -------------- | -------------------------------------- | +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | | Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the information about the bundles.| **Example** @@ -989,7 +990,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored.. The absolute path of the application and the data directory sandbox path are supported.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.| **Example** @@ -1006,7 +1007,6 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { }) ``` - ## bundle.getAbilityInfodeprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead. @@ -1029,7 +1029,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- |------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name.| | abilityName | string | Yes | Ability name.| **Return value** @@ -1042,7 +1042,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1073,7 +1073,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------ | ---- |----------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | abilityName | string | Yes | Ability name. | | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| @@ -1081,7 +1081,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -1111,10 +1111,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|--------|-----|------------| -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name.| +| abilityName | string | Yes | Ability name. | **Return value** @@ -1126,7 +1126,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityLabel(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1155,17 +1155,17 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|------------------------|-----|-------------------------| -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Ability name. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| abilityName | string | Yes | Ability name. | | callback | AsyncCallback\ | Yes | Callback used to return the application name.| **Example** ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -1197,13 +1197,13 @@ SystemCapability.BundleManager.BundleFramework | Type | Description | | ----------------- | ------------------------- | -| Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Promise\ | Promise used to return the result. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ bundle.isAbilityEnabled(abilityInfo).then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1230,13 +1230,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ----------------------- | | info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. | -| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the ability is enabled, and **false** means the opposite.| **Example** ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ bundle.isAbilityEnabled(abilityInfo, (err, data) => { if (err) { @@ -1264,13 +1264,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** | Type | Description | | ----------------- | ------------------------- | -| Promise\ | Promise used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Promise\ | Promise used to return the result. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -1300,8 +1300,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ----------------------- | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of the application.| -| callback | AsyncCallback\ | Yes | Callback used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned. | +| bundleName | string | Yes | Bundle name.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -1322,7 +1322,7 @@ bundle.isApplicationEnabled(bundleName, (err, data) => { queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> -Obtains the ability information based on a given want. This API uses a promise to return the result. +Obtains the ability information based on given Want. This API uses a promise to return the result. No permission is required for obtaining the caller's own information. @@ -1338,8 +1338,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ------------------------------------- | -| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| want | [Want](js-apis-application-want.md) | Yes | Want containing the bundle name | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -1355,7 +1355,7 @@ let bundleFlags = 0; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, userId) .then((data) => { @@ -1373,7 +1373,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the ability information of the specified user based on a given want. This API uses an asynchronous callback to return the result. +Obtains the ability information of the specified user based on given Want. This API uses an asynchronous callback to return the result. No permission is required for obtaining the caller's own information. @@ -1387,12 +1387,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| -| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Want containing the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflagdeprecated).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -1401,7 +1401,7 @@ let bundleFlags = 0; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { if (err) { @@ -1418,7 +1418,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void; -Obtains the ability information based on a given want. This API uses an asynchronous callback to return the result. +Obtains the ability information based on given Want. This API uses an asynchronous callback to return the result. No permission is required for obtaining the caller's own information. @@ -1432,11 +1432,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| -| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Want containing the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflagdeprecated).| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -1444,7 +1444,7 @@ SystemCapability.BundleManager.BundleFramework let bundleFlags = 0; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { if (err) { @@ -1477,7 +1477,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** | Type | Description | @@ -1516,7 +1516,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------- | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the **Want** object.| **Example** @@ -1582,9 +1582,9 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|----------|------------------------|-----|----------------------------| -| uid | number | Yes | UID based on which the bundle name is to obtain. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------------------------------- | +| uid | number | Yes | UID based on which the bundle name is to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -1621,10 +1621,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- |-----------------| -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------ | +| bundleName | string | Yes | Bundle name.| +| abilityName | string | Yes | Ability name. | **Return value** | Type | Description | @@ -1635,7 +1635,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityIcon(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1667,7 +1667,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- |-------------------------------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | abilityName | string | Yes | Ability name. | | callback | AsyncCallback\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| @@ -1675,7 +1675,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index c9cc2b79ba9aed4400fdc52bd938c5e3db711b6b..a55ab990ef39072d83989526e66723eab794ca63 100644 --- a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -1,4 +1,4 @@ -# @ohos.enterprise.EnterpriseAdminExtensionAbility +# @ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility) The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators. diff --git a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index e7be32c9b840dbe67f99e120e3798ad5ecd9fcd4..a22f7b48a977066e085da4b9ddfcdeb24f21463f 100644 --- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -1,4 +1,4 @@ -# Work Scheduler Callbacks +# @ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks) The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks. 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 84033dd0a9d22eba5ffe275c38f078bfb0649b83..37bf04c704a91f0580fddf99b14f9f52fb94d683 100644 --- a/en/application-dev/reference/apis/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -1,4 +1,4 @@ -# @ohos.ability.ability +# @ohos.ability.ability (Ability) The **Ability** module provides all level-2 module APIs for developers to export. diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index f77fd415a1bb7dd8a7d8968f96dce2718f2873ed..d345bbb9db0739da16156ecfc0bd4fe344989149 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -14,10 +14,10 @@ This module provides APIs for accessing ability-specific resources. You can use Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. ```ts -import Ability from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; - let context = undefined; -class MainAbility extends Ability { +let context = undefined; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { context = this.context; } @@ -30,8 +30,8 @@ class MainAbility extends Ability { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| abilityInfo | AbilityInfo | Yes| No| Ability information.| -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| +| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| Ability information.| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the current HAP.| | config | [Configuration](js-apis-application-configuration.md) | Yes| No| Configuration information.| ## AbilityContext.startAbility @@ -40,6 +40,11 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; Starts an ability. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -54,13 +59,14 @@ Starts an ability. This API uses an asynchronous callback to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; @@ -89,6 +95,11 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -104,15 +115,16 @@ Starts an ability with the start options specified. This API uses an asynchronou | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0 @@ -142,6 +154,11 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; Starts an ability. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -162,13 +179,14 @@ Starts an ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; var options = { @@ -198,7 +216,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -214,15 +237,16 @@ Starts an ability. This API uses an asynchronous callback to return the result w | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -248,7 +272,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -265,15 +294,16 @@ Starts an ability with the start options specified. This API uses an asynchronou | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0, @@ -303,7 +333,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -Starts an ability. This API uses a promise to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -326,13 +361,14 @@ Starts an ability. This API uses a promise to return the result when the ability | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; var options = { @@ -361,9 +397,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -375,22 +416,23 @@ Starts an ability. This API uses an asynchronous callback to return the result w | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\<[AbilityResult](js-apis-inner-ability-abilityResult.md)\> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -418,9 +460,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +Starts an ability with the start options and account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -440,15 +487,16 @@ Starts an ability with the start options specified. This API uses an asynchronou | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -479,9 +527,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed. +Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -499,22 +552,23 @@ Starts an ability with the start options specified. This API uses a promise to r | Type| Description| | -------- | -------- | -| Promise<AbilityResult> | Promise used to return the result.| +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -543,7 +597,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -561,15 +615,16 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -594,7 +649,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -611,15 +666,16 @@ Starts a new Service Extension ability. This API uses a promise to return the re | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -644,9 +700,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -665,15 +721,16 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -699,9 +756,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +Starts a ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -719,15 +776,16 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -752,7 +810,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -770,20 +828,27 @@ Stops a Service Extension ability in the same application. This API uses an asyn | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { + this.context.startAbility(want, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbility(want, (error) => { - if (error.code) { + if (error.code != 0) { // Process service logic errors. console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + ' error.message: ' + JSON.stringify(error.message)); @@ -803,7 +868,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -820,18 +885,25 @@ Stops a Service Extension ability in the same application. This API uses a promi | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { + this.context.startAbility(want, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbility(want) .then((data) => { // Carry out normal service processing. @@ -853,9 +925,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -874,19 +946,26 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. @@ -908,9 +987,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -928,19 +1007,26 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) .then((data) => { // Carry out normal service processing. @@ -977,7 +1063,8 @@ Terminates this ability. This API uses an asynchronous callback to return the re | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1014,7 +1101,8 @@ Terminates this ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1034,7 +1122,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1050,7 +1138,8 @@ Terminates this ability. This API uses an asynchronous callback to return the ab | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1088,8 +1177,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). ## AbilityContext.terminateSelfWithResult terminateSelfWithResult(parameter: AbilityResult): Promise<void>; - -Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1110,7 +1198,8 @@ Terminates this ability. This API uses a promise to return the ability result in | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1173,15 +1262,16 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, @@ -1204,9 +1294,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. +Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability with the account ID specified. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1231,15 +1321,16 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1283,7 +1374,8 @@ Disconnects a connection. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1329,7 +1421,8 @@ Disconnects a connection. This API uses an asynchronous callback to return the r | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1361,6 +1454,11 @@ startAbilityByCall(want: Want): Promise<Caller>; Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -1388,7 +1486,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }; @@ -1419,7 +1517,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "", parameters: { "ohos.aafwk.param.callAbilityToForeground": true @@ -1450,7 +1548,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1469,15 +1572,16 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -1506,7 +1610,12 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1526,15 +1635,16 @@ Starts an ability with the account ID and start options specified. This API uses | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1566,7 +1676,12 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Starts an ability with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1585,15 +1700,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1618,65 +1734,6 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). } ``` -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; - -Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Yes| Callback used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); - }); - - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; - -Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Promise used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - - ``` - - ## AbilityContext.setMissionLabel setMissionLabel(label: string, callback:AsyncCallback<void>): void; @@ -1696,7 +1753,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call ```ts this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); + console.log('setMissionLabel result:' + JSON.stringify(result)); }); ``` @@ -1744,7 +1801,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | image.PixelMap | Yes| Icon of the ability to set.| +| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -1786,7 +1843,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | image.PixelMap | Yes| Icon of the ability to set.| +| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md index 7b041a216de98edff7ee662ff229c0e16b70470e..f1301ad877dcf5a0bd2fec5ad5be10452ee88716 100644 --- a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md @@ -1,4 +1,4 @@ -# @ohos.ability.dataUriUtils +# @ohos.ability.dataUriUtils (dataUriUtils) The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module. diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md index c6e16f3f0cbe2bd0dd18dd5ea7fd72c8a0f44fb7..dc0e8ae8928a9191f70b555e84a3f58b09e4b876 100644 --- a/en/application-dev/reference/apis/js-apis-ability-errorCode.md +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -1,9 +1,9 @@ -# @ohos.ability.errorCode +# @ohos.ability.errorCode (ErrorCode) -The **ErrorCode** module defines the error codes that can be used when the ability is started. - - **NOTE** +The **ErrorCode** module defines the error codes that may be returned when an ability is started. +> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -14,13 +14,13 @@ import errorCode from '@ohos.ability.errorCode' ## ErrorCode -Defines the error codes used when the ability is started. +Enumerates the error codes that may be returned when an ability is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ------------------------------ | ---- | ---------------------------------------- | -| NO_ERROR | 0 | No error occurs. | +| NO_ERROR | 0 | No error. | | INVALID_PARAMETER | -1 | Invalid parameter.| | ABILITY_NOT_FOUND | -2 | The ability is not found.| | PERMISSION_DENY | -3 | Permission denied. | diff --git a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md index 2f1b927b6191b6b87b649f1b4a85067deb705541..b527edfcf7911fec83b4e8d5a01a2761772e95f1 100644 --- a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -1,6 +1,6 @@ -# @ohos.ability.featureAbility +# @ohos.ability.featureAbility (FeatureAbility) -The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connect to a Service ability. +The **FeatureAbility** module provides APIs that enable user interaction. You can use the APIs to start or terminate an ability, obtain a **dataAbilityHelper** object, obtain the window corresponding to the current ability, and connect to or disconnect from a ServiceAbility. > **NOTE** > @@ -9,7 +9,7 @@ The **FeatureAbility** module provides a UI for interacting with users. You can ## Constraints -APIs of the **FeatureAbility** module can be called only by Page abilities. +The APIs of the **FeatureAbility** module can be called only by PageAbilities. ## Modules to Import @@ -23,6 +23,11 @@ startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\) Starts an ability. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -48,7 +53,7 @@ featureAbility.startAbility( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri: "" }, }, @@ -66,6 +71,11 @@ startAbility(parameter: StartAbilityParameter): Promise\ Starts an ability. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -74,6 +84,12 @@ Starts an ability. This API uses a promise to return the result. | --------- | ---------------------------------------- | ---- | -------------- | | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the result.| + **Example** ```ts @@ -90,7 +106,7 @@ featureAbility.startAbility( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri: "" }, } @@ -105,6 +121,12 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper Obtains a **dataAbilityHelper** object. +Observe the following when using this API: + - To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**). + - If an application running in the background needs to call this API to access a DataAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -117,7 +139,7 @@ Obtains a **dataAbilityHelper** object. | Type | Description | | ----------------- | ------------------------------- | -| DataAbilityHelper | A utility class used to help other abilities access the Data ability.| +| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access the Data ability.| **Example** @@ -132,7 +154,12 @@ var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts an ability. This API uses an asynchronous callback to return the execution result when the ability is destroyed. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -159,7 +186,7 @@ featureAbility.startAbilityForResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"" }, }, @@ -173,7 +200,12 @@ featureAbility.startAbilityForResult( startAbilityForResult(parameter: StartAbilityParameter): Promise\ -Starts an ability. This API uses a promise to return the execution result when the ability is destroyed. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -187,7 +219,7 @@ Starts an ability. This API uses a promise to return the execution result when t | Type | Description | | ---------------------------------------- | ------- | -| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promised returned with the execution result.| +| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| **Example** @@ -205,7 +237,7 @@ featureAbility.startAbilityForResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { @@ -229,7 +261,7 @@ featureAbility.startAbilityForResult( terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -237,7 +269,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | -------------- | -| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -257,7 +289,7 @@ featureAbility.terminateSelfWithResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { mykey0: 2222, @@ -281,7 +313,7 @@ featureAbility.terminateSelfWithResult( terminateSelfWithResult(parameter: AbilityResult): Promise\ -Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -289,7 +321,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | ------------- | -| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.| **Return value** @@ -314,7 +346,7 @@ featureAbility.terminateSelfWithResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { mykey0: 2222, @@ -345,7 +377,7 @@ Checks whether the main window of this ability has the focus. This API uses an a | Name | Type | Mandatory | Description | | -------- | ----------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
If the main window has the focus, **true** is returned. Otherwise, **false** is returned.| **Example** @@ -368,7 +400,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr | Type | Description | | ----------------- | ------------------------------------- | -| Promise\ | Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| Promise\ | Promise used to return the result. If the main window has the focus, **true** is returned. Otherwise, **false** is returned.| **Example** @@ -383,7 +415,7 @@ featureAbility.hasWindowFocus().then((data) => { getWant(callback: AsyncCallback\): void -Obtains the **Want** object sent from this ability. This API uses an asynchronous callback to return the result. +Obtains the Want corresponding to the ability to start. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -391,7 +423,7 @@ Obtains the **Want** object sent from this ability. This API uses an asynchronou | Name | Type | Mandatory | Description | | -------- | ----------------------------- | ---- | --------- | -| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the Want.| **Example** @@ -406,7 +438,7 @@ featureAbility.getWant((err, data) => { getWant(): Promise\ -Obtains the **Want** object sent from this ability. This API uses a promise to return the result. +Obtains the Want corresponding to the ability to start. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -414,7 +446,7 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r | Type | Description | | ----------------------- | ---------------- | -| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the result.| +| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the Want.| **Example** @@ -453,7 +485,7 @@ context.getBundleName((err, data) => { terminateSelf(callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. +Terminates this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -478,7 +510,7 @@ featureAbility.terminateSelf( terminateSelf(): Promise\ -Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result. +Terminates this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -501,7 +533,13 @@ featureAbility.terminateSelf().then((data) => { connectAbility(request: Want, options:ConnectOptions): number -Connects this ability to a specific Service ability. This API uses an asynchronous callback to return the result. +Connects this ability to a ServiceAbility. + +Observe the following when using this API: + - To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).. + - If an application running in the background needs to call this API to connect to a ServiceAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -509,14 +547,14 @@ Connects this ability to a specific Service ability. This API uses an asynchrono | Name | Type | Mandatory | Description | | ------- | -------------- | ---- | --------------------- | -| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.| -| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Callback used to return the result. | +| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. | **Return value** | Type | Description | | ------ | -------------------- | -| number | ID of the Service ability connected.| +| number | ID of the connected ServiceAbility. The ID starts from 0 and is incremented by 1 each time a connection is set up.| **Example** @@ -536,7 +574,7 @@ var connectId = featureAbility.connectAbility( { deviceId: "", bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -550,7 +588,7 @@ var connectId = featureAbility.connectAbility( disconnectAbility(connection: number, callback:AsyncCallback\): void -Disconnects this ability from a specific Service ability. This API uses an asynchronous callback to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -558,7 +596,7 @@ Disconnects this ability from a specific Service ability. This API uses an async | Name | Type | Mandatory | Description | | ---------- | -------------------- | ---- | ----------------------- | -| connection | number | Yes | ID of the Service ability to disconnect.| +| connection | number | Yes | ID of the ServiceAbility to disconnect.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -578,7 +616,7 @@ function onFailedCallback(code){ var connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -597,7 +635,7 @@ var result = featureAbility.disconnectAbility(connectId, disconnectAbility(connection: number): Promise\ -Disconnects this ability from a specific Service ability. This API uses a promise to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -605,7 +643,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ----------------------- | -| connection | number | Yes | ID of the Service ability to disconnect.| +| connection | number | Yes | ID of the ServiceAbility to disconnect.| **Return value** @@ -630,7 +668,7 @@ function onFailedCallback(code){ var connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -659,7 +697,7 @@ Obtains the window corresponding to this ability. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the window.| +| callback | AsyncCallback\<[window.Window](js-apis-window.md#window)> | Yes | Callback used to return the window.| **Example** @@ -681,7 +719,7 @@ Obtains the window corresponding to this ability. This API uses a promise to ret | Type | Description | | ----------------------- | ----------------------------- | -| Promise\ | Promise used to return the window.| +| Promise\<[window.Window](js-apis-window.md#window)> | Promise used to return the window.| **Example** @@ -693,7 +731,7 @@ featureAbility.getWindow().then((data) => { ## AbilityWindowConfiguration -The value is obtained through the **featureAbility.AbilityWindowConfiguration** API. +Defines the window configuration corresponding to this ability. The configuration is obtained through **featureAbility.AbilityWindowConfiguration**. **Example** @@ -705,18 +743,18 @@ featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED | Name | Value | Description | | ---------------------------------------- | ---- | ---------------------------------------- | -| WINDOW_MODE_UNDEFINED7+ | 0 | The Page ability is in an undefined window display mode.| -| WINDOW_MODE_FULLSCREEN7+ | 1 | The Page ability is in full screen mode. | -| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.| -| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.| -| WINDOW_MODE_FLOATING7+ | 102 | The Page ability is displayed in floating window mode.| +| WINDOW_MODE_UNDEFINED7+ | 0 | The PageAbility is in an undefined window display mode.| +| WINDOW_MODE_FULLSCREEN7+ | 1 | The PageAbility is in full screen mode. | +| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The PageAbility is displayed in the primary window when it is in split-screen mode.| +| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The PageAbility is displayed in the secondary window when it is in split-screen mode.| +| WINDOW_MODE_FLOATING7+ | 102 | The PageAbility is displayed in floating window mode.| ## AbilityStartSetting -The **AbilityStartSetting** attribute is an object defined as [key: string]: any. The key is a type of **AbilityStartSetting**, and the value is a type of **AbilityWindowConfiguration**. +Defines the window attribute corresponding to this ability. The **abilityStartSetting** attribute is an object defined in the format of [**key: string]: any**, where **key** is an enumerated value of **AbilityStartSetting** and **value** is an enumerated value of **AbilityWindowConfiguration**. -The value is obtained through the **featureAbility.AbilityStartSetting** API. +The value is obtained through **featureAbility.AbilityStartSetting**. **Example** @@ -734,7 +772,7 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY ## ErrorCode -Enumerates error codes. +Enumerates the error codes. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -743,12 +781,12 @@ Enumerates error codes. | NO_ERROR7+ | 0 | No error occurs.| | INVALID_PARAMETER7+ | -1 | Invalid parameter.| | ABILITY_NOT_FOUND7+ | -2 | The ability is not found.| -| PERMISSION_DENY7+ | -3 | The request is denied.| +| PERMISSION_DENY7+ | -3 | Permission denied.| ## DataAbilityOperationType -Enumerates operation types of the Data ability. +Enumerates the operation types of a DataAbility. The DataAbility can use an enumerated value to specify the operation type when operating data in batches. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -761,23 +799,25 @@ Enumerates operation types of the Data ability. ## flags +Enumerates the flags that specify how the Want will be handled. + **System capability**: SystemCapability.Ability.AbilityBase | Name | Value | Description | | ------------------------------------ | ---------- | ---------------------------------------- | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to the URI. | | FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | -| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Continues the ability on a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | -| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether the FormAbility is enabled. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ability is started in the foreground regardless of whether the host application is started.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | | FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| -| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on an existing mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md index 46355b926228755520d3d215d4275af03ecd88bc..7d00454ea5ce5b0051c2fff6856f9653be89b455 100644 --- a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -1,6 +1,6 @@ -# @ohos.ability.particleAbility +# @ohos.ability.particleAbility (ParticleAbility) -The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability. +The **particleAbility** module provides APIs for operating a ServiceAbility. You can use the APIs to start and terminate a ParticleAbility, obtain a **dataAbilityHelper** object, and connect to or disconnect from a ServiceAbility. > **NOTE** > @@ -21,7 +21,12 @@ import particleAbility from '@ohos.ability.particleAbility' startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts a Particle ability. This API uses an asynchronous callback to return the result. +Starts a ParticleAbility. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -48,7 +53,7 @@ particleAbility.startAbility( flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, deviceId: "", bundleName: "com.example.Data", - abilityName: "com.example.Data.MainAbility", + abilityName: "EntryAbility", uri: "" }, }, @@ -62,7 +67,12 @@ particleAbility.startAbility( startAbility(parameter: StartAbilityParameter): Promise\; -Starts a Particle ability. This API uses a promise to return the result. +Starts a ParticleAbility. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -94,7 +104,7 @@ particleAbility.startAbility( flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, deviceId: "", bundleName: "com.example.Data", - abilityName: "com.example. Data.MainAbility", + abilityName: "EntryAbility", uri: "" }, }, @@ -107,7 +117,7 @@ particleAbility.startAbility( terminateSelf(callback: AsyncCallback\): void -Terminates this Particle ability. This API uses an asynchronous callback to return the result. +Terminates this ParticleAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -133,7 +143,7 @@ particleAbility.terminateSelf( terminateSelf(): Promise\ -Terminates this Particle ability. This API uses a promise to return the result. +Terminates this ParticleAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -161,6 +171,12 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper Obtains a **dataAbilityHelper** object. +Observe the following when using this API: + - To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**). + - If an application running in the background needs to call this API to access a DataAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -173,7 +189,7 @@ Obtains a **dataAbilityHelper** object. | Type | Description | | ----------------- | -------------------------------------------- | -| DataAbilityHelper | A utility class used to help other abilities access a Data ability.| +| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access a DataAbility.| **Example** @@ -222,7 +238,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -283,7 +299,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -349,7 +365,7 @@ particleAbility.cancelBackgroundRunning(callback); cancelBackgroundRunning(): Promise<void>; -Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). +Requests to cancel a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -376,7 +392,13 @@ particleAbility.cancelBackgroundRunning().then(() => { connectAbility(request: Want, options:ConnectOptions): number -Connects this ability to a specific Service ability. This API uses a callback to return the result. +Connects this ability to a specific ServiceAbility. + +Observe the following when using this API: + - To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).. + - If an application running in the background needs to call this API to connect to a ServiceAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -384,23 +406,14 @@ Connects this ability to a specific Service ability. This API uses a callback to | Name | Type | Mandatory| Description | | ------- | -------------- | ---- | ---------------------------- | -| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.| -| options | ConnectOptions | Yes | Callback used to return the result. | - - -ConnectOptions +| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. | -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Mandatory | Description | -| ------------ | -------- | ---- | ------------------------- | -| onConnect | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect | function | Yes | Callback invoked when the connection fails. | -| onFailed | function | Yes | Callback invoked when **connectAbility** fails to be called.| **Example** ```ts +import particleAbility from '@ohos.ability.particleAbility' import rpc from '@ohos.rpc' function onConnectCallback(element, remote) { @@ -439,7 +452,7 @@ particleAbility.disconnectAbility(connId).then((data) => { disconnectAbility(connection: number, callback:AsyncCallback\): void; -Disconnects this ability from the Service ability. This API uses a callback to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -452,7 +465,8 @@ Disconnects this ability from the Service ability. This API uses a callback to r **Example** ```ts -import rpc from '@ohos.rpc' +import particleAbility from '@ohos.ability.particleAbility'; +import rpc from '@ohos.rpc'; function onConnectCallback(element, remote) { console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); @@ -489,7 +503,7 @@ var result = particleAbility.disconnectAbility(connId).then((data) => { disconnectAbility(connection: number): Promise\; -Disconnects this ability from the Service ability. This API uses a promise to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -502,7 +516,8 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Example** ```ts -import rpc from '@ohos.rpc' +import particleAbility from '@ohos.ability.particleAbility'; +import rpc from '@ohos.rpc'; function onConnectCallback(element, remote) { console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); @@ -538,7 +553,7 @@ particleAbility.disconnectAbility(connId).then((data) => { ## ErrorCode -Enumerates error codes. +Enumerates the error codes. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index 30fb8b3b970b22513f2dd520d43a11b76f66e47d..87b52688c5bec0a80bc44d9c8dcba63fe00283f2 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -1,4 +1,4 @@ -# @ohos.ability.wantConstant +# @ohos.ability.wantConstant (wantConstant) The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. @@ -14,7 +14,7 @@ import wantConstant from '@ohos.ability.wantConstant'; ## wantConstant.Action -Enumerates the action constants of the **Want** object. +Enumerates the action constants of the **Want** object. **action** specifies the operation to execute. **System capability**: SystemCapability.Ability.AbilityBase @@ -57,7 +57,7 @@ Enumerates the action constants of the **Want** object. ## wantConstant.Entity -Enumerates the entity constants of the **Want** object. +Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability. **System capability**: SystemCapability.Ability.AbilityBase @@ -72,25 +72,25 @@ Enumerates the entity constants of the **Want** object. ## wantConstant.Flags -Describes flags. +Enumerates the flags that specify how the Want will be handled. **System capability**: SystemCapability.Ability.AbilityBase | Name | Value | Description | | ------------------------------------ | ---------- | ------------------------------------------------------------ | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to the URI. | | FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | | FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | | FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ServiceAbility is started regardless of whether the host application has been started. | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | | FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| -| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the history mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index ed59083949a8d151e7e007e9b2475d20e91446e6..88ffbc6255e15705d88259e65392fa9e4f6a3193 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -1,4 +1,4 @@ -# @ohos.abilityAccessCtrl (Ability Access Control) +# @ohos.abilityAccessCtrl (Application Access Control) The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation. @@ -40,7 +40,7 @@ Implements ability access control. checkAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> -Checks whether an application has the specified permission. This API uses a promise to return the result. +Checks whether a permission is granted to an application. This API uses a promise to return the result. **System capability**: SystemCapability.Security.AccessToken @@ -48,8 +48,8 @@ Checks whether an application has the specified permission. This API uses a prom | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Permission to check.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to check. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -71,7 +71,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { atManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); @@ -87,7 +87,7 @@ try { verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus -Verifies whether an application has the specified permission. This API returns the result synchronously. +Verifies whether a permission is granted to an application. This API returns the result synchronously. **System capability**: SystemCapability.Security.AccessToken @@ -95,8 +95,8 @@ Verifies whether an application has the specified permission. This API returns t | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. | -| permissionName | Permissions | Yes | Name of the permission to verify.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -116,7 +116,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ```js let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let data = atManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); console.log(`data->${JSON.stringify(data)}`); ``` @@ -137,8 +137,8 @@ Grants a user_grant permission to an application. This API uses a promise to ret | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to grant.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** @@ -165,7 +165,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -194,10 +194,10 @@ Grants a user_grant permission to an application. This API uses an asynchronous | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| -| permissionName | Permissions | Yes | Name of the permission to grant.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted successfully, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -208,7 +208,8 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | -| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | +| 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100007 | Service is abnormal. | **Example** @@ -216,7 +217,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -247,8 +248,8 @@ Revokes a user_grant permission from an application. This API uses a promise to | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to revoke.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** @@ -275,7 +276,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -304,10 +305,10 @@ Revokes a user_grant permission from an application. This API uses an asynchrono | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to revoke.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is revoked successfully, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is revoked successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -318,7 +319,8 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | -| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | +| 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100007 | Service is abnormal. | **Example** @@ -326,7 +328,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -357,8 +359,8 @@ Obtains the flags of the specified permission of an application. This API uses a | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to query.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Target permission. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -375,7 +377,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | -| 12100006 | The operation is not allowd. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. | | 12100007 | Service is abnormal. | **Example** @@ -384,7 +386,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); @@ -525,7 +527,7 @@ try { verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> -Verifies whether an application has the specified permission. This API uses a promise to return the result. +Verifies whether a permission is granted to an application. This API uses a promise to return the result. > **NOTE**
You are advised to use [checkAccessToken](#checkaccesstoken9). @@ -535,8 +537,8 @@ Verifies whether an application has the specified permission. This API uses a pr | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to verify. Only valid permission names are supported.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -550,18 +552,107 @@ Verifies whether an application has the specified permission. This API uses a pr import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); ``` +### requestPermissionsFromUser9+ + +requestPermissionsFromUser(context: Context, permissions: Array<Permissions>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; + +Requests user authorization in a dialog box. This API uses an asynchronous callback to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Ability context of the application that requests the permission.| +| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +| ID| Error Message| +| -------- | -------- | +| 12100001 | Parameter invalid. | + +**Example** + + ```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"], (err, data)=>{ + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} + ``` + +### requestPermissionsFromUser9+ + +requestPermissionsFromUser(context: Context, permissions: Array<Permissions>) : Promise<PermissionRequestResult>; + +Requests user authorization in a dialog box. This API uses a promise to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Ability context of the application that requests the permission.| +| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +| ID| Error Message| +| -------- | -------- | +| 12100001 | Parameter invalid. | + +**Example** + + ```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }).catch((err) => { + console.info("data:" + JSON.stringify(err)); + }) +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} + ``` + ### verifyAccessToken(deprecated) verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> -Verifies whether an application has the specified permission. This API uses a promise to return the result. +Verifies whether a permission is granted to an application. This API uses a promise to return the result. > NOTE
This API is deprecated since API version 9. You are advised to use [checkAccessToken](#checkaccesstoken9). @@ -571,8 +662,8 @@ Verifies whether an application has the specified permission. This API uses a pr | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | string | Yes | Name of the permission to verify.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | string | Yes | Permission to check.| **Return value** @@ -586,7 +677,7 @@ Verifies whether an application has the specified permission. This API uses a pr import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); @@ -629,4 +720,4 @@ Defines the detailed permission grant state change information. | -------------- | ------------------------- | ---- | ---- | ------------------ | | change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | No | Operation that triggers the permission grant state change. | | tokenID | number | Yes | No | Token ID of the application whose permission grant state changes are subscribed.| -| permissionName | Permissions | Yes | No | Name of the permission whose grant state is changed.| +| permissionName | Permissions | Yes | No | permission whose grant state is changed. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| diff --git a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md deleted file mode 100644 index 9fee7500eae2ec8435f0c3bdc2b48c986b14686a..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ /dev/null @@ -1,379 +0,0 @@ -# AccessibilityExtensionContext - -The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities. - -You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Usage - -Before using the **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**. - -```js -import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' -class MainAbility extends AccessibilityExtensionAbility { - onConnect(): void { - console.log("AxExtensionAbility onConnect"); - let axContext = this.context; - } -} -``` - -## FocusDirection - -Enumerates the focus directions. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| -------- | ------- | -| up | Search for the next focusable item above the current item in focus.| -| down | Search for the next focusable item below the current item in focus.| -| left | Search for the next focusable item on the left of the current item in focus.| -| right | Search for the next focusable item on the right of the current item in focus.| -| forward | Search for the next focusable item before the current item in focus.| -| backward | Search for the next focusable item after the current item in focus.| - -## FocusType - -Enumerates the focus types. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| ------------- | ----------- | -| accessibility | Accessibility focus.| -| normal | Normal focus. | - -## Rect - -Defines a rectangle. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | --------- | -| left | number | Yes | No | Left boundary of the rectangle.| -| top | number | Yes | No | Top boundary of the rectangle.| -| width | number | Yes | No | Width of the rectangle. | -| height | number | Yes | No | Height of the rectangle. | - -## WindowType - -Enumerates the window types. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| ----------- | --------- | -| application | Application window.| -| system | System window.| - -## AccessibilityExtensionContext.setTargetBundleName - -setTargetBundleName(targetNames: Array\): Promise\; - -Sets the concerned target bundle. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ------------------- | ---- | -------- | -| targetNames | Array<string> | Yes | Name of the target bundle.| - -**Return value** - -| Type | Description | -| ---------------------- | --------------------- | -| Promise<boolean> | Promise used to return the result.| - -**Example** - -```ts -this.context.setTargetBundleName(['com.ohos.mms']); -``` - -## AccessibilityExtensionContext.getFocusElement - -getFocusElement(isAccessibilityFocus?: boolean): Promise\; - -Obtains the focus element. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | -| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| - -**Return value** - -| Type | Description | -| ----------------------------------- | ---------------------- | -| Promise<AccessibilityElement> | Promise used to return the current focus element.| - -**Example** - -```ts -this.context.getFocusElement().then(focusElement => { - console.log("AxExtensionAbility getFocusElement success"); -}) -``` - -## AccessibilityExtensionContext.getWindowRootElement - -getWindowRootElement(windowId?: number): Promise\; - -Obtains the root element of a window. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | --------------------------- | -| windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| - -**Return value** - -| Type | Description | -| ----------------------------------- | ----------------------- | -| Promise<AccessibilityElement> | Promise used to return the root element.| - -**Example** - -```ts -this.context.getWindowRootElement().then(rootElement => { - console.log("AxExtensionAbility getWindowRootElement success"); -}) -``` - -## AccessibilityExtensionContext.getWindows - -getWindows(displayId?: number): Promise>; - -Obtains the list of windows visible to users. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ------------------------- | -| displayId | number | No | Screen from which the window information is obtained. If this parameter is not specified, it indicates the default home screen.| - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<AccessibilityElement>> | Promise used to return the window list. | - -**Example** - -```ts -this.context.getWindows().then(windows => { - console.log("AxExtensionAbility getWindows success"); -}) -``` - -## AccessibilityExtensionContext.injectGesture - -injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void - -Injects a gesture. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```ts -let gesturePath = new GesturePath(100); -for (let i = 0; i < 10; i++) { - let gesturePoint = new GesturePosition(100, i * 200); - gesturePath.positions.push(gesturePoint); -} -this.context.gestureInject(gesturePath, (result) => { - console.info('gestureInject result: ' + result); -}) -``` -## AccessibilityElement.attributeNames - -attributeNames\(): Promise\>; - -Obtains all attribute names of this element. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<T>> | Promise used to return all attribute names of the element.| - -**Example** - -```ts -let accessibilityElement; -try { - accessibilityElement.attributeNames().then((values) => { - console.log("get attribute names success"); - }).catch((err) => { - console.log("get attribute names err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.attributeValue - -attributeValue\(attributeName: T): Promise\; - -Obtains the attribute value based on an attribute name. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| attributeName | T | Yes | Attribute name. | - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<ElementAttributeValues[T]>> | Promise used to return the attribute value.| - -**Example** - -```ts -let accessibilityElement; -try { - let attributeName = 'name'; - accessibilityElement.attributeValue(attributeName).then((value) => { - console.log("get attribute value by name success"); - }).catch((err) => { - console.log("get attribute value by name err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.actionNames - -actionNames(): Promise\>; - -Obtains the names of all actions supported by this element. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<string>> | Promise used to return the names of all actions supported by the element.| - -**Example** - -```ts -let accessibilityElement; -try { - accessibilityElement.actionNames().then((values) => { - console.log("get action names success"); - }).catch((err) => { - console.log("get action names err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.performAction - -performAction(actionName: string, parameters?: object): Promise\; - -Performs an action based on the specified action name. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. | -| parameters | object | No | Parameter required for performing the target action. | - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<boolean>> | Promise used to return the result.| - -**Example** - -```ts -let accessibilityElement; -try { - - accessibilityElement.performAction('action').then((result) => { - console.info('perform action result: ' + result); - }).catch((err) => { - console.log("perform action err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.findElement - -findElement(type: 'content', condition: string): Promise\>; - -Queries the information about this element based on the specified information type and condition. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'content'**. | -| condition | string | Yes | Search criteria. | - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<T>> | Promise used to return the result.| - -**Example** - -```ts -let accessibilityElement; -try { - let condition = 'keyword'; - accessibilityElement.findElement('content', condition).then((values) => { - console.log("find element success"); - }).catch((err) => { - console.log("find element err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-ability.md b/en/application-dev/reference/apis/js-apis-app-ability-ability.md index 59e1e229f2e8396ae11584dee80a439ea74fdf6b..cfa11ddc30560c1ffa6a03eb8efccb8ea60b6d5b 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-ability.md @@ -1,18 +1,12 @@ -# @ohos.app.ability.Ability +# @ohos.app.ability.Ability (Ability Base Class) -The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. +This is the base class of [UIAbility](js-apis-app-ability-uiAbility.md) and [ExtensionAbility](js-apis-app-ability-extensionAbility.md). It provides the callbacks for system configuration updates and memory level updates. You cannot inherit from this base class. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -## Modules to Import - -```ts -import Ability from '@ohos.app.ability.Ability'; -``` - ## Ability.onConfigurationUpdate onConfigurationUpdate(newConfig: Configuration): void; @@ -23,40 +17,45 @@ Called when the configuration of the environment where the ability is running is **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| **Example** - ```ts - class myAbility extends Ability { - onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); - } - } +// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example. +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } +} ``` ## Ability.onMemoryLevel onMemoryLevel(level: AbilityConstant.MemoryLevel): void; -Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. +Called when the system adjusts the memory level. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| **Example** - + ```ts - class myAbility extends Ability { +// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example. +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); } - } +} ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index 5d6c93e6e2b45b33ca9cb7ec9976435c17fd2a56..766636a7c7d4cda38cb2b71395fd3f2575e2f784 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -1,8 +1,6 @@ -# @ohos.app.ability.AbilityConstant +# @ohos.app.ability.AbilityConstant (AbilityConstant) -The **AbilityConstant** module provides ability launch parameters. - -The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results. +The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes. > **NOTE** > @@ -17,31 +15,48 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ## Attributes +## AbilityConstant.LaunchParam + +Defines the parameters for starting an ability. + **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| +| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason, which is an enumerated type.| +| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit, which is an enumerated type.| ## AbilityConstant.LaunchReason -Enumerates the ability launch reasons. +Enumerates the initial ability launch reasons. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | | UNKNOWN | 0 | Unknown reason.| -| START_ABILITY | 1 | Ability startup.| -| CALL | 2 | Call.| -| CONTINUATION | 3 | Ability continuation.| -| APP_RECOVERY | 4 | Application recovery.| +| START_ABILITY | 1 | The ability is started by calling [startAbility](js-apis-ability-context.md#abilitycontextstartability).| +| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-ability-context.md#abilitycontextstartabilitybycall).| +| CONTINUATION | 3 | The ability is started by means of cross-device migration.| +| APP_RECOVERY | 4 | The ability is automatically started when the application is restored from a fault.| + +**Example** +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onCreate(want, launchParam) { + if (launchParam.launchReason === AbilityConstant.LaunchReason.START_ABILITY) { + console.log("The ability has been started by the way of startAbility."); + } + } +} +``` ## AbilityConstant.LastExitReason -Enumerates reasons for the last exit. +Enumerates the reasons for the last exit. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -49,12 +64,25 @@ Enumerates reasons for the last exit. | ----------------------------- | ---- | ------------------------------------------------------------ | | UNKNOWN | 0 | Unknown reason.| | ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| -| NORMAL | 2 | Normal status.| +| NORMAL | 2 | The ability exits normally.| +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onCreate(want, launchParam) { + if (launchParam.lastExitReason === AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) { + console.log("The ability has exit last because the ability was not responding."); + } + } +} +``` ## AbilityConstant.OnContinueResult -Enumerates ability continuation results. +Enumerates the ability continuation results. You can use it together with [onContinue(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncontinue) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -64,9 +92,21 @@ Enumerates ability continuation results. | REJECT | 1 | Continuation denied.| | MISMATCH | 2 | Mismatch.| +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onContinue(wantParam) { + return AbilityConstant.OnConinueResult.AGREE; + } +} +``` + ## AbilityConstant.WindowMode -Enumerates the window modes in which an ability can be displayed at startup. +Enumerates the window modes in which an ability can be displayed at startup. It can be used in **startAbility()** to specify the window mode when the ability is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -78,36 +118,81 @@ Enumerates the window modes in which an ability can be displayed at startup. | WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | | WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| +**Example** + +```ts +let want = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" +}; +let option = { + windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN +}; + +// Ensure that the context is obtained. +this.context.startAbility(want, option).then(()={ + console.log("Succeed to start ability."); +}).catch((error)=>{ + console.log("Failed to start ability with error: " + JSON.stringify(error)); +}); +``` + ## AbilityConstant.MemoryLevel -Enumerates the memory levels. +Enumerates the memory levels. You can use it in [onMemoryLevel(level)](js-apis-app-ability-ability.md#abilityonmemorylevel) of [Ability](js-apis-app-ability-ability.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value| Description | -| --- | --- | --- | -| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. | -| MEMORY_LEVEL_LOW | 1 | Low memory usage. | +| --- | --- | --- | +| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage.| +| MEMORY_LEVEL_LOW | 1 | Low memory usage. | | MEMORY_LEVEL_CRITICAL | 2 | High memory usage. | +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onMemoryLevel(level) { + if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) { + console.log("The memory of device is critical, please release some memory."); + } + } +} +``` + ## AbilityConstant.OnSaveResult -Enumerates the result types for the operation of saving application data. +Enumerates the result types for the operation of saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | -| ALL_AGREE | 0 | Agreed to save the status.| +| ALL_AGREE | 0 | Always agreed to save the status.| | CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.| | CONTINUATION_MISMATCH | 2 | Continuation mismatch.| | RECOVERY_AGREE | 3 | Agreed to restore the saved status.| | RECOVERY_REJECT | 4 | Rejected to restore the saved state.| -| ALL_REJECT | 5 | Rejected to save the status.| +| ALL_REJECT | 5 | Always rejected to save the status.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onSaveState(reason, wantParam) { + return AbilityConstant.OnSaveResult.ALL_AGREE; + } +} +``` ## AbilityConstant.StateType -Enumerates the scenarios for saving application data. +Enumerates the scenarios for saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -115,3 +200,18 @@ Enumerates the scenarios for saving application data. | ----------------------------- | ---- | ------------------------------------------------------------ | | CONTINUATION | 0 | Saving the status in continuation.| | APP_RECOVERY | 1 | Saving the status in application recovery.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onSaveState(reason, wantParam) { + if (reason === AbilityConstant.StateType.CONTINUATION) { + console.log("Save the ability data when the ability continuation."); + } + return AbilityConstant.OnSaveResult.ALL_AGREE; + } +} +``` 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 78fb6181c03380c6d69eb31318d1d459dec307fe..5cfa437047868a9183ae4bb4f41ff42eec47f5d7 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,26 +1,27 @@ -# @ohos.app.ability.abilityDelegatorRegistry +# @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry) -The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. +**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. > **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 can be used only in the test framework. ## Modules to Import ```ts -import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; ``` ## AbilityLifecycleState -Enumerates the ability lifecycle states. +Enumerates the ability lifecycle states. It can be used in [getAbilityState(ability)](js-apis-inner-application-abilityDelegator.md#getabilitystate9) of [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) to return different ability lifecycle states. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ------------- | ---- | --------------------------- | -| UNINITIALIZED | 0 | The ability is in an invalid state. | +| UNINITIALIZED | 0 | The ability is in an invalid state. | | CREATE | 1 | The ability is created.| | FOREGROUND | 2 | The ability is running in the foreground. | | BACKGROUND | 3 | The ability is running in the background. | @@ -30,7 +31,7 @@ Enumerates the ability lifecycle states. getAbilityDelegator(): AbilityDelegator -Obtains the **AbilityDelegator** object of the application. +Obtains an [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) object. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -38,20 +39,33 @@ Obtains the **AbilityDelegator** object of the application. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| +| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule the functionalities of the test framework.| **Example** ```ts -var abilityDelegator; -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); + +let want = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" +}; +abilityDelegator.startAbility(want, (err) => { + if (err.code !== 0) { + console.log("Success start ability."); + } else { + console.log("Failed start ability, error: " + JSON.stringify(err)); + } +}) ``` ## AbilityDelegatorRegistry.getArguments getArguments(): AbilityDelegatorArgs -Obtains the **AbilityDelegatorArgs** object of the application. +Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) object. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -64,8 +78,11 @@ Obtains the **AbilityDelegatorArgs** object of the application. **Example** ```ts -var args = AbilityDelegatorRegistry.getArguments(); +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +let args = AbilityDelegatorRegistry.getArguments(); console.info("getArguments bundleName:" + args.bundleName); +console.info("getArguments parameters:" + JSON.stringify(args.parameters)); console.info("getArguments testCaseNames:" + args.testCaseNames); console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md index f3e6e08396d0b819efd6acda39218af497e83ef9..84be19350707fee37328ff8040b2986588afd2f8 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.abilityLifecycleCallback +# @ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback) -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. +The **AbilityLifecycleCallback** module defines the callbacks to receive lifecycle changes of [ApplicationContext](js-apis-inner-application-applicationContext.md). The callbacks include [onAbilityCreate](#abilitylifecyclecallbackonabilitycreate), [onWindowStageCreate](#abilitylifecyclecallbackonwindowstagecreate), [onWindowStageActive](#abilitylifecyclecallbackonwindowstageactive), [onWindowStageInactive](#abilitylifecyclecallbackonwindowstageinactive), [onWindowStageDestroy](#abilitylifecyclecallbackonwindowstagedestroy), [onAbilityDestroy](#abilitylifecyclecallbackonabilitydestroy), [onAbilityForeground](#abilitylifecyclecallbackonabilityforeground), [onAbilityBackground](#abilitylifecyclecallbackonabilitybackground), and [onAbilityContinue](#abilitylifecyclecallbackonabilitycontinue). > **NOTE** > @@ -25,10 +25,18 @@ Called when an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageCreate @@ -40,11 +48,19 @@ Called when the window stage of an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageActive @@ -56,11 +72,19 @@ Called when the window stage of an ability gains focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageInactive @@ -72,11 +96,19 @@ Called when the window stage of an ability loses focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageDestroy @@ -88,11 +120,19 @@ Called when the window stage of an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityDestroy @@ -104,10 +144,18 @@ Called when an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityForeground @@ -119,10 +167,18 @@ Called when an ability is switched from the background to the foreground. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityBackground @@ -134,10 +190,18 @@ Called when an ability is switched from the foreground to the background. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityContinue @@ -149,63 +213,91 @@ Called when an ability is continued on another device. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue."); + } +}; +``` + +## Usage of AbilityLifecycleCallback **Example** - - - ```ts - import UIAbility from "@ohos.app.ability.UIAbility"; - - export default class MyAbility extends UIAbility { - onCreate() { - console.log("MyAbility onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); - }, - onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageInactive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageDestroy(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); - }, - onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); - }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); - }, - onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); - } - } - // 1. Obtain applicationContext through the context attribute. - let applicationContext = this.context.getApplicationContext(); - // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - let lifecycleid = applicationContext.on("abilityLifecycle", AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); - }, - onDestroy() { - let applicationContext = this.context.getApplicationContext(); - applicationContext.off("abilityLifecycle", lifecycleid, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - } - } - ``` + +MyFirstAbility.ts +```ts +import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; +import AbilityStage from "@ohos.app.ability.AbilityStage"; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Declare the ability lifecycle callbacks. A listener can be registered in applicationContext only after all the callbacks are configured. +let abilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate."); + }, + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate."); + }, + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive."); + }, + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive."); + }, + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy."); + }, + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy."); + }, + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground."); + }, + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground."); + }, + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue."); + } +}; + +export default class MyFirstAbility extends UIAbility { + onCreate() { + console.log("MyAbilityStage onCreate"); + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Register the listener for the ability lifecycle changes through the applicationContext object. + try { + globalThis.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + } catch (paramError) { + console.log("error: " + paramError.code + " ," + paramError.message); + } + } +} +``` + +MySecondAbility.ts +```ts +import UIAbility from "ohos.app.ability.UIAbility"; + +export default class MySecondAbility extends UIAbility { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + // 3. Deregister the listener for the environment changes through the applicationContext object. + applicationContext.off("abilityLifecycle", globalThis.lifecycleId, (error) => { + if (error.code != 0) { + console.log("unregisterAbilityLifecycleCallback failed, error: " + JSON.stringify(error)); + } else { + console.log("unregisterAbilityLifecycleCallback success."); + } + }); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md index 0a191c0038f3a5811018346ffe779dc558b3ad20..f7f9c49a4cdf1c9e8c92ad8b7c8bd977df525477 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.abilityManager +# @ohos.app.ability.abilityManager (AbilityManager) -The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. +The **AbilityManager** module provides APIs for obtaining, adding, and updating ability running information and state information. > **NOTE** > @@ -10,24 +10,24 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying ## Modules to Import ```ts -import AbilityManager from '@ohos.app.ability.abilityManager' +import abilityManager from '@ohos.app.ability.abilityManager'; ``` ## AbilityState -Enumerates the ability states. +Enumerates the ability states. This enum can be used together with [AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md) to return the ability state. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This enum is an internal definition of a system API and cannot be called by third-party applications. | Name| Value| Description| | -------- | -------- | -------- | | INITIAL | 0 | The ability is in the initial state.| | FOREGROUND | 9 | The ability is in the foreground state. | | BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding state. | +| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | +| BACKGROUNDING | 12 | The ability is in the state of being switched to the background. | ## updateConfiguration @@ -43,25 +43,42 @@ Updates the configuration. This API uses an asynchronous callback to return the | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.| +| callback | AsyncCallback\ | Yes | Callback used to return the API call result. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var config = { - language: 'chinese' -} +const config = { + language: 'Zh-Hans', // Simplified Chinese. + colorMode: COLOR_MODE_LIGHT, // Light theme. + direction: DIRECTION_VERTICAL, // Vertical direction. + screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + displayId: 1, // The application is displayed on the display with ID 1. + hasPointerDevice: true, // A pointer device is connected. +}; try { - abilitymanager.updateConfiguration(config, () => { - console.log('------------ updateConfiguration -----------'); - }) + abilityManager.updateConfiguration(config, (err) => { + if (err.code !== 0) { + console.log("updateConfiguration fail, err: " + JSON.stringify(err)); + } else { + console.log("updateConfiguration success."); + } + }) } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -79,32 +96,45 @@ Updates the configuration. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.| **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var config = { - language: 'chinese' -} +const config = { + language: 'Zh-Hans', // Simplified Chinese. + colorMode: COLOR_MODE_LIGHT, // Light theme. + direction: DIRECTION_VERTICAL, // Vertical direction. + screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + displayId: 1, // The application is displayed on the display with ID 1. + hasPointerDevice: true, // A pointer device is connected. +}; try { - abilitymanager.updateConfiguration(config).then(() => { - console.log('updateConfiguration success'); - }).catch((err) => { - console.log('updateConfiguration fail'); - }) + abilityManager.updateConfiguration(config).then(() => { + console.log('updateConfiguration success.'); + }).catch((err) => { + console.log('updateConfiguration fail, err: ' + JSON.stringify(err)); + }) } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -122,20 +152,32 @@ Obtains the ability running information. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; try { - abilitymanager.getAbilityRunningInfos((err,data) => { - console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); - }); + abilityManager.getAbilityRunningInfos((err, data) => { + if (err.code !== 0) { + console.log("getAbilityRunningInfos fail, error: " + JSON.stringify(err)); + } else { + console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data)); + } + }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -153,22 +195,30 @@ Obtains the ability running information. This API uses a promise to return the r | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; - +import abilityManager from '@ohos.app.ability.abilityManager'; + try { - abilitymanager.getAbilityRunningInfos().then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) - }).catch((err) => { - console.log("getAbilityRunningInfos err: " + err) - }); + abilityManager.getAbilityRunningInfos().then((data) => { + console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data)) + }).catch((err) => { + console.log("getAbilityRunningInfos fail, err: " + JSON.stringify(err)); + }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -176,7 +226,7 @@ try { getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void -Obtains the extension running information. This API uses an asynchronous callback to return the result. +Obtains the ExtensionAbility running information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -186,23 +236,35 @@ Obtains the extension running information. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | Yes| Maximum number of messages that can be obtained.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 231-1.| +| callback | AsyncCallback\> | Yes | Callback used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var upperLimit = 0; +let upperLimit = 10; try { - abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); - }); + abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => { + if (err.code !== 0) { + console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err)); + } else { + console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data)); + } + }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -210,7 +272,7 @@ try { getExtensionRunningInfos(upperLimit: number): Promise\> -Obtains the extension running information. This API uses a promise to return the result. +Obtains the ExtensionAbility running information. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -220,30 +282,38 @@ Obtains the extension running information. This API uses a promise to return the | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | Yes| Maximum number of messages that can be obtained.| +| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 231-1.| **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var upperLimit = 0; +let upperLimit = 10; try { - abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); - }).catch((err) => { - console.log("getAbilityRunningInfos err: " + err); - }) + abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { + console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err)); + }) } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -259,21 +329,28 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; - -try { - abilitymanager.getTopAbility((err,data) => { - console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); - }); -} catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); -} +import abilityManager from '@ohos.app.ability.abilityManager'; + +abilityManager.getTopAbility((err, data) => { + if (err.code !== 0) { + console.log("getTopAbility fail, err: " + JSON.stringify(err)); + } else { + console.log("getTopAbility success, data: " + JSON.stringify(data)); + } +}); ``` ## getTopAbility @@ -288,21 +365,24 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Type | Description | | ---------------------------------------- | ------- | -| Promise\| Promise used to return the result.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -try { - abilitymanager.getTopAbility().then((data) => { - console.log("getTopAbility data: " + JSON.stringify(data)); - }).catch((err) => { - console.log("getTopAbility err: " + err); - }) -} catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); -} +abilityManager.getTopAbility().then((data) => { + console.log("getTopAbility success, data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getTopAbility fail, err: " + JSON.stringify(err)); +}) ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md index b1226842409c7d03c82d25d33319042a716b9d86..50feb82791f8992894641a296d6cb831fdc86680 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.AbilityStage +# @ohos.app.ability.AbilityStage (AbilityStage) **AbilityStage** is a runtime class for HAP files. @@ -25,13 +25,15 @@ Called when the application is created. **Example** - ```ts - class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage.onCreate is called") - } - } - ``` +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage.onCreate is called"); + } +} +``` ## AbilityStage.onAcceptWant @@ -44,9 +46,9 @@ Called when a specified ability is started. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| **Return value** @@ -56,14 +58,16 @@ Called when a specified ability is started. **Example** - ```ts - class MyAbilityStage extends AbilityStage { - onAcceptWant(want) { - console.log("MyAbilityStage.onAcceptWant called"); - return "com.example.test"; - } - } - ``` +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onAcceptWant(want) { + console.log("MyAbilityStage.onAcceptWant called"); + return "com.example.test"; + } +} +``` ## AbilityStage.onConfigurationUpdate @@ -82,13 +86,15 @@ Called when the global configuration is updated. **Example** - ```ts - class MyAbilityStage extends AbilityStage { - onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, language:' + config.language); - } - } - ``` +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, language:' + config.language); + } +} +``` ## AbilityStage.onMemoryLevel @@ -106,22 +112,24 @@ Called when the system has decided to adjust the memory level. For example, this **Example** - ```ts - class MyAbilityStage extends AbilityStage { +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); } - } - ``` +} +``` ## AbilityStage.context context: AbilityStageContext; -Describes the configuration information about the context. +Defines the context of **AbilityStage**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Description | | ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Called when initialization is performed during ability startup.| +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | The context is obtained in the callback invoked when initialization is performed during ability startup.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md index b6fae35d6d03575442b1223c63cbcd4150773bb9..840a395eac9e17558918dd7466aa9e0b178b1c4d 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.appManager +# @ohos.app.ability.appManager (appManager) The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. @@ -12,7 +12,7 @@ The **appManager** module implements application management. You can use the API import appManager from '@ohos.app.ability.appManager'; ``` -## appManager.isRunningInStabilityTest9+ +## appManager.isRunningInStabilityTest static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void @@ -22,21 +22,34 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest((err, flag) => { - console.log('startAbility result:' + JSON.stringify(err)); - }) - ``` +```ts +import appManager from '@ohos.app.ability.appManager'; -## appManager.isRunningInStabilityTest9+ +appManager.isRunningInStabilityTest((err, flag) => { + if (err.code !== 0) { + console.log("isRunningInStabilityTest faile, err: " + JSON.stringify(err)); + } else { + console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag)); + } +}) +``` + + +## appManager.isRunningInStabilityTest static isRunningInStabilityTest(): Promise<boolean> @@ -48,18 +61,27 @@ Checks whether this application is undergoing a stability test. This API uses a | Type| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest().then((flag) => { - console.log('success:' + JSON.stringify(flag)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRunningInStabilityTest().then((flag) => { + console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` ## appManager.isRamConstrainedDevice @@ -74,17 +96,27 @@ Checks whether this application is running on a RAM constrained device. This API | Type| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.isRamConstrainedDevice().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRamConstrainedDevice().then((data) => { + console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` ## appManager.isRamConstrainedDevice @@ -96,18 +128,31 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + | Type| Description| + | -------- | -------- | + | AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.isRamConstrainedDevice((err, data) => { - console.log('startAbility result failed:' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRamConstrainedDevice((err, data) => { + if (err.code !== 0) { + console.log("isRamConstrainedDevice faile, err: " + JSON.stringify(err)); + } else { + console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data)); + } +}) +``` ## appManager.getAppMemorySize @@ -121,17 +166,27 @@ Obtains the memory size of this application. This API uses a promise to return t | Type| Description| | -------- | -------- | - | Promise<number> | Size of the application memory.| + | Promise<number> | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getAppMemorySize().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getAppMemorySize().then((data) => { + console.log("The size of app memory is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` ## appManager.getAppMemorySize @@ -143,20 +198,33 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | Yes| Size of the application memory.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<number> |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getAppMemorySize((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` -## appManager.getProcessRunningInformation9+ +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getAppMemorySize((err, data) => { + if (err.code !== 0) { + console.log("getAppMemorySize faile, err: " + JSON.stringify(err)); + } else { + console.log("The size of app memory is:" + JSON.stringify(data)); + } +}) +``` + +## appManager.getProcessRunningInformation getProcessRunningInformation(): Promise\>; @@ -172,17 +240,27 @@ Obtains information about the running processes. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the process information.| +| Promise\> | Promise used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getProcessRunningInformation().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getProcessRunningInformation().then((data) => { + console.log("The process running information is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` ## appManager.getProcessRunningInformation9+ @@ -198,18 +276,31 @@ Obtains information about the running processes. This API uses an asynchronous c **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the process information.| +| Type| Description| +| -------- | -------- | +|AsyncCallback\> | Callback used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getProcessRunningInformation((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getProcessRunningInformation((err, data) => { + if (err.code !== 0) { + console.log("getProcessRunningInformation faile, err: " + JSON.stringify(err)); + } else { + console.log("The process running information is:" + JSON.stringify(data)); + } +}) +``` ## appManager.on @@ -227,37 +318,52 @@ Registers an observer to listen for the state changes of all applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| + +**Return value** + +| Type| Description| +| --- | --- | +| number | Digital code of the observer, which will be used in **off()** to deregister the observer.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var applicationStateObserver = { + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); }, onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); }, onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); }, onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); }, onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } - } - try { - const observerCode = app.on(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); - } - - ``` +} +try { + const observerId = appManager.on('applicationState', applicationStateObserver); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} +``` ## appManager.on @@ -275,39 +381,55 @@ Registers an observer to listen for the state changes of a specified application | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| -| bundleNameList | Array | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| +| bundleNameList | `Array` | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| + +**Return value** + +| Type| Description| +| --- | --- | +| number | Digital code of the observer, which will be used in **off()** to deregister the observer.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var applicationStateObserver = { + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); }, onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); }, onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); }, onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); }, onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } - } - var bundleNameList = ['bundleName1', 'bundleName2']; - try { - const observerCode = app.on("applicationState", applicationStateObserver, bundleNameList); - console.log('-------- observerCode: ---------', observerCode); - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); - } +} +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + const observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} +``` - ``` ## appManager.off off(type: "applicationState", observerId: number, callback: AsyncCallback\): void; @@ -321,29 +443,68 @@ Deregisters the application state observer. This API uses an asynchronous callba **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observerId | number | Yes| Digital code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var observerId = 100; - function unregisterApplicationStateObserverCallback(err) { - if (err) { - console.log('------------ unregisterApplicationStateObserverCallback ------------', err); - } +```ts +import appManager from '@ohos.app.ability.appManager'; + +let observeId = 0; + +// 1. Register an application state observer. +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } - try { - app.off(observerId, unregisterApplicationStateObserverCallback); - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); +} +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} + +// 2. Deregister the application state observer. +function unregisterApplicationStateObserverCallback(err) { + if (err.code !== 0) { + console.log("unregisterApplicationStateObserverCallback faile, err: " + JSON.stringify(err)); + } else { + console.log("unregisterApplicationStateObserverCallback success."); } - ``` +} +try { + appManager.off("applicationState", observerId, unregisterApplicationStateObserverCallback); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); +} +``` ## appManager.off @@ -361,38 +522,73 @@ Deregisters the application state observer. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observerId | number | Yes| Digital code of the observer.| **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var observerId = 100; - - try { - app.off(observerId) - .then((data) => { - console.log('----------- unregisterApplicationStateObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- unregisterApplicationStateObserver fail ----------', err); - }) - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let observeId = 0; + +// 1. Register an application state observer. +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } - ``` +} +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} + +// 2. Deregister the application state observer. +try { + appManager.off("applicationState", observerId).then((data) => { + console.log("unregisterApplicationStateObserver success, data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("unregisterApplicationStateObserver faile, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); +} +``` ## appManager.getForegroundApplications getForegroundApplications(callback: AsyncCallback\>): void; -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -400,96 +596,44 @@ Obtains applications that are running in the foreground. This API uses an asynch **System API**: This is a system API and cannot be called by third-party applications. -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| - -**Example** - - ```js - function getForegroundApplicationsCallback(err, data) { - if (err) { - console.log('--------- getForegroundApplicationsCallback fail ---------', err.code + ': ' + err.message); - } else { - console.log('--------- getForegroundApplicationsCallback success ---------', data) - } - } - app.getForegroundApplications(getForegroundApplicationsCallback); - ``` - -unregisterApplicationStateObserver(observerId: number): Promise\; - -Deregisters the application state observer. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER +**Error codes** -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | -**System API**: This is a system API and cannot be called by third-party applications. +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observerId | number | Yes| Numeric code of the observer.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| +| callback | AsyncCallback\> | Yes| Callback used to return the API call result and an array holding the application state data. You can perform error handling or custom processing in this callback.| **Example** - - ```ts - var observerId = 100; - app.unregisterApplicationStateObserver(observerId) - .then((data) => { - console.log('----------- unregisterApplicationStateObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- unregisterApplicationStateObserver fail ----------', err); - }) - ``` - -## appManager.getForegroundApplications9+ - -getForegroundApplications(callback: AsyncCallback\>): void; - -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| +```ts +import appManager from '@ohos.app.ability.appManager'; -**Example** - - ```ts - function getForegroundApplicationsCallback(err, data) { - if (err) { - console.log('--------- getForegroundApplicationsCallback fail ---------', err); +function getForegroundApplicationsCallback(err, data) { + if (err.code !== 0) { + console.log("getForegroundApplicationsCallback fail, err: " + JSON.stringify(err)); } else { - console.log('--------- getForegroundApplicationsCallback success ---------', data) + console.log("getForegroundApplicationsCallback success, data: " + JSON.stringify(data)); } - } - app.getForegroundApplications(getForegroundApplicationsCallback); - ``` +} +try { + appManager.getForegroundApplications(getForegroundApplicationsCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## appManager.getForegroundApplications9+ +## appManager.getForegroundApplications getForegroundApplications(): Promise\>; -Obtains applications that are running in the foreground. This API uses a promise to return the result. +Obtains applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -501,27 +645,35 @@ Obtains applications that are running in the foreground. This API uses a promise | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the application state data.| +| Promise\> | Promise used to return an array holding the application state data| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getForegroundApplications() - .then((data) => { - console.log('--------- getForegroundApplications success -------', data); - }) - .catch((err) => { - console.log('--------- getForegroundApplications fail -------', err); - }) - ``` - -## appManager.killProcessWithAccount9+ + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getForegroundApplications().then((data) => { + console.log("getForegroundApplications success, data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getForegroundApplications fail, err: " + JSON.stringify(err)); +}) +``` + +## appManager.killProcessWithAccount killProcessWithAccount(bundleName: string, accountId: number): Promise\ Kills a process by bundle name and account ID. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -529,27 +681,39 @@ Kills a process by bundle name and account ID. This API uses a promise to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -var bundleName = 'bundleName'; -var accountId = 0; -app.killProcessWithAccount(bundleName, accountId) - .then((data) => { - console.log('------------ killProcessWithAccount success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessWithAccount fail ------------', err); - }) +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +let accountId = 0; +try { + appManager.killProcessWithAccount(bundleName, accountId).then(() => { + console.log("killProcessWithAccount success"); + }).catch((err) => { + console.log("killProcessWithAccount fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` -## appManager.killProcessWithAccount9+ +## appManager.killProcessWithAccount killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void @@ -559,32 +723,42 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **System API**: This is a system API and cannot be called by third-party applications. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| + | bundleName | string | Yes| Bundle name.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| + | callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -var bundleName = 'bundleName'; -var accountId = 0; +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +let accountId = 0; function killProcessWithAccountCallback(err, data) { - if (err) { - console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); - } else { - console.log('------------- killProcessWithAccountCallback success, data: --------------', data); - } + if (err.code !== 0) { + console.log("killProcessWithAccountCallback fail, err: " + JSON.stringify(err)); + } else { + console.log("killProcessWithAccountCallback success."); + } } -app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); ``` -## appManager.killProcessesByBundleName9+ +## appManager.killProcessesByBundleName killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); @@ -600,24 +774,38 @@ Kills a process by bundle name. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - var bundleName = 'bundleName'; - function killProcessesByBundleNameCallback(err, data) { - if (err) { - console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +function killProcessesByBundleNameCallback(err, data) { + if (err.code !== 0) { + console.log("killProcessesByBundleNameCallback fail, err: " + JSON.stringify(err)); } else { - console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); + console.log("killProcessesByBundleNameCallback success."); } - } - app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); - ``` +} +try { + appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## appManager.killProcessesByBundleName9+ +## appManager.killProcessesByBundleName killProcessesByBundleName(bundleName: string): Promise\; @@ -633,7 +821,7 @@ Kills a process by bundle name. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** @@ -641,20 +829,32 @@ Kills a process by bundle name. This API uses a promise to return the result. | -------- | -------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** - - ```ts -var bundleName = 'bundleName'; -app.killProcessesByBundleName(bundleName) - .then((data) => { - console.log('------------ killProcessesByBundleName success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessesByBundleName fail ------------', err); - }) - ``` - -## appManager.clearUpApplicationData9+ + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +try { + appManager.killProcessesByBundleName(bundleName).then((data) => { + console.log("killProcessesByBundleName success."); + }).catch((err) => { + console.log("killProcessesByBundleName fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## appManager.clearUpApplicationData clearUpApplicationData(bundleName: string, callback: AsyncCallback\); @@ -670,24 +870,38 @@ Clears application data by bundle name. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - var bundleName = 'bundleName'; - function clearUpApplicationDataCallback(err, data) { + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +function clearUpApplicationDataCallback(err, data) { if (err) { - console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); + console.log("clearUpApplicationDataCallback fail, err: " + JSON.stringify(err)); } else { - console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); + console.log("clearUpApplicationDataCallback success."); } - } - app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); - ``` +} +try { + appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## appManager.clearUpApplicationData9+ +## appManager.clearUpApplicationData clearUpApplicationData(bundleName: string): Promise\; @@ -703,28 +917,42 @@ Clears application data by bundle name. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - var bundleName = 'bundleName'; - app.clearUpApplicationData(bundleName) - .then((data) => { - console.log('------------ clearUpApplicationData success ------------', data); - }) - .catch((err) => { - console.log('------------ clearUpApplicationData fail ------------', err); + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +try { + appManager.clearUpApplicationData(bundleName).then((data) => { + console.log("clearUpApplicationData success."); + }).catch((err) => { + console.log("clearUpApplicationData fail, err: " + JSON.stringify(err)); }) - ``` +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## ApplicationState9+ +## ApplicationState + +Enumerates the application states. This enum can be used together with [AbilityStateData](js-apis-inner-application-appStateData.md) to return the application state. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -738,7 +966,9 @@ Clears application data by bundle name. This API uses a promise to return the re | STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | | STATE_DESTROY | 5 | State indicating that the application is destroyed. | -## ProcessState9+ +## ProcessState + +Enumerates the process states. This enum can be used together with [ProcessData](js-apis-inner-application-processData.md) to return the process state. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index 6f512b4f9f32904106f9120ea2fcc1095ec732b8..e066ac119344842ffce617fd7934efa3712d895f 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.appRecovery (Application Recovery) +# @ohos.app.ability.appRecovery (appRecovery) -The **appRecovery** module provides APIs for recovering failed applications. +The **appRecovery** module provides APIs for recovering faulty applications. > **NOTE** > @@ -8,13 +8,13 @@ The **appRecovery** module provides APIs for recovering failed applications. ## Modules to Import ```ts -import appRecovery from '@ohos.app.ability.appRecovery' +import appRecovery from '@ohos.app.ability.appRecovery'; ``` ## appRecovery.RestartFlag -Enumerates the application restart options used in [enableAppRecovery](#apprecoveryenableapprecovery). +Enumerates the application restart flags. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -28,7 +28,7 @@ Enumerates the application restart options used in [enableAppRecovery](#apprecov ## appRecovery.SaveOccasionFlag -Enumerates the scenarios for saving the application state, which is used in [enableAppRecovery](#apprecoveryenableapprecovery). +Enumerates the scenarios for saving the application state. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -39,7 +39,7 @@ Enumerates the scenarios for saving the application state, which is used in [ena ## appRecovery.SaveModeFlag -Enumerates the application state saving modes used in [enableAppRecovery](#apprecoveryenableapprecovery). +Enumerates the application state saving modes. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -50,7 +50,7 @@ Enumerates the application state saving modes used in [enableAppRecovery](#appre ## appRecovery.enableAppRecovery -enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; +enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void; Enables application recovery. @@ -67,9 +67,17 @@ Enables application recovery. **Example** ```ts -export default class MyAbilityStage extends AbilityStage { +import appRecovery from '@ohos.app.ability.appRecovery'; +import AbilityStage from '@ohos.app.ability.AbilityStage'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class MyAbility extends UIAbility { onCreate() { - appRecovery.enableAppRecovery(RestartFlag::ALWAYS_RESTART, SaveOccasionFlag::SAVE_WHEN_ERROR, SaveModeFlag::SAVE_WITH_FILE); + appRecovery.enableAppRecovery( + appRecovery.RestartFlag::ALWAYS_RESTART, + appRecovery.SaveOccasionFlag::SAVE_WHEN_ERROR, + appRecovery.SaveModeFlag::SAVE_WITH_FILE + ); } } ``` @@ -86,13 +94,21 @@ Restarts the application. This API can be used together with APIs of [errorManag **Example** ```ts -var observer = { +import appRecovery from '@ohos.app.ability.appRecovery'; +import errorManager from '@ohos.app.ability.errorManager'; + +let observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) appRecovery.restartApp(); } -} +}; +try { + errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` ## appRecovery.saveAppState @@ -107,15 +123,24 @@ Saves the application state. This API can be used together with APIs of [errorMa | Type| Description| | -------- | -------- | -| boolean | Whether the saving is successful.| +| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.| **Example** ```ts -var observer = { +import appRecovery from '@ohos.app.ability.appRecovery'; +import errorManager from '@ohos.app.ability.errorManager'; + +let observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) appRecovery.saveAppState(); } +}; + +try { + errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); } ``` 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 23184c6036f12bd3c914d7b500fece72afafc538..5cc9b61b90fb3072aacf530fdaee0ae2633f7ac0 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.common +# @ohos.app.ability.common (Context) The **Common** module provides all level-2 module APIs for developers to export. @@ -15,21 +15,21 @@ import common from '@ohos.app.ability.common' **System capability**: SystemCapability.Ability.AbilityBase -| Name | Type | Mandatory| Description | -| ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No | Level-2 module **UIAbilityContext**. | -| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | Level-2 module **AbilityStageContext**.| -| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | Level-2 module **ApplicationContext**.| -| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | No | Level-2 module **BaseContext**.| -| Context | [Context](js-apis-inner-application-context.md) | No | Level-2 module **Context**.| -| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | Level-2 module **ExtensionContext**.| -| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | No | Level-2 module **FormExtensionContext**.| -| AreaMode | [AreaMode](#areamode) | No | Enumerated values of **AreaMode**.| -| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | No | Level-2 module **EventHub**.| -| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | No | Level-2 module **PermissionRequestResult**.| -| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | No | Level-2 module **PacMap**.| -| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No | Level-2 module **AbilityResult**.| -| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No | Level-2 module **ConnectOptions**.| +| Name | Type | Description | +| ----------- | -------------------- | ------------------------------------------------------------ | +| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Level-2 module **UIAbilityContext**. | +| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Level-2 module **AbilityStageContext**.| +| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | Level-2 module **ApplicationContext**.| +| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | Level-2 module **BaseContext**.| +| Context | [Context](js-apis-inner-application-context.md) | Level-2 module **Context**.| +| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Level-2 module **ExtensionContext**.| +| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.| +| AreaMode | [AreaMode](#areamode) | Enumerated values of **AreaMode**.| +| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | Level-2 module **EventHub**.| +| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | Level-2 module **PermissionRequestResult**.| +| 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**.| **Example** ```ts @@ -52,11 +52,11 @@ let connectOptions: common.ConnectOptions; ## AreaMode -Defines the area where the file to be access is located. Each area has its own content. +Enumerates the data encryption levels. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | --------------- | ---- | --------------- | -| EL1 | 0 | Device-level encryption area. | -| EL2 | 1 | User credential encryption area. The default value is **EL2**.| +| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on. | +| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md index 90075377af701150b8de77600ed3ae3808b50d41..88aab2d4026afac5edaf8c3c7ff58033976e3e66 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.Configuration +# @ohos.app.ability.Configuration (Configuration) The **Configuration** module defines environment change information. @@ -14,34 +14,42 @@ import Configuration from '@ohos.app.ability.Configuration' **System capability**: SystemCapability.Ability.AbilityBase -| Name| Type| Readable| Writable| Description| + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| language | string | Yes| Yes| Language of the application.| +| language | string | Yes| Yes| Language of the application, for example, **zh**.| | colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| +| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| +| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| | displayId | number | Yes| No| ID of the display where the application is located.| | hasPointerDevice | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file. -**Example** - +**Example** + ```ts - let envCallback = { - onConfigurationUpdated(config) { - console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) - let language = config.language; - let colorMode = config.colorMode; - let direction = config.direction; - let screenDensity = config.screenDensity; - let displayId = config.displayId; - let hasPointerDevice = config.hasPointerDevice; + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let envCallback = { + onConfigurationUpdated(config) { + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + let language = config.language; + let colorMode = config.colorMode; + let direction = config.direction; + let screenDensity = config.screenDensity; + let displayId = config.displayId; + let hasPointerDevice = config.hasPointerDevice; + } + }; + try { + let applicationContext = this.context.getApplicationContext(); + let callbackId = applicationContext.on("environment", envCallback); + console.log("callbackId: " + callbackId); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } } - }; - try { - var callbackId = applicationContext.on("environment", envCallback); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md index 24b6b4745b1ba606cdb40c741fa2fcf10376cc06..bd56e256603930f874c9ba2c064462c8fad594a8 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.ConfigurationConstant +# @ohos.app.ability.ConfigurationConstant (ConfigurationConstant) The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. @@ -25,7 +25,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | COLOR_MODE_LIGHT | 1 | Light mode.| -## ConfigurationConstant.Direction9+ +## ConfigurationConstant.Direction You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. @@ -38,7 +38,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | DIRECTION_HORIZONTAL | 1 | Horizontal direction.| -## ConfigurationConstant.ScreenDensity9+ +## ConfigurationConstant.ScreenDensity You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md index dc1b5a1430c8c063de23cc87126ff891d5363b80..0c39c8fa01fe62a537614287f3d27645c8b0f354 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.contextConstant +# @ohos.app.ability.contextConstant (ContextConstant) -The **ContextConstant** module defines data encryption levels. +The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of data encryption levels. > **NOTE** > @@ -19,7 +19,7 @@ You can obtain the value of this constant by calling the **ContextConstant.AreaM **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| EL1 | 0 | Device-level encryption area.| -| EL2 | 1 | User credential encryption area.| +| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.| +| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md index c7a6f6021594569e01519814160894fff5096c2d..9a869f051a08c4a79c9dac58e8f4dceb9dc4658b 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.dataUriUtils +# @ohos.app.ability.dataUriUtils (DataUriUtils) The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md index 1208aeb8dabdbc09b77a9395e0ad313b1bf7e8cd..0cb95a9abfd6b90f1efacc431070ef6b3397e1e6 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.EnvironmentCallback +# @ohos.app.ability.EnvironmentCallback (EnvironmentCallback) The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. @@ -33,18 +33,18 @@ Called when the system environment changes. ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from "@ohos.app.ability.Ability"; var callbackId; -export default class MyAbility extends Ability { +export default class MyAbility extends UIAbility { onCreate() { console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ console.log("onConfigurationUpdated config:" + JSON.stringify(config)); - }, + } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md index f7203ef5de08d0151d65e2c65cf19b6e3855c1ea..e543a93e9ceb5af52f3cdb939a0cfd5d24145968 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -1,13 +1,13 @@ -# @ohos.app.ability.errorManager (Error Manager) +# @ohos.app.ability.errorManager (ErrorManager) -The **errorManager** module provides APIs for registering and deregistering error observers. +The **ErrorManager** module provides APIs for registering and deregistering error observers. For example, you can use the APIs to register an observer when your application wants to capture JS crashes. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```ts import errorManager from '@ohos.app.ability.errorManager' ``` @@ -23,19 +23,26 @@ Registers an error observer. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Digital code of the observer.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | number | Index of the observer.| **Example** -```js +```ts var observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) } } +var observerId = -1; try { - errorManager.on("error", observer); + observerId = errorManager.on("error", observer); } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } @@ -53,13 +60,13 @@ Deregisters an error observer. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observerId | number | Yes| Index of the observer returned by **on()**.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** -```js +```ts var observerId = 100; function unregisterErrorObserverCallback(err) { @@ -86,8 +93,8 @@ Deregisters an error observer. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observerId | number | Yes| Index of the observer returned by **on()**.| **Return value** @@ -97,7 +104,7 @@ Deregisters an error observer. This API uses a promise to return the result. **Example** -```js +```ts var observerId = 100; try { errorManager.off("error", observerId) diff --git a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md index b53881f7fdb5df90cf0a1783c04554ce93240b04..d532723b43a1c31f2b01b35799747ec689df5099 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md @@ -1,30 +1,10 @@ -# @ohos.app.ability.ExtensionAbility +# @ohos.app.ability.ExtensionAbility (ExtensionAbility Base Class) -The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information. +**ExtensionAbility** is the base class for scenario-specific ExtensionAbilities. It is inherited from [Ability](js-apis-app-ability-ability.md), with no attribute or method added. You cannot inherit from this base class. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -## Modules to Import - -```ts -import ExtensionAbility from '@ohos.app.ability.ExtensionAbility'; -``` - **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```ts - class MyExtensionAbility extends ExtensionAbility { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 4f989652d549a118d01097b3a8ec2f5084ec0031..434fb19383e072a36352012300c2a755769d6c1f 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -1,15 +1,15 @@ -# @ohos.app.ability.missionManager +# @ohos.app.ability.missionManager (missionManager) The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```ts -import missionManager from '@ohos.app.ability.missionManager' +import missionManager from '@ohos.app.ability.missionManager'; ``` ## Required Permissions @@ -32,19 +32,19 @@ Registers a listener to observe the mission status. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listener | MissionListener | Yes| Listener to register.| + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.| **Return value** | Type| Description| | -------- | -------- | - | number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| + | number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.| **Example** ```ts -import Ability from '@ohos.application.Ability' import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, @@ -52,14 +52,15 @@ var listener = { onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; var listenerId = -1; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate"); globalThis.abilityWant = want; globalThis.context = this.context; } @@ -74,12 +75,12 @@ export default class MainAbility extends Ability { } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") try { listenerId = missionManager.on("mission", listener); } catch (paramError) { @@ -106,7 +107,7 @@ export default class MainAbility extends Ability { off(type: "mission", listenerId: number, callback: AsyncCallback<void>): void; -Deregisters a mission status listener. This API uses an asynchronous callback to return the result. +Deregisters a mission status listener. **Required permissions**: ohos.permission.MANAGE_MISSIONS @@ -118,14 +119,14 @@ Deregisters a mission status listener. This API uses an asynchronous callback to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts -import Ability from '@ohos.application.Ability' import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, @@ -133,14 +134,15 @@ var listener = { onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; var listenerId = -1; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") globalThis.abilityWant = want; globalThis.context = this.context; } @@ -155,12 +157,12 @@ export default class MainAbility extends Ability { } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") try { listenerId = missionManager.on("mission", listener); } catch (paramError) { @@ -199,19 +201,19 @@ Deregisters a mission status listener. This API uses a promise to return the res | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** ```ts -import Ability from '@ohos.application.Ability' import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, @@ -219,14 +221,15 @@ var listener = { onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; var listenerId = -1; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") globalThis.abilityWant = want; globalThis.context = this.context; } @@ -241,12 +244,12 @@ export default class MainAbility extends Ability { } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") try { listenerId = missionManager.on("mission", listener); } catch (paramError) { @@ -292,19 +295,28 @@ Obtains the information about a given mission. This API uses an asynchronous cal **Example** ```ts - import missionManager from '@ohos.app.ability.missionManager' + import missionManager from '@ohos.app.ability.missionManager'; + let testMissionId = 1; try { - var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); - missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { - console.log("getMissionInfo is called, error.code = " + error.code) - console.log("mission.missionId = " + mission.missionId); - console.log("mission.runningState = " + mission.runningState); - console.log("mission.lockedState = " + mission.lockedState); - console.log("mission.timestamp = " + mission.timestamp); - console.log("mission.label = " + mission.label); - console.log("mission.iconPath = " + mission.iconPath); - }); + var allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); + if (allMissions && allMissions.length > 0) { + testMissionId = allMissions[0].missionId; + } + + missionManager.getMissionInfo("", testMissionId, (error, mission) => { + if (error) { + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + } else { + console.log("mission.missionId = " + mission.missionId); + console.log("mission.runningState = " + mission.runningState); + console.log("mission.lockedState = " + mission.lockedState); + console.log("mission.timestamp = " + mission.timestamp); + console.log("mission.label = " + mission.label); + console.log("mission.iconPath = " + mission.iconPath); + } + }); } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } @@ -338,18 +350,20 @@ Obtains the information about a given mission. This API uses a promise to return **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var mission = missionManager.getMissionInfo("", 10).catch(function (err){ - console.log(err); +let testMissionId = 1; +try { + missionManager.getMissionInfo("", testMissionId).then((data) => { + console.info('getMissionInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionInfo failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('getMissionInfo failed. Cause: ' + error.message); +} +``` ## missionManager.getMissionInfos @@ -374,13 +388,17 @@ Obtains information about all missions. This API uses an asynchronous callback t **Example** ```ts - import missionManager from '@ohos.app.ability.missionManager' + import missionManager from '@ohos.app.ability.missionManager'; try { missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); + if (error) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + } else { + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + } }) } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); @@ -415,18 +433,19 @@ Obtains information about all missions. This API uses a promise to return the re **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ - console.log(err); +try { + missionManager.getMissionInfos("", 10).then((data) => { + console.info('getMissionInfos successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionInfos failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('getMissionInfos failed. Cause: ' + error.message); +} +``` ## missionManager.getMissionSnapShot @@ -449,27 +468,22 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) - }) - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +let testMissionId = 2; +try { + missionManager.getMissionSnapShot("", testMissionId, (err, data) => { + if (err) { + console.error('getMissionSnapShot failed:' + err.message); + } else { + console.info('getMissionSnapShot successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getMissionSnapShot failed:' + err.message); +} +``` ## missionManager.getMissionSnapShot @@ -497,26 +511,20 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ - console.log(err); - }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +let testMissionId = 2; +try { + missionManager.getMissionSnapShot("", testMissionId).then((data) => { + console.info('getMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionSnapShot failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getMissionSnapShot failed. Cause: ' + error.message); +} +``` ## missionManager.getLowResolutionMissionSnapShot @@ -539,27 +547,22 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { - console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) - }) - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +let testMissionId = 2; +try { + missionManager.getLowResolutionMissionSnapShot("", testMissionId, (err, data) => { + if (err) { + console.error('getLowResolutionMissionSnapShot failed:' + err.message); + } else { + console.info('getLowResolutionMissionSnapShot successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getLowResolutionMissionSnapShot failed:' + err.message); +} +``` ## missionManager.getLowResolutionMissionSnapShot @@ -588,25 +591,20 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ - console.log(err); - }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +let testMissionId = 2; +try { + missionManager.getLowResolutionMissionSnapShot("", testMissionId).then((data) => { + console.info('getLowResolutionMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); +} +``` ## missionManager.lockMission @@ -630,25 +628,22 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.lockMission(id).then(() => { - console.log("lockMission is called "); - }); +let testMissionId = 2; +try { + missionManager.lockMission(testMissionId, (err, data) => { + if (err) { + console.error('lockMission failed:' + err.message); + } else { + console.info('lockMission successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('lockMission failed:' + err.message); +} +``` ## missionManager.lockMission @@ -670,32 +665,25 @@ Locks a given mission. This API uses a promise to return the result. **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.lockMission(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.lockMission(testMissionId).then((data) => { + console.info('lockMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('lockMission failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('lockMission failed. Cause: ' + error.message); +} +``` ## missionManager.unlockMission @@ -717,26 +705,22 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.unlockMission(id).then(() => { - console.log("unlockMission is called "); - }); +let testMissionId = 2; +try { + missionManager.unlockMission(testMissionId, (err, data) => { + if (err) { + console.error('unlockMission failed:' + err.message); + } else { + console.info('unlockMission successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('unlockMission failed:' + err.message); +} +``` ## missionManager.unlockMission @@ -758,35 +742,26 @@ Unlocks a given mission. This API uses a promise to return the result. **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.lockMission(id).catch(function (err){ - console.log(err); - }); - missionManager.unlockMission(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.unlockMission(testMissionId).then((data) => { + console.info('unlockMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('unlockMission failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('unlockMission failed. Cause: ' + error.message); +} +``` ## missionManager.clearMission @@ -809,24 +784,22 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.clearMission(id).then(() => { - console.log("clearMission is called "); - }); +let testMissionId = 2; +try { + missionManager.clearMission(testMissionId, (err, data) => { + if (err) { + console.error('clearMission failed:' + err.message); + } else { + console.info('clearMission successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +} catch (err) { + console.error('clearMission failed:' + err.message); +} +``` ## missionManager.clearMission @@ -849,32 +822,26 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.clearMission(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.clearMission(testMissionId).then((data) => { + console.info('clearMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('clearMission failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('clearMission failed. Cause: ' + error.message); +} +``` ## missionManager.clearAllMissions @@ -890,14 +857,21 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - missionManager.clearAllMissions().then(() => { - console.log("clearAllMissions is called "); - }); - ``` +```ts +import missionManager from '@ohos.app.ability.missionManager'; +try { + missionManager.clearAllMissions(err => { + if (err) { + console.error('clearAllMissions failed:' + err.message); + } else { + console.info('clearAllMissions successfully.'); + } + }); +} catch (err) { + console.error('clearAllMissions failed:' + err.message); +} +``` ## missionManager.clearAllMissions @@ -913,19 +887,25 @@ Clears all unlocked missions. This API uses a promise to return the result. **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' - missionManager.clearAllMissions().catch(function (err){ - console.log(err); - }); - ``` +```ts +import missionManager from '@ohos.app.ability.missionManager'; +try { + missionManager.clearAllMissions(bundleName).then(() => { + console.info('clearAllMissions successfully.'); + }).catch(err => { + console.error('clearAllMissions failed:' + err.message); + }); +} catch (err) { + console.error('clearAllMissions failed:' + err.message); +} +``` ## missionManager.moveMissionToFront @@ -948,25 +928,22 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.moveMissionToFront(id).then(() => { - console.log("moveMissionToFront is called "); - }); +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId, (err, data) => { + if (err) { + console.error('moveMissionToFront failed:' + err.message); + } else { + console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('moveMissionToFront failed:' + err.message); +} +``` ## missionManager.moveMissionToFront @@ -990,25 +967,22 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => { - console.log("moveMissionToFront is called "); - }); +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId, {windowMode : 101}, (err, data) => { + if (err) { + console.error('moveMissionToFront failed:' + err.message); + } else { + console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('moveMissionToFront failed:' + err.message); +} +``` ## missionManager.moveMissionToFront @@ -1031,28 +1005,23 @@ Switches a given mission to the foreground, with the startup parameters for the **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.moveMissionToFront(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId).then((data) => { + console.info('moveMissionToFront successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('moveMissionToFront failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +} catch (error) { + console.error('moveMissionToFront failed. Cause: ' + error.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md index c703726492eb8bc4ddd1211f97d95a3490a8938a..a2090ed00e60cac1b5452bf6357f47cfb3c7be2e 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.quickFixManager +# @ohos.app.ability.quickFixManager (quickFixManager) The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire application. @@ -36,7 +36,7 @@ Defines the quick fix information at the application level. | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | bundleVersionCode | number | Yes | Internal version number of the application. | | bundleVersionName | string | Yes | Version number of the application that is shown to users. | | quickFixVersionCode | number | Yes | Version code of the quick fix patch package. | @@ -65,8 +65,6 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - try { let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { @@ -108,8 +106,6 @@ Applies a quick fix patch. This API uses a promise to return the result. **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] try { quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { @@ -136,16 +132,14 @@ Obtains the quick fix information of the application. This API uses an asynchron **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes|Bundle name of the application. | - | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes|Bundle name. | +| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - try { let bundleName = "bundleName" quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { @@ -174,9 +168,9 @@ Obtains the quick fix information of the application. This API uses a promise to **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of the application. | +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| **Return value** @@ -187,8 +181,6 @@ Obtains the quick fix information of the application. This API uses a promise to **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - try { let bundleName = "bundleName" quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { @@ -199,4 +191,4 @@ Obtains the quick fix information of the application. This API uses a promise to } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } -``` + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md index 6c3e0e6e2a0e116120aa405758506d46175c3468..0efdb59d5eaed4c2b70e5ff666b0c9d63b11212f 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -1,10 +1,10 @@ -# @ohos.app.ability.ServiceExtensionAbility +# @ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility) -The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. +The **ServiceExtensionAbility** module provides lifecycle callbacks when a ServiceExtensionAbility (background service) is created, destroyed, connected, or disconnected. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -23,16 +23,16 @@ None. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| ServiceExtensionContext, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate onCreate(want: Want): void; -Called when a Service Extension ability is created to initialize the service logic. +Called when a ServiceExtensionAbility is created to initialize the service logic. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -40,9 +40,9 @@ Called when a Service Extension ability is created to initialize the service log **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Example** @@ -59,7 +59,7 @@ Called when a Service Extension ability is created to initialize the service log onDestroy(): void; -Called when this Service Extension ability is destroyed to clear resources. +Called when this ServiceExtensionAbility is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -80,7 +80,7 @@ Called when this Service Extension ability is destroyed to clear resources. onRequest(want: Want, startId: number): void; -Called after **onCreate** is invoked when a Service Extension ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. +Called following **onCreate()** when a ServiceExtensionAbility is started by calling **startAbility()**. The value of **startId** is incremented for each ability that is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -88,10 +88,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| +| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** @@ -108,7 +108,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started onConnect(want: Want): rpc.RemoteObject; -Called after **onCreate** is invoked when a Service Extension ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. +Called following **onCreate()** when a ServiceExtensionAbility is started by calling **connectAbility()**. A **RemoteObject** object is returned for communication between the server and client. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -116,15 +116,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| +| Type| Description| +| -------- | -------- | +| rpc.RemoteObject | A **RemoteObject** object used for communication between the server and client.| **Example** @@ -150,7 +150,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started onDisconnect(want: Want): void; -Called when this Service Extension ability is disconnected. +Called when a client is disconnected from this ServiceExtensionAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -158,9 +158,9 @@ Called when this Service Extension ability is disconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Example** @@ -176,7 +176,7 @@ Called when this Service Extension ability is disconnected. onReconnect(want: Want): void; -Called when this Service Extension ability is reconnected. +Called when a new client attempts to connect to this ServiceExtensionAbility after all previous clients are disconnected. This capability is reserved. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -184,9 +184,9 @@ Called when this Service Extension ability is reconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Example** @@ -202,7 +202,7 @@ Called when this Service Extension ability is reconnected. onConfigurationUpdate(newConfig: Configuration): void; -Called when the configuration of this Service Extension ability is updated. +Called when the configuration of this ServiceExtensionAbility is updated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -210,9 +210,9 @@ Called when the configuration of this Service Extension ability is updated. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| **Example** @@ -236,9 +236,9 @@ Dumps the client information. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md index fc5215fe400919172a7c2f2dd7c5a567e44acae3..3e95fbf541e7ed79834673c2ca97b1398bc73989 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.StartOptions +# @ohos.app.ability.StartOptions (StartOptions) -The **StartOptions** module implements ability startup options. +**StartOptions** is used as an input parameter of [startAbility()](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1) to specify the window mode of an ability. > **NOTE** > @@ -21,4 +21,4 @@ import StartOptions from '@ohos.app.ability.StartOptions'; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| -| displayId | number | No| Display ID.| +| displayId | number | No| Display ID. The default value is **0**, indicating the current display.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index cce8b81738f29586417ae5f9814da2448f053e17..38d9f5428c37873ae9f786ed0f391142f30a011b 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -1,11 +1,9 @@ -# @ohos.app.ability.UIAbility +# @ohos.app.ability.UIAbility (UIAbility) -The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. +UIAbility is an application component that has the UI. The **UIAbility** module provides lifecycle callback such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration: -This module provides the following common ability-related functions: - -- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). -- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. +- [Caller](#caller): an object returned by [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall). The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee). +- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). > **NOTE** > @@ -15,39 +13,39 @@ This module provides the following common ability-related functions: ## Modules to Import ```ts -import Ability from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; ``` ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of an ability.| -| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the ability.| -| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the ability was started last time.| -| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| +| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.| +| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.| +| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the UIAbility was started last time.| +| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| -## Ability.onCreate +## UIAbility.onCreate onCreate(want: Want, param: AbilityConstant.LaunchParam): void; -Called to initialize the service logic when an ability is created. +Called to initialize the service logic when a UIAbility is created. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this ability, including the ability name and bundle name.| - | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this UIAbility, including the ability name and bundle name.| +| param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); } @@ -55,24 +53,24 @@ Called to initialize the service logic when an ability is created. ``` -## Ability.onWindowStageCreate +## UIAbility.onWindowStageCreate onWindowStageCreate(windowStage: window.WindowStage): void -Called when a **WindowStage** is created for this ability. +Called when a **WindowStage** is created for this UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); } @@ -80,18 +78,18 @@ Called when a **WindowStage** is created for this ability. ``` -## Ability.onWindowStageDestroy +## UIAbility.onWindowStageDestroy onWindowStageDestroy(): void -Called when the **WindowStage** is destroyed for this ability. +Called when the **WindowStage** is destroyed for this UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onWindowStageDestroy() { console.log('onWindowStageDestroy'); } @@ -99,24 +97,24 @@ Called when the **WindowStage** is destroyed for this ability. ``` -## Ability.onWindowStageRestore +## UIAbility.onWindowStageRestore onWindowStageRestore(windowStage: window.WindowStage): void -Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability. +Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onWindowStageRestore(windowStage) { console.log('onWindowStageRestore'); } @@ -124,18 +122,18 @@ Called when the **WindowStage** is restored during the migration of this ability ``` -## Ability.onDestroy +## UIAbility.onDestroy onDestroy(): void; -Called when this ability is destroyed to clear resources. +Called when this UIAbility is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onDestroy() { console.log('onDestroy'); } @@ -143,18 +141,18 @@ Called when this ability is destroyed to clear resources. ``` -## Ability.onForeground +## UIAbility.onForeground onForeground(): void; -Called when this ability is switched from the background to the foreground. +Called when this UIAbility is switched from the background to the foreground. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onForeground() { console.log('onForeground'); } @@ -162,18 +160,18 @@ Called when this ability is switched from the background to the foreground. ``` -## Ability.onBackground +## UIAbility.onBackground onBackground(): void; -Called when this ability is switched from the foreground to the background. +Called when this UIAbility is switched from the foreground to the background. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onBackground() { console.log('onBackground'); } @@ -181,7 +179,7 @@ Called when this ability is switched from the foreground to the background. ``` -## Ability.onContinue +## UIAbility.onContinue onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; @@ -191,21 +189,21 @@ Called to save data during the ability migration preparation process. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | wantParam | {[key: string]: any} | Yes| **want** parameter.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wantParam | {[key: string]: any} | Yes| **want** parameter.| **Return value** - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnContinueResult | Continuation result.| +| Type| Description| +| -------- | -------- | +| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.| **Example** ```ts - import AbilityConstant from "@ohos.application.AbilityConstant" - class myAbility extends Ability { + import AbilityConstant from "@ohos.app.ability.AbilityConstant" + class MyUIAbility extends UIAbility { onContinue(wantParams) { console.log('onContinue'); wantParams["myData"] = "my1234567"; @@ -215,32 +213,33 @@ Called to save data during the ability migration preparation process. ``` -## Ability.onNewWant +## UIAbility.onNewWant onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; -Called when the ability startup mode is set to singleton. +Called when a new Want is passed in and this UIAbility is started again. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want parameters, such as the ability name and bundle name.| - | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| +| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| **Example** ```ts - class myAbility extends Ability { - onNewWant(want) { + class MyUIAbility extends UIAbility { + onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); + console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); } } ``` -## Ability.onDump +## UIAbility.onDump onDump(params: Array\): Array\; @@ -250,14 +249,14 @@ Dumps client information. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onDump(params) { console.log('dump, params:' + JSON.stringify(params)); return ["params"] @@ -266,33 +265,33 @@ Dumps client information. ``` -## Ability.onSaveState +## UIAbility.onSaveState onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; -Called when the framework automatically saves the ability state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). +Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). If automatic state saving is enabled, **onSaveState** is called to save the state of this UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reason | [AbilityConstant.StateType](js-apis-application-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the ability state.| - | wantParam | {[key: string]: any} | Yes| **want** parameter.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.| +| wantParam | {[key: string]: any} | Yes| **want** parameter.| **Return value** - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnSaveResult | Whether the ability state is saved.| +| Type| Description| +| -------- | -------- | +| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.| **Example** ```ts -import AbilityConstant from '@ohos.application.AbilityConstant' +import AbilityConstant from '@ohos.app.ability.AbilityConstant' -class myAbility extends Ability { +class MyUIAbility extends UIAbility { onSaveState(reason, wantParam) { console.log('onSaveState'); wantParam["myData"] = "my1234567"; @@ -305,7 +304,7 @@ class myAbility extends Ability { ## Caller -Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). +Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility). ## Caller.call @@ -317,29 +316,29 @@ Sends sequenceable data to the target ability. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| +| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return a response.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return a response.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; - class MyMessageAble{ // Custom sequenceable data structure + class MyMessageAble{ // Custom sequenceable data structure. name:"" str:"" num: 1 @@ -360,13 +359,13 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). return true; } }; - var method = 'call_Function'; // Notification message string negotiated by the two abilities + var method = 'call_Function'; // Notification message string negotiated by the two abilities. var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -398,28 +397,28 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| +| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| +| Type| Description| +| -------- | -------- | +| Promise<[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)> | Promise used to return the sequenceable data from the target ability.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -443,11 +442,11 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). }; var method = 'call_Function'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -491,13 +490,12 @@ Releases the caller interface of the target ability. **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -525,20 +523,19 @@ Registers a callback that is invoked when the stub on the target ability is disc **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| **Example** ```ts - import Ability from '@ohos.application.Ability'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -568,28 +565,28 @@ Registers a callback that is invoked when the stub on the target ability is disc **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **release**.| - | callback | OnReleaseCallback | Yes| Callback used for the **onRelease** API.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is fixed at **release**.| +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -624,22 +621,22 @@ Registers a caller notification callback, which is invoked when the target abili **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities.| - | callback | CalleeCallback | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities.| +| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -668,7 +665,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). pdata.readSequenceable(msg); return new MyMessageAble("test1", "Callee test"); } - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -691,24 +688,24 @@ Deregisters a caller notification callback, which is invoked when the target abi **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Registered notification message string.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Registered notification message string.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; var method = 'call_Function'; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -727,9 +724,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Readable| Writable| Type| Description| +| Name| Readable| Writable| Type| Description| | -------- | -------- | -------- | -------- | -------- | -| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| +| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| ## CalleeCallback @@ -737,6 +734,6 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Readable| Writable| Type| Description| +| Name| Readable| Writable| Type| Description| | -------- | -------- | -------- | -------- | -------- | -| (indata: rpc.MessageParcel) | Yes| No| rpc.Sequenceable | Prototype of the listener function registered by the callee.| +| (indata: [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated)) | Yes| No| [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Prototype of the listener function registered by the callee.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md index c7bd4f6e9693c9bcc7ac71286e204f4d0b5005a8..c96e29d90f3a10a563df41bc8a545cb42dfdeba4 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.Want +# @ohos.app.ability.Want (Want) -Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When UIAbility A needs to start UIAbility B and transfer some data to UIAbility B, it can use Want a carrier to transfer the data. > **NOTE** > @@ -18,26 +18,26 @@ import Want from '@ohos.app.ability.Want'; | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. | -| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| bundleName | string | No | Bundle name of the ability.| +| moduleName | string | No| Name of the module to which the ability belongs.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| -| uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | -| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| -| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. | -| moduleName | string | No | Module to which the ability belongs.| +| [action](js-apis-app-ability-wantConstant.md#wantconstantaction) | string | No | Action to take, such as viewing and sharing application details. 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 details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | +| [entities](js-apis-app-ability-wantConstant.md#wantconstantentity) | Array\ | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.| +| uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | string | No| MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.| +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | No| How the **Want** object will be handled. By default, a number is passed in.
For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.| **Example** -- Basic usage +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). ```ts - var want = { + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", "moduleName": "entry" // moduleName is optional. }; this.context.startAbility(want, (error) => { @@ -46,13 +46,13 @@ import Want from '@ohos.app.ability.Want'; }) ``` -- Data is transferred through user-defined fields. The following data types are supported: +- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility): * String ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForString: "str", }, @@ -61,8 +61,8 @@ import Want from '@ohos.app.ability.Want'; * Number ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForInt: 100, keyForDouble: 99.99, @@ -72,8 +72,8 @@ import Want from '@ohos.app.ability.Want'; * Boolean ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForBool: true, }, @@ -82,8 +82,8 @@ import Want from '@ohos.app.ability.Want'; * Object ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForObject: { keyForObjectString: "str", @@ -97,8 +97,8 @@ import Want from '@ohos.app.ability.Want'; * Array ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForArrayString: ["str1", "str2", "str3"], keyForArrayInt: [100, 200, 300, 400], @@ -109,26 +109,28 @@ import Want from '@ohos.app.ability.Want'; ``` * File descriptor (FD) ```ts - import fileio from '@ohos.fileio'; - var fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); + import fileio from '@ohos.fileio'; + let fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", + "moduleName": "entry", // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} } - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} - } - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) ``` - +- For more details and examples, see [Want](../../application-models/want-overview.md). + + diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md index 3a73d862541383d93b8944d5b57326656ca50b4c..43b95743b25c34bdae9457c1e1ed1cf01f8e986e 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.wantAgent +# @ohos.app.ability.wantAgent (WantAgent) The **app.ability.WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md index ece4baa69e5d3b2883e971655e2367e23acf7812..4d7a483eab8a55c91d4dbb89287fa611f980ef34 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.wantConstant +# @ohos.app.ability.wantConstant (wantConstant) The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. @@ -14,7 +14,7 @@ import wantConstant from '@ohos.app.ability.wantConstant'; ## wantConstant.Action -Enumerates the action constants of the **Want** object. +Enumerates the action constants of the **Want** object. **action** specifies the operation to execute. **System capability**: SystemCapability.Ability.AbilityBase @@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object. | INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | | INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. | | ACTION_FILE_SELECT | ohos.action.fileSelect | Action of selecting a file. | -| PARAMS_STREAM | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | +| PARAMS_STREAM | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | ACTION_APP_ACCOUNT_AUTH | account.appAccount.action.auth | Action of providing the authentication service. | | ACTION_MARKET_DOWNLOAD | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_CROWDTEST | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | @@ -56,7 +56,7 @@ Enumerates the action constants of the **Want** object. ## wantConstant.Entity -Enumerates the entity constants of the **Want** object. +Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability. **System capability**: SystemCapability.Ability.AbilityBase @@ -71,7 +71,7 @@ Enumerates the entity constants of the **Want** object. ## wantConstant.Flags -Describes flags. + Enumerates the flags that specify how the Want will be handled. **System capability**: SystemCapability.Ability.AbilityBase @@ -79,17 +79,4 @@ Describes flags. | ------------------------------------ | ---------- | ------------------------------------------------------------ | | FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | | FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | -| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | -| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | -| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | -| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | -| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | -| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| -| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md index bf3f9cbb803b4bed60bba43d88813e6acf38fcb2..51637975d72ea807f428f235aec90310f69b197f 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -1,4 +1,4 @@ -# @ohos.app.form.formBindingData +# @ohos.application.formBindingData (formBindingData) The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. @@ -48,20 +48,17 @@ Creates a **FormBindingData** object. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility'; -import fileio from '@ohos.fileio'; -let context=featureAbility.getContext(); -context.getOrCreateLocalDir((err,data)=>{ - let path=data+"/xxx.jpg"; - let fd = fileio.openSync(path); +import fs from '@ohos.file.fs'; +import formBindingData from '@ohos.app.form.formBindingData'; + +try { + let fd = fs.openSync('/path/to/form.png') let obj = { "temperature": "21°", - "formImages": {"image": fd} + "formImages": { "image": fd } }; - try { - formBindingData.createFormBindingData(obj); - } catch (error) { - console.log(`catch err->${JSON.stringify(err)}`); - } -}) + formBindingData.createFormBindingData(obj); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md index c2bedd6d4dc1b50b6575120b88c0ab88423e7846..ef4e93e215b868013f025722737472735a1016f7 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -1,6 +1,6 @@ -# @ohos.app.form.FormExtensionAbility +# @ohos.app.form.FormExtensionAbility (FormExtensionAbility) -The **FormExtensionAbility** module provides APIs related to Form Extension abilities. +The **FormExtensionAbility** module provides lifecycle callbacks invoked when a widget is created, destroyed, or updated. > **NOTE** > @@ -17,9 +17,9 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; **System capability**: SystemCapability.Ability.Form -| Name | Type | Readable| Writable| Description | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the **FormExtensionAbility**. This context is inherited from **ExtensionContext**.| +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the FormExtensionAbility. This context is inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).| ## onAddForm @@ -33,7 +33,7 @@ Called to notify the widget provider that a **Form** instance (widget) has been | Name| Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Information related to the Extension ability, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| +| want | [Want](js-apis-application-want.md) | Yes | Want information related to the FormExtensionAbility, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| **Return value** @@ -45,17 +45,19 @@ Called to notify the widget provider that a **Form** instance (widget) has been ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want) { console.log('FormExtensionAbility onAddForm, want:' + want.abilityName); let dataObj1 = { - temperature:"11c", - "time":"11:00" + temperature: "11c", + "time": "11:00" }; let obj1 = formBindingData.createFormBindingData(dataObj1); return obj1; } -} +}; ``` ## onCastToNormalForm @@ -75,18 +77,20 @@ Called to notify the widget provider that a temporary widget has been converted **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onCastToNormalForm(formId) { console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId); } -} +}; ``` ## onUpdateForm onUpdateForm(formId: string): void -Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) class to update the widget data. +Called to notify the widget provider that a widget has been updated. After obtaining the latest data, your application should call [updateForm](js-apis-app-form-formProvider.md#updateform) of **formProvider** to update the widget data. **System capability**: SystemCapability.Ability.Form @@ -99,17 +103,24 @@ Called to notify the widget provider that a widget has been updated. After obtai **Example** ```ts -import formBindingData from '@ohos.app.form.formBindingData' +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; +import formProvider from '@ohos.app.form.formProvider'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onUpdateForm(formId) { console.log('FormExtensionAbility onUpdateForm, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2).then((data)=>{ + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + formProvider.updateForm(formId, obj2).then((data) => { console.log('FormExtensionAbility context updateForm, data:' + data); }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } -} + console.error('Operation updateForm failed. Cause: ' + error); + }); + } +}; ``` ## onChangeFormVisibility @@ -129,21 +140,28 @@ Called to notify the widget provider of the change of visibility. **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData' +import formProvider from '@ohos.app.form.formProvider'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onChangeFormVisibility(newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2).then((data)=>{ + console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + + for (let key in newStatus) { + console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); + formProvider.updateForm(key, obj2).then((data) => { console.log('FormExtensionAbility context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error); + }); } } -} +}; ``` ## onFormEvent @@ -164,11 +182,13 @@ Called to instruct the widget provider to receive and process the widget event. **Example** ```ts -export default class MyFormExtension extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onFormEvent(formId, message) { console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); } -} +}; ``` ## onRemoveForm @@ -188,11 +208,13 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onRemoveForm(formId) { console.log('FormExtensionAbility onRemoveForm, formId:' + formId); } -} +}; ``` ## onConfigurationUpdate @@ -207,16 +229,18 @@ Called when the configuration of the environment where the ability is running is | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| newConfig | [Configuration](js-apis-configuration.md) | Yes| New configuration.| +| newConfig | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| **Example** ```ts -class MyFormExtensionAbility extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onConfigurationUpdate(config) { console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); } -} +}; ``` ## onAcquireFormState @@ -236,13 +260,15 @@ Called when the widget provider receives the status query result of a widget. By **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formInfo from '@ohos.app.form.formInfo'; -class MyFormExtensionAbility extends FormExtensionAbility { + +export default class MyFormExtensionAbility extends FormExtensionAbility { onAcquireFormState(want) { console.log('FormExtensionAbility onAcquireFormState, want:' + want); return formInfo.FormState.UNKNOWN; } -} +}; ``` ## onShareForm @@ -270,14 +296,16 @@ Called by the widget provider to receive shared widget data. **Example** ```ts -class MyFormExtensionAbility extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onShareForm(formId) { console.log('FormExtensionAbility onShareForm, formId:' + formId); let wantParams = { - "temperature":"20", - "time":"2022-8-8 09:59", + "temperature": "20", + "time": "2022-8-8 09:59", }; return wantParams; } -} +}; ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md index 826050a278af8fa031a54ddcbf701b8759e4132a..e78cf3647a1298ed77b4993d811393ede4e2e5b6 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -1,6 +1,6 @@ -# @ohos.app.form.formHost +# @ohos.app.form.formHost (formHost) -The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. +The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. > **NOTE** > @@ -28,31 +28,32 @@ Deletes a widget. After this API is called, the application can no longer use th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.deleteForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.deleteForm(formId, (error) => { if (error) { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost deleteForm success'); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } - ``` ## deleteForm @@ -82,21 +83,23 @@ Deletes a widget. After this API is called, the application can no longer use th | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Parameters** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -115,27 +118,29 @@ Releases a widget. After this API is called, the application can no longer use t | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.releaseForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.releaseForm(formId, (error) => { if (error) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -155,27 +160,29 @@ Releases a widget. After this API is called, the application can no longer use t | -------------- | ------ | ---- | ----------- | | formId | string | Yes | Widget ID. | | isReleaseCache | boolean | Yes | Whether to release the cache.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.releaseForm(formId, true, (error, data) => { + let formId = "12400633174999288"; + formHost.releaseForm(formId, true, (error) => { if (error) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -206,21 +213,23 @@ Releases a widget. After this API is called, the application can no longer use t | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -239,27 +248,29 @@ Requests a widget update. This API uses an asynchronous callback to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.requestForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.requestForm(formId, (error) => { if (error) { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -289,21 +300,23 @@ Requests a widget update. This API uses a promise to return the result. | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -323,27 +336,29 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.castToNormalForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.castToNormalForm(formId, (error) => { if (error) { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -373,21 +388,23 @@ Converts a temporary widget to a normal one. This API uses a promise to return t | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.castToNormalForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -406,27 +423,29 @@ Instructs the widget framework to make a widget visible. After this API is calle | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.notifyVisibleForms(formId, (error) => { if (error) { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -456,21 +475,23 @@ Instructs the widget framework to make a widget visible. After this API is calle | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -489,27 +510,29 @@ Instructs the widget framework to make a widget invisible. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.notifyInvisibleForms(formId, (error) => { if (error) { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -539,21 +562,23 @@ Instructs the widget framework to make a widget invisible. After this API is cal | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -572,27 +597,29 @@ Instructs the widget framework to make a widget updatable. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.enableFormsUpdate(formId, (error) => { if (error) { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -622,21 +649,23 @@ Instructs the widget framework to make a widget updatable. After this API is cal | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -655,27 +684,29 @@ Instructs the widget framework to make a widget not updatable. After this API is | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.disableFormsUpdate(formId, (error) => { if (error) { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -705,21 +736,23 @@ Instructs the widget framework to make a widget not updatable. After this API is | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -735,20 +768,21 @@ Checks whether the system is ready. This API uses an asynchronous callback to re | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; formHost.isSystemReady((error, data) => { if (error) { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -769,15 +803,16 @@ Checks whether the system is ready. This API uses a promise to return the result **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -795,21 +830,23 @@ Obtains the widget information provided by all applications on the device. This | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getAllFormsInfo((error, data) => { if (error) { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -825,21 +862,23 @@ Obtains the widget information provided by all applications on the device. This **Return value** -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Type | Description | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -857,29 +896,31 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { if (error) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -897,30 +938,32 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | Yes| Module name.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { if (error) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -938,33 +981,35 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | No| Module name.| **Return value** -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Type | Description | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -983,22 +1028,24 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of valid widget IDs.| -| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds, (error, data) => { if (error) { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1027,15 +1074,17 @@ Deletes invalid widgets from the list. This API uses a promise to return the res **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1053,20 +1102,22 @@ Obtains the widget state. This API uses an asynchronous callback to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| -| callback | AsyncCallback<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| +| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formHost from '@ohos.app.form.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -1079,13 +1130,13 @@ var want = { try { formHost.acquireFormState(want, (error, data) => { if (error) { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1103,25 +1154,27 @@ Obtains the widget state. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| +| Promise<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formHost from '@ohos.app.form.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -1135,10 +1188,10 @@ try { formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1160,6 +1213,8 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -1179,11 +1234,13 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on("formUninstall")**.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -1206,27 +1263,29 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isVisible | boolean | Yes | Whether to make the widgets visible.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { - formHost.notifyFormsVisible(formIds, true, (error, data) => { + formHost.notifyFormsVisible(formIds, true, (error) => { if (error) { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1257,21 +1316,23 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1291,27 +1352,29 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { - formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + formHost.notifyFormsEnableUpdate(formIds, true, (error) => { if (error) { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1342,21 +1405,23 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` ## shareForm @@ -1375,29 +1440,30 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| | deviceId | string | Yes | Remote device ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). - +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +import formHost from '@ohos.app.form.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; try { - formHost.shareForm(formId, deviceId, (error, data) => { + formHost.shareForm(formId, deviceId, (error) => { if (error) { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1428,22 +1494,24 @@ Shares a specified widget with a remote device. This API uses a promise to retur | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| -**Parameters** +**Example** ```ts -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +import formHost from '@ohos.app.form.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; try { formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1451,6 +1519,8 @@ try { notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void +Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result. + **Required permissions**: ohos.permission.REQUIRE_FORM **System capability**: SystemCapability.Ability.Form @@ -1459,20 +1529,75 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callb | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| deviceId | string | Yes | Remote device ID.| +| formIds | Array\ | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If privacy protection is set successfully, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID | Error Message | +| ------------------------------------------------------------ | ------------------ | +| 401 | Incorrect input parameter.| +| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| | + +**Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyFormsPrivacyProtected + +function notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean): Promise\; + +Notifies that the privacy protection status of the specified widgets changes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------- | ---- | -------------------------------- | +| formIds | Array\ | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID | Error Message | +| ------------------------------------------------------------ | ------------------ | +| 401 | Incorrect input parameter.| +| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| | + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost shareForm success'); + console.log('formHost notifyFormsPrivacyProtected success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md index 5f1ff73b163ffd2c1c5b0feeb1c26a4f3f60cb78..84b40a57a56038b89ddf7ee06caef5f492e252f0 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -1,6 +1,6 @@ -# @ohos.app.form.formInfo +# @ohos.app.form.formInfo (formInfo) -The **FormInfo** module provides widget information and state. +The **formInfo** module provides types and enums related to the widget information and state. > **NOTE** > @@ -20,8 +20,8 @@ Describes widget information. | Name | Type | Readable | Writable | Description | | ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | -| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | -| moduleName | string | Yes | No | Name of the module to which the widget belongs. | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| moduleName | string | Yes | No | Name of the module to which the widget belongs. | | abilityName | string | Yes | No | Name of the ability to which the widget belongs. | | name | string | Yes | No | Widget name. | | description | string | Yes | No | Description of the widget. | @@ -30,11 +30,11 @@ Describes widget information. | colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | | isDefault | boolean | Yes | No | Whether the widget is the default one. | | updateEnabled | boolean | Yes | No | Whether the widget is updatable. | -| formVisibleNotify | string | Yes | No | Whether to send a notification when the widget is visible. | -| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | +| formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. | +| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | | scheduledUpdateTime | string | Yes | No | Time when the widget was updated. | | formConfigAbility | string | Yes | No | Configuration ability of the widget, that is, the ability corresponding to the option in the selection box displayed when the widget is long pressed. | -| updateDuration | string | Yes | No | Update period of the widget.| +| updateDuration | number | Yes | No | Update period of the widget.| | defaultDimension | number | Yes | No | Default dimension of the widget. | | supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#formdimension). | | customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | @@ -100,8 +100,8 @@ Enumerates the widget parameters. | WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | | HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | -| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. | -| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID.
**System API**: This is a system API. | +| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. | +| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID. | | BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| ## FormDimension @@ -125,9 +125,9 @@ Defines the widget information filter. Only the widget information that meets th **System capability**: SystemCapability.Ability.Form -| Name | Description | -| ----------- | ------------ | -| moduleName | Only the information about the widget whose **moduleName** is the same as the provided value is returned.| +| Name | Type | Description | +| ----------- | ---- | ------------ | +| moduleName | string | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.
If this parameter is not set, **moduleName** is not used for filtering. | ## VisibilityType diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md index 392f053b31f4fdb51033abb04a83514b8d3cfbd8..d61484f86b36bafd74ded1860272ac1a4b86089a 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -1,4 +1,4 @@ -# @ohos.app.form.formProvider +# @ohos.app.form.formProvider (formProvider) The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. @@ -31,23 +31,25 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider setFormNextRefreshTime success`); } }); } catch (error) { - console.log("error" + JSON.stringify(error)) + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -76,21 +78,23 @@ Sets the next refresh time for a widget. This API uses a promise to return the r | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log('formProvider setFormNextRefreshTime success'); + console.log(`formProvider setFormNextRefreshTime success`); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -114,25 +118,27 @@ Updates a widget. This API uses an asynchronous callback to return the result. | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj, (error, data) => { if (error) { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider updateForm success`); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -161,23 +167,25 @@ Updates a widget. This API uses a promise to return the result. | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -var formId = "12400633174999288"; -let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; +let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); try { formProvider.updateForm(formId, obj).then(() => { - console.log('formProvider updateForm success'); + console.log(`formProvider updateForm success`); }).catch((error) => { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -193,29 +201,31 @@ Obtains the application's widget information on the device. This API uses an asy | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.getFormsInfo((error, data) => { if (error) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` ## getFormsInfo @@ -231,33 +241,35 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -import formInfo from '@ohos.application.formInfo'; -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" }; try { formProvider.getFormsInfo(filter, (error, data) => { if (error) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); } }); -} catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -279,31 +291,33 @@ Obtains the application's widget information on the device. This API uses a prom | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -import formInfo from '@ohos.application.formInfo'; -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" }; try { formProvider.getFormsInfo(filter).then((data) => { console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -322,21 +336,23 @@ Requests to publish a widget carrying data to the widget host. This API uses an | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| | callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -345,16 +361,16 @@ var want = { } }; try { - let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); formProvider.requestPublishForm(want, obj, (error, data) => { if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -379,13 +395,15 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -396,15 +414,14 @@ var want = { try { formProvider.requestPublishForm(want, (error, data) => { if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } - ``` ## requestPublishForm @@ -422,7 +439,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | **Return value** @@ -434,13 +451,15 @@ Requests to publish a widget to the widget host. This API uses a promise to retu | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -452,10 +471,10 @@ try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -478,37 +497,38 @@ Checks whether a widget can be published to the widget host. This API uses an as **Example** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.isRequestPublishFormSupported((error, isSupported) => { - if (error) { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); - } else { - if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - try { - formProvider.requestPublishForm(want, (error, data) => { - if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + if (isSupported) { + var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" } - }); - } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + }; + try { + formProvider.requestPublishForm(want, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); + } catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); + } } - } - } -}); + }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -531,34 +551,33 @@ Checks whether a widget can be published to the widget host. This API uses a pro **Example** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } - } }).catch((error) => { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-appControl.md b/en/application-dev/reference/apis/js-apis-appControl.md index 1cb94f68880afc18137b22ed6f73ed3350caffb4..06b334d58cad8e7dd26a45c0344cfa48e1fdf0d6 100644 --- a/en/application-dev/reference/apis/js-apis-appControl.md +++ b/en/application-dev/reference/apis/js-apis-appControl.md @@ -1,4 +1,4 @@ -# appControl +# @ohos.bundle.appControl (appControl) The **appControl** module provides APIs for setting, obtaining, and deleting the disposed status of an application. An application in the disposed state is forbidden to run. When a user clicks the application icon on the home screen, the corresponding page is displayed based on the disposal intent. @@ -30,7 +30,7 @@ Sets the disposed status for an application. This API uses a promise to return t | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | disposedWant | Want | Yes| Disposal intent of the application.| **Return value** @@ -81,7 +81,7 @@ Sets the disposed status for an application. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | disposedWant | Want | Yes| Disposal intent of the application.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| @@ -128,7 +128,7 @@ Obtains the disposed status of an application. This API uses a promise to return | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | **Return value** @@ -177,7 +177,7 @@ Obtains the disposed status of an application. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the disposed status obtained; otherwise, **err** is an error object. | **Error codes** @@ -222,7 +222,7 @@ Deletes the disposed status for an application. This API uses a promise to retur | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | **Return value** @@ -271,7 +271,7 @@ Deletes the disposed status for an application. This API uses an asynchronous ca | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index 8c1c83988c352d24ac4bc7d64b61d53f3378156a..efba928564b2c9aa34e35b2af7485674ea99274d 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -1,4 +1,4 @@ -# @ohos.application.Ability +# @ohos.application.Ability (Ability) The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. @@ -15,7 +15,7 @@ This module provides the following common ability-related functions: ## Modules to Import ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; ``` ## Attributes @@ -47,7 +47,7 @@ Called to initialize the service logic when an ability is created. **Example** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); } @@ -67,7 +67,7 @@ Called when a **WindowStage** is created for this ability. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** @@ -111,7 +111,7 @@ Called when the **WindowStage** is restored during the migration of this ability | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** @@ -219,23 +219,24 @@ Called to save data during the ability migration preparation process. onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; -Called when the ability startup mode is set to singleton. +Called when a new Want is passed in and this UIAbility is started again. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want parameters, such as the ability name and bundle name.| - | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information, such as the ability name and bundle name.| +| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| **Example** ```ts class myAbility extends Ability { - onNewWant(want) { + onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); + console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); } } ``` @@ -388,8 +389,9 @@ Sends sequenceable data to the target ability. **Example** ```ts - import Ability from '@ohos.application.Ability'; - class MyMessageAble{ // Custom sequenceable data structure + import UIAbility from '@ohos.app.ability.UIAbility'; + + class MyMessageAble{ // Custom sequenceable data structure. name:"" str:"" num: 1 @@ -412,11 +414,11 @@ Sends sequenceable data to the target ability. }; var method = 'call_Function'; // Notification message string negotiated by the two abilities var caller; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -472,7 +474,8 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + class MyMessageAble{ name:"" str:"" @@ -496,11 +499,11 @@ Sends sequenceable data to the target ability and obtains the sequenceable data }; var method = 'call_Function'; var caller; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -543,14 +546,17 @@ Releases the caller interface of the target ability. **Example** + ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var caller; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -585,13 +591,15 @@ Registers a callback that is invoked when the stub on the target ability is disc **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var caller; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -642,7 +650,7 @@ Registers a caller notification callback, which is invoked when the target abili **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -671,7 +679,7 @@ Registers a caller notification callback, which is invoked when the target abili pdata.readSequenceable(msg); return new MyMessageAble("test1", "Callee test"); } - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -710,9 +718,11 @@ Deregisters a caller notification callback, which is invoked when the target abi **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var method = 'call_Function'; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -724,7 +734,7 @@ Deregisters a caller notification callback, which is invoked when the target abi } } ``` - + ## OnReleaseCallBack (msg: string): void; diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md index c97e344590f1bdd6b0d0242c1b61003053908e37..70d679e5f44e1089e91ff7377b687ded761e29e6 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md @@ -1,12 +1,10 @@ -# @ohos.application.AbilityConstant +# @ohos.application.AbilityConstant (AbilityConstant) -The **AbilityConstant** module provides ability launch parameters. - -The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results. +The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -21,12 +19,12 @@ import AbilityConstant from '@ohos.application.AbilityConstant'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| +| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason.| +| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit.| ## AbilityConstant.LaunchReason -Enumerates ability launch reasons. +Enumerates the initial ability launch reasons. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -41,7 +39,7 @@ Enumerates ability launch reasons. ## AbilityConstant.LastExitReason -Enumerates reasons for the last exit. +Enumerates the reasons for the last exit. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -54,7 +52,7 @@ Enumerates reasons for the last exit. ## AbilityConstant.OnContinueResult -Enumerates ability continuation results. +Enumerates the ability continuation results. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index c58eae8878a6df52715e9b4ec06738aeef34bf01..ae72afeca2e3214d00a785c0639793e8df47d715 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -1,10 +1,10 @@ -# @ohos.application.abilityDelegatorRegistry +# @ohos.application.abilityDelegatorRegistry (AbilityDelegatorRegistry) The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. > **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 supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index cd4a4db73667651bae07a865d0a088321cda0ce6..040448220bb9da59779f0d449c43a59d8ab920bd 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,10 +1,10 @@ -# @ohos.application.AbilityLifecycleCallback +# @ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback) -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. +The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. These callbacks can be used as an input parameter of [registerAbilityLifecycleCallback](js-apis-inner-application-applicationContext.md#applicationcontextregisterabilitylifecyclecallback). > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. @@ -25,9 +25,9 @@ Called when an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onWindowStageCreate @@ -40,10 +40,10 @@ Called when the window stage of an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageActive @@ -56,10 +56,10 @@ Called when the window stage of an ability gains focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageInactive @@ -72,10 +72,10 @@ Called when the window stage of an ability loses focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageDestroy @@ -88,10 +88,10 @@ Called when the window stage of an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onAbilityDestroy @@ -104,9 +104,9 @@ Called when an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityForeground @@ -119,9 +119,9 @@ Called when an ability is switched from the background to the foreground. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityBackground @@ -134,9 +134,9 @@ Called when an ability is switched from the foreground to the background. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityContinue @@ -149,64 +149,64 @@ Called when an ability is continued on another device. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| **Example** - ```ts import AbilityStage from "@ohos.application.AbilityStage"; -var lifecycleid; +var lifecycleId; export default class MyAbilityStage extends AbilityStage { onCreate() { console.log("MyAbilityStage onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + let AbilityLifecycleCallback = { + onAbilityCreate(ability) { + console.log("onAbilityCreate ability:" + JSON.stringify(ability)); }, - onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + onWindowStageCreate(ability, windowStage) { + console.log("onWindowStageCreate ability:" + JSON.stringify(ability)); + console.log("onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); }, - onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + onWindowStageActive(ability, windowStage) { + console.log("onWindowStageActive ability:" + JSON.stringify(ability)); + console.log("onWindowStageActive windowStage:" + JSON.stringify(windowStage)); }, - onWindowStageInactive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + onWindowStageInactive(ability, windowStage) { + console.log("onWindowStageInactive ability:" + JSON.stringify(ability)); + console.log("onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); }, - onWindowStageDestroy(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + onWindowStageDestroy(ability, windowStage) { + console.log("onWindowStageDestroy ability:" + JSON.stringify(ability)); + console.log("onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); }, - onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + onAbilityDestroy(ability) { + console.log("onAbilityDestroy ability:" + JSON.stringify(ability)); }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + onAbilityForeground(ability) { + console.log("onAbilityForeground ability:" + JSON.stringify(ability)); }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + onAbilityBackground(ability) { + console.log("onAbilityBackground ability:" + JSON.stringify(ability)); }, - onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + onAbilityContinue(ability) { + console.log("onAbilityContinue ability:" + JSON.stringify(ability)); } } // 1. Obtain applicationContext through the context attribute. let applicationContext = this.context.getApplicationContext(); // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); + lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); } + onDestroy() { let applicationContext = this.context.getApplicationContext(); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); }); } } diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index cf7f8da5870889e80853b396a433932afc895679..e509a1b5d13a2d0d20b8d6dee4efee9487c5ee92 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -1,16 +1,16 @@ -# @ohos.application.abilityManager +# @ohos.application.abilityManager (AbilityManager) The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. > **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 supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) instead. 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. ## Modules to Import ```ts -import AbilityManager from '@ohos.application.abilityManager' +import abilityManager from '@ohos.application.abilityManager' ``` ## AbilityState @@ -26,8 +26,8 @@ Enumerates the ability states. | INITIAL | 0 | The ability is in the initial state.| | FOREGROUND | 9 | The ability is in the foreground state. | | BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding state. | +| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | +| BACKGROUNDING | 12 | The ability is in the state of being switched to the background. | ## updateConfiguration @@ -49,13 +49,11 @@ Updates the configuration. This API uses an asynchronous callback to return the **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var config = { language: 'chinese' } -abilitymanager.updateConfiguration(config, () => { +abilityManager.updateConfiguration(config, () => { console.log('------------ updateConfiguration -----------'); }) ``` @@ -85,13 +83,11 @@ Updates the configuration. This API uses a promise to return the result. **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var config = { language: 'chinese' } -abilitymanager.updateConfiguration(config).then(() => { +abilityManager.updateConfiguration(config).then(() => { console.log('updateConfiguration success'); }).catch((err) => { console.log('updateConfiguration fail'); @@ -112,14 +108,12 @@ Obtains the ability running information. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getAbilityRunningInfos((err,data) => { +abilityManager.getAbilityRunningInfos((err,data) => { console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -138,14 +132,12 @@ Obtains the ability running information. This API uses a promise to return the r | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getAbilityRunningInfos().then((data) => { +abilityManager.getAbilityRunningInfos().then((data) => { console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) }).catch((err) => { console.log("getAbilityRunningInfos err: " + err) @@ -167,16 +159,14 @@ Obtains the extension running information. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | | upperLimit | number | Yes| Maximum number of messages that can be obtained.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var upperLimit = 0; -abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { +abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -201,16 +191,14 @@ Obtains the extension running information. This API uses a promise to return the | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var upperLimit = 0; -abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { +abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); }).catch((err) => { console.log("getAbilityRunningInfos err: " + err); @@ -229,14 +217,12 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the result. | **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getTopAbility((err,data) => { +abilityManager.getTopAbility((err,data) => { console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -253,14 +239,12 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Type | Description | | ---------------------------------------- | ------- | -| Promise\| Promise used to return the result.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the result.| **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getTopAbility().then((data) => { +abilityManager.getTopAbility().then((data) => { console.log("getTopAbility data: " + JSON.stringify(data)); }).catch((err) => { console.log("getTopAbility err: " + err); diff --git a/en/application-dev/reference/apis/js-apis-application-abilityStage.md b/en/application-dev/reference/apis/js-apis-application-abilityStage.md index 45227a89b2a6ed8d01997b8c699f8fc8c320b955..1421dcd723028b9a7f052e76e2534f1ea7c4017a 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityStage.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityStage.md @@ -1,4 +1,4 @@ -# @ohos.application.AbilityStage +# @ohos.application.AbilityStage (AbilityStage) **AbilityStage** is a runtime class for HAP files. @@ -38,21 +38,21 @@ Called when the application is created. onAcceptWant(want: Want): string; -Called when a specified ability is started. +Called when a UIAbility is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target UIAbility, such as the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| +| Type| Description| +| -------- | -------- | +| string | Returns a UIAbility ID. If this UIAbility has been started, no new instance is created and the UIAbility is placed at the top of the stack. Otherwise, a new instance is created and started.| **Example** @@ -76,9 +76,9 @@ Called when the global configuration is updated. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| **Example** @@ -100,9 +100,9 @@ Called when the system has decided to adjust the memory level. For example, this **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| **Example** @@ -118,10 +118,10 @@ Called when the system has decided to adjust the memory level. For example, this context: AbilityStageContext; -Describes the configuration information about the context. +Defines the **Context** object of **AbilityStage**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Description | -| ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Called when initialization is performed during ability startup.| +| Name | Type | Description | +| ------- | ------------------------------------------------------------ | -------------------------- | +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | **Context** object of AbilityStage.| diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md index a3f97be529cfef048393d37907a257fddf10b0bf..591f5ec77a34ef2eb36979a00b9553241b33ddb3 100644 --- a/en/application-dev/reference/apis/js-apis-application-appManager.md +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -1,4 +1,4 @@ -# @ohos.application.appManager +# @ohos.application.appManager (appManager) The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. @@ -9,7 +9,7 @@ The **appManager** module implements application management. You can use the API ## Modules to Import ```ts -import app from '@ohos.application.appManager'; +import appManager from '@ohos.application.appManager'; ``` ## appManager.isRunningInStabilityTest8+ @@ -29,9 +29,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Example** ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest((err, flag) => { - console.log('startAbility result:' + JSON.stringify(err)); + appManager.isRunningInStabilityTest((err, flag) => { + console.log('error:' + JSON.stringfy(err)); + console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); }) ``` @@ -53,11 +53,10 @@ Checks whether this application is undergoing a stability test. This API uses a **Example** ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest().then((flag) => { - console.log('success:' + JSON.stringify(flag)); + appManager.isRunningInStabilityTest().then((flag) => { + console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -79,10 +78,10 @@ Checks whether this application is running on a RAM constrained device. This API **Example** ```ts - app.isRamConstrainedDevice().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.isRamConstrainedDevice().then((data) => { + console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -103,9 +102,9 @@ Checks whether this application is running on a RAM constrained device. This API **Example** ```ts - app.isRamConstrainedDevice((err, data) => { - console.log('startAbility result failed:' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.isRamConstrainedDevice((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); }) ``` @@ -126,10 +125,10 @@ Obtains the memory size of this application. This API uses a promise to return t **Example** ```ts - app.getAppMemorySize().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.getAppMemorySize().then((data) => { + console.log('The size of app memory is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -150,9 +149,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Example** ```ts - app.getAppMemorySize((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.getAppMemorySize((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The size of app memory is:' + JSON.stringify(data)); }) ``` ## appManager.getProcessRunningInfos(deprecated) @@ -171,15 +170,15 @@ Obtains information about the running processes. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the process information.| +| Promise\> | Promise used to return the process information.| **Example** ```ts - app.getProcessRunningInfos().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.getProcessRunningInfos().then((data) => { + console.log('The process running infos is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -199,14 +198,14 @@ Obtains information about the running processes. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| +| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| **Example** ```ts - app.getProcessRunningInfos((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.getProcessRunningInfos((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The process running infos is:' + JSON.stringify(data)); }) ``` @@ -229,10 +228,10 @@ Obtains information about the running processes. This API uses a promise to retu **Example** ```ts - app.getProcessRunningInformation().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.getProcessRunningInformation().then((data) => { + console.log('The process running info is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -255,9 +254,9 @@ Obtains information about the running processes. This API uses an asynchronous c **Example** ```ts - app.getProcessRunningInformation((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.getProcessRunningInformation((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The process running info is:' + JSON.stringify(data)); }) ``` @@ -299,7 +298,7 @@ Registers an observer to listen for the state changes of all applications. console.log('------------ onProcessStateChanged -----------', processData); } } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); console.log('-------- observerCode: ---------', observerCode); ``` @@ -343,7 +342,7 @@ Registers an observer to listen for the state changes of a specified application } } var bundleNameList = ['bundleName1', 'bundleName2']; - const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); + const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver, bundleNameList); console.log('-------- observerCode: ---------', observerCode); ``` ## appManager.unregisterApplicationStateObserver8+ @@ -359,7 +358,7 @@ Deregisters the application state observer. This API uses an asynchronous callba **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observerId | number | Yes| Numeric code of the observer.| @@ -375,7 +374,7 @@ Deregisters the application state observer. This API uses an asynchronous callba console.log('------------ unregisterApplicationStateObserverCallback ------------', err); } } - app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); + appManager.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); ``` ## appManager.unregisterApplicationStateObserver8+ @@ -407,7 +406,7 @@ Deregisters the application state observer. This API uses a promise to return th ```ts var observerId = 100; - app.unregisterApplicationStateObserver(observerId) + appManager.unregisterApplicationStateObserver(observerId) .then((data) => { console.log('----------- unregisterApplicationStateObserver success ----------', data); }) @@ -420,8 +419,8 @@ Deregisters the application state observer. This API uses a promise to return th getForegroundApplications(callback: AsyncCallback\>): void; -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. - +Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). + **Required permissions**: ohos.permission.GET_RUNNING_INFO **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -432,7 +431,7 @@ Obtains applications that are running in the foreground. This API uses an asynch | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| +| callback | AsyncCallback\> | Yes| Callback used to return the application information.| **Example** @@ -444,14 +443,14 @@ Obtains applications that are running in the foreground. This API uses an asynch console.log('--------- getForegroundApplicationsCallback success ---------', data) } } - app.getForegroundApplications(getForegroundApplicationsCallback); + appManager.getForegroundApplications(getForegroundApplicationsCallback); ``` ## appManager.getForegroundApplications8+ getForegroundApplications(): Promise\>; -Obtains applications that are running in the foreground. This API uses a promise to return the result. +Obtains information about the applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -463,12 +462,12 @@ Obtains applications that are running in the foreground. This API uses a promise | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the application state data.| +| Promise\> | Promise used to return the application information.| **Example** ```ts - app.getForegroundApplications() + appManager.getForegroundApplications() .then((data) => { console.log('--------- getForegroundApplications success -------', data); }) @@ -483,7 +482,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\ Kills a process by bundle name and account ID. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -491,17 +490,17 @@ Kills a process by bundle name and account ID. This API uses a promise to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Example** ```ts var bundleName = 'bundleName'; var accountId = 0; -app.killProcessWithAccount(bundleName, accountId) +appManager.killProcessWithAccount(bundleName, accountId) .then((data) => { console.log('------------ killProcessWithAccount success ------------', data); }) @@ -521,15 +520,15 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **System API**: This is a system API and cannot be called by third-party applications. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -543,7 +542,7 @@ function killProcessWithAccountCallback(err, data) { console.log('------------- killProcessWithAccountCallback success, data: --------------', data); } } -app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); ``` ## appManager.killProcessesByBundleName8+ @@ -562,7 +561,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -576,7 +575,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); } } - app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); + appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); ``` ## appManager.killProcessesByBundleName8+ @@ -595,7 +594,7 @@ Kills a process by bundle name. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** @@ -604,10 +603,10 @@ Kills a process by bundle name. This API uses a promise to return the result. | Promise\ | Promise used to return the result.| **Example** - + ```ts - var bundleName = 'bundleName'; - app.killProcessesByBundleName(bundleName) + var bundleName = 'com.example.myapplication'; + appManager.killProcessesByBundleName(bundleName) .then((data) => { console.log('------------ killProcessesByBundleName success ------------', data); }) @@ -632,7 +631,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -646,7 +645,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); } } - app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); + appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); ``` ## appManager.clearUpApplicationData8+ @@ -665,7 +664,7 @@ Clears application data by bundle name. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** @@ -677,7 +676,7 @@ Clears application data by bundle name. This API uses a promise to return the re ```ts var bundleName = 'bundleName'; - app.clearUpApplicationData(bundleName) + appManager.clearUpApplicationData(bundleName) .then((data) => { console.log('------------ clearUpApplicationData success ------------', data); }) diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md index 1fbb65c4ae5cbe676db6d5ddad5bdacf305df5bb..81870036a845c61f852f671616f63c12f92851b8 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -1,9 +1,8 @@ -# @ohos.application.Configuration +# @ohos.application.Configuration (Configuration) The **Configuration** module defines environment change information. > **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. > This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md index 316244503def8d44c09fb10c7bbe164730239eae..dabe32b2f9d166dbce68b94c204b82f78b0090de 100644 --- a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -1,4 +1,4 @@ -# @ohos.application.ConfigurationConstant +# @ohos.application.ConfigurationConstant (ConfigurationConstant) The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. @@ -18,11 +18,11 @@ You can obtain the value of this constant by calling the **ConfigurationConstant **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| -| COLOR_MODE_DARK | 0 | Dark mode.| -| COLOR_MODE_LIGHT | 1 | Light mode.| +| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| +| COLOR_MODE_DARK | 0 | Dark mode.| +| COLOR_MODE_LIGHT | 1 | Light mode.| ## ConfigurationConstant.Direction9+ @@ -31,11 +31,11 @@ You can obtain the value of this constant by calling the **ConfigurationConstant **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| DIRECTION_NOT_SET | -1 | Unspecified direction.| -| DIRECTION_VERTICAL | 0 | Vertical direction.| -| DIRECTION_HORIZONTAL | 1 | Horizontal direction.| +| DIRECTION_NOT_SET | -1 | Unspecified direction.| +| DIRECTION_VERTICAL | 0 | Vertical direction.| +| DIRECTION_HORIZONTAL | 1 | Horizontal direction.| ## ConfigurationConstant.ScreenDensity9+ @@ -44,12 +44,12 @@ You can obtain the value of this constant by calling the **ConfigurationConstant **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| -| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| -| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| -| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| -| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| -| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| -| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| +| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| +| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| +| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| +| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| +| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| +| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| +| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index 88a5c84c617f675c93ea2f43de62625294025ca6..d42e522c14266de6ca53fff7370c68de14c34d36 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -1,4 +1,4 @@ -# @ohos.application.context +# @ohos.application.context (Context) The **Context** module provides all level-2 module APIs for developers to export. diff --git a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md index e1d2033c652d413ddac9933e32c3c53c1372f443..d4c25269235da3b95e4f230c084d92c1df047269 100644 --- a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md @@ -1,10 +1,10 @@ -# @ohos.application.EnvironmentCallback +# @ohos.application.EnvironmentCallback (EnvironmentCallback) -The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. +The **EnvironmentCallback** module provides APIs, such as **onConfigurationUpdated** and **onMemoryLevel**, for the application context to listen for system environment changes. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. @@ -25,18 +25,32 @@ Called when the system environment changes. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| -**Example** +## EnvironmentCallback.onMemoryLevel + +onMemoryLevel(level: number): void; + +Called when the system memory level changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| + +**Example** ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var callbackId; -export default class MyAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate() { console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); @@ -44,6 +58,9 @@ export default class MyAbility extends Ability { onConfigurationUpdated(config){ console.log("onConfigurationUpdated config:" + JSON.stringify(config)); }, + onMemoryLevel(level){ + console.log("onMemoryLevel level:" + level); + } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; diff --git a/en/application-dev/reference/apis/js-apis-application-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md index b1a98049c70502462a6225a63efd642c164ca60c..c1eaa2d35e90966795e4b98f4b75cffc0570e855 100644 --- a/en/application-dev/reference/apis/js-apis-application-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md @@ -1,10 +1,10 @@ -# @ohos.application.errorManager (Error Manager) +# @ohos.application.errorManager (ErrorManager) -The **errorManager** module provides APIs for registering and deregistering error observers. +The **ErrorManager** module provides APIs for registering and deregistering error observers. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```ts diff --git a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md index 055980e455acb5fd56ece9d4a1a582c7868b1646..f18b293edd8d7a4f65684bc38df4fe48498fa11b 100644 --- a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md @@ -1,6 +1,6 @@ -# @ohos.application.ExtensionAbility +# @ohos.application.ExtensionAbility (ExtensionAbility) -The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information. +The **ExtensionAbility** module manages the ExtensionAbility lifecycle and context, such as creating and destroying an ExtensionAbility, and dumping client information. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-application-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md index f0cdf74799a4373cfe61446191166a1e2ca0a014..5fbc52c95dc9e573947fb9820f00100a76a06f22 100644 --- a/en/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -1,4 +1,4 @@ -# @ohos.application.formBindingData +# @ohos.application.formBindingData (formBindingData) The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. @@ -48,16 +48,17 @@ Creates a **FormBindingData** object. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility'; -import fileio from '@ohos.fileio'; -let context=featureAbility.getContext(); -context.getOrCreateLocalDir((err,data)=>{ - let path=data+"/xxx.jpg"; - let fd = fileio.openSync(path); +import formBindingData from @ohos.application.formBindingData; +import fs from '@ohos.file.fs'; + +try { + let fd = fs.openSync('/path/to/form.png') let obj = { "temperature": "21°", - "formImages": {"image": fd} + "formImages": { "image": fd } }; - let formBindingDataObj = formBindingData.createFormBindingData(obj); -}) + formBindingData.createFormBindingData(obj); +} catch (error.code) { + console.log('catch error, error:' + JSON.stringify(error)); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formError.md b/en/application-dev/reference/apis/js-apis-application-formError.md index 7a9a6618cd4906b2a4894f8cdfd8c796beefc905..4ca6eecb8cfae8ddbad623262b8a1c7c9ff515ff 100644 --- a/en/application-dev/reference/apis/js-apis-application-formError.md +++ b/en/application-dev/reference/apis/js-apis-application-formError.md @@ -1,6 +1,6 @@ -# @ohos.application.formError +# @ohos.application.formError (formError) -The **FormError** module provides error codes for widgets. +The **formError** module provides error codes for widgets. > **NOTE** > @@ -50,5 +50,3 @@ SystemCapability.Ability.Form | ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. | | ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. | | ERR_DISTRIBUTED_SCHEDULE_FAILED9+ | 37 | The distributed scheduler failed.
**System API**: This is a system API. | - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-formExtension.md b/en/application-dev/reference/apis/js-apis-application-formExtension.md index a01e08710907030edfc7f0b1d04927282f5bc387..fcde831bc20ca03c224b977271f40b69f1ad0569 100644 --- a/en/application-dev/reference/apis/js-apis-application-formExtension.md +++ b/en/application-dev/reference/apis/js-apis-application-formExtension.md @@ -1,4 +1,4 @@ -# @ohos.application.FormExtension +# @ohos.application.FormExtension (FormExtension) The **FormExtension** module provides APIs related to Form Extension abilities. diff --git a/en/application-dev/reference/apis/js-apis-application-formHost.md b/en/application-dev/reference/apis/js-apis-application-formHost.md index 8b44dbf345b717b3cf1433392fd82907b6caab5f..11da810effa714b8aaf37e35d3c0566556281ebf 100644 --- a/en/application-dev/reference/apis/js-apis-application-formHost.md +++ b/en/application-dev/reference/apis/js-apis-application-formHost.md @@ -1,11 +1,11 @@ -# @ohos.application.formHost +# @ohos.application.formHost (formHost) -The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. +The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. > **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. -> This module is deprecated since API version 9. You are advised to use [FormHost](js-apis-app-form-formHost.md) instead. +> This module is deprecated since API version 9. You are advised to use [formHost](js-apis-app-form-formHost.md) instead. > The APIs provided by this module are system APIs. ## Modules to Import @@ -34,10 +34,12 @@ Deletes a widget. After this API is called, the application can no longer use th **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.deleteForm(formId, (error, data) => { if (error.code) { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.error('formHost deleteForm, error:' + JSON.stringify(error)); } }); ``` @@ -67,11 +69,13 @@ Deletes a widget. After this API is called, the application can no longer use th **Parameters** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.error('formHost deleteForm, error:' + JSON.stringify(error)); }); ``` @@ -95,10 +99,14 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.releaseForm(formId, (error, data) => { if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error:' + JSON.stringify(error)); + } else { + console.log('formHost releaseForm success'); } }); ``` @@ -124,10 +132,14 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.releaseForm(formId, true, (error, data) => { if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error:' + JSON.stringify(error)); + } else { + console.log('formHost releaseForm success'); } }); ``` @@ -158,11 +170,13 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error:' + JSON.stringify(error)); }); ``` @@ -186,10 +200,12 @@ Requests a widget update. This API uses an asynchronous callback to return the r **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.requestForm(formId, (error, data) => { if (error.code) { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.error('formHost requestForm, error:' + JSON.stringify(error)); } }); ``` @@ -219,11 +235,13 @@ Requests a widget update. This API uses a promise to return the result. **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.error('formHost requestForm, error:' + JSON.stringify(error)); }); ``` @@ -242,15 +260,17 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.castTempForm(formId, (error, data) => { if (error.code) { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.error('formHost castTempForm, error:' + JSON.stringify(error)); } }); ``` @@ -280,11 +300,13 @@ Converts a temporary widget to a normal one. This API uses a promise to return t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.castTempForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.error('formHost castTempForm, error:' + JSON.stringify(error)); }); ``` @@ -303,15 +325,17 @@ Instructs the widget framework to make a widget visible. After this API is calle | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyVisibleForms(formId, (error, data) => { if (error.code) { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); } }); ``` @@ -341,11 +365,13 @@ Instructs the widget framework to make a widget visible. After this API is calle **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); }); ``` @@ -364,15 +390,17 @@ Instructs the widget framework to make a widget invisible. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyInvisibleForms(formId, (error, data) => { if (error.code) { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); } }); ``` @@ -402,11 +430,13 @@ Instructs the widget framework to make a widget invisible. After this API is cal **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); }); ``` @@ -425,15 +455,17 @@ Instructs the widget framework to make a widget updatable. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.enableFormsUpdate(formId, (error, data) => { if (error.code) { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); } }); ``` @@ -463,11 +495,13 @@ Instructs the widget framework to make a widget updatable. After this API is cal **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); }); ``` @@ -486,15 +520,17 @@ Instructs the widget framework to make a widget not updatable. After this API is | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.disableFormsUpdate(formId, (error, data) => { if (error.code) { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); } }); ``` @@ -524,11 +560,13 @@ Instructs the widget framework to make a widget not updatable. After this API is **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); }); ``` @@ -544,15 +582,17 @@ Checks whether the system is ready. This API uses an asynchronous callback to re | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.isSystemReady((error, data) => { if (error.code) { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.error('formHost isSystemReady, error:' + JSON.stringify(error)); } }); ``` @@ -574,11 +614,13 @@ Checks whether the system is ready. This API uses a promise to return the result **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.error('formHost isSystemReady, error:' + JSON.stringify(error)); }); ``` @@ -596,14 +638,16 @@ Obtains the widget information provided by all applications on the device. This | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.application.formHost'; + formHost.getAllFormsInfo((error, data) => { if (error.code) { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); } else { console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); } @@ -624,15 +668,17 @@ Obtains the widget information provided by all applications on the device. This | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts + import formHost from '@ohos.application.formHost'; + formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); }); ``` @@ -650,15 +696,17 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.application.formHost'; + formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { if (error.code) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); } else { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } @@ -679,18 +727,20 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | Yes| Module name.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.application.formHost'; + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { if (error.code) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); ``` @@ -709,22 +759,24 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | No| Module name.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts + import formHost from '@ohos.application.formHost'; + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); }); ``` @@ -743,15 +795,17 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of valid widget IDs.| -| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds, (error, data) => { if (error.code) { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); } else { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); } @@ -783,11 +837,13 @@ Deletes invalid widgets from the list. This API uses a promise to return the res **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); }); ``` @@ -805,13 +861,15 @@ Obtains the widget state. This API uses an asynchronous callback to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| -| callback | AsyncCallback<[FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| +| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| **Example** ```ts -var want = { +import formHost from '@ohos.application.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -823,7 +881,7 @@ var want = { }; formHost.acquireFormState(want, (error, data) => { if (error.code) { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.error('formHost acquireFormState, error:' + JSON.stringify(error)); } else { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); } @@ -855,7 +913,9 @@ Obtains the widget state. This API uses a promise to return the result. **Example** ```ts -var want = { +import formHost from '@ohos.application.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -868,7 +928,7 @@ var want = { formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.error('formHost acquireFormState, error:' + JSON.stringify(error)); }); ``` @@ -890,6 +950,8 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to **Example** ```ts +import formHost from '@ohos.application.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -909,11 +971,13 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on("formUninstall")**.| **Example** ```ts +import formHost from '@ohos.application.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -936,15 +1000,17 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isVisible | boolean | Yes | Whether to make the widgets visible.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsVisible(formIds, true, (error, data) => { if (error.code) { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); } }); ``` @@ -975,11 +1041,13 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); }); ``` @@ -999,15 +1067,17 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { if (error.code) { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); } }); ``` @@ -1038,11 +1108,13 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); }); ``` ## shareForm9+ @@ -1051,7 +1123,7 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>) Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.REQUIRE_FORM +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Ability.Form @@ -1061,16 +1133,18 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| | deviceId | string | Yes | Remote device ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; formHost.shareForm(formId, deviceId, (error, data) => { if (error.code) { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.error('formHost shareForm, error:' + JSON.stringify(error)); } }); ``` @@ -1101,18 +1175,22 @@ Shares a specified widget with a remote device. This API uses a promise to retur **Parameters** ```ts -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.error('formHost shareForm, error:' + JSON.stringify(error)); }); ``` ## notifyFormsPrivacyProtected9+ -notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void +notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean, callback: AsyncCallback<void>): void + +Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.REQUIRE_FORM @@ -1126,10 +1204,51 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callb | deviceId | string | Yes | Remote device ID.| ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.error('formHost shareForm, error:' + JSON.stringify(error)); }); ``` + +## notifyFormsPrivacyProtected + +function notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean): Promise<void>; + +Notifies that the privacy protection status of the specified widgets changes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------- | ---- | -------------------------------- | +| formIds | Array<string> | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { + console.log('formHost notifyFormsPrivacyProtected success'); + }).catch((error) => { + console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-formInfo.md b/en/application-dev/reference/apis/js-apis-application-formInfo.md index de5bd8f6b24e7bd1f6e3fe66b4f4122c9a570d16..df591cea222b9bdbc98c4d108a4151a8aa1c69cb 100644 --- a/en/application-dev/reference/apis/js-apis-application-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-application-formInfo.md @@ -1,11 +1,11 @@ -# @ohos.application.formInfo +# @ohos.application.formInfo (formInfo) -The **FormInfo** module provides widget information and state. +The **formInfo** module provides types and enums related to the widget information and state. > **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. -> This module is deprecated since API version 9. You are advised to use [FormInfo](js-apis-app-form-formInfo.md) instead. +> This module is deprecated since API version 9. You are advised to use [formInfo](js-apis-app-form-formInfo.md) instead. ## Modules to Import @@ -21,9 +21,9 @@ Describes widget information. | Name | Type | Readable | Writable | Description | | ----------- | -------- |-------- | -------------------- | ------------------------------------------------------------ | -| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | | moduleName | string | Yes | No | Name of the module to which the widget belongs. | -| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | +| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | | name | string | Yes | No | Widget name. | | description | string | Yes | No | Description of the widget. | | type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, only JS widgets are supported.| @@ -31,11 +31,11 @@ Describes widget information. | colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | | isDefault | boolean | Yes | No | Whether the widget is the default one. | | updateEnabled | boolean | Yes | No | Whether the widget is updatable. | -| formVisibleNotify | string | Yes | No | Whether to send a notification when the widget is visible. | -| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | +| formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. | +| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | | scheduledUpdateTime | string | Yes | No | Time when the widget was updated. | | formConfigAbility | string | Yes | No | Configuration ability of the widget. | -| updateDuration | string | Yes | No | Update period of the widget.| +| updateDuration | number | Yes | No | Update period of the widget.| | defaultDimension | number | Yes | No | Default dimension of the widget. | | supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. | | customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | @@ -102,7 +102,7 @@ Enumerates the widget parameters. | HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | | ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | -| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID.
**System API**: This is a system API. | +| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID. | | BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| ## FormDimension9+ @@ -117,18 +117,7 @@ Enumerates the widget dimensions. | Dimension_2_2 9+ | 2 | 2 x 2. | | Dimension_2_4 9+ | 3 | 2 x 4. | | Dimension_4_4 9+ | 4 | 4 x 4. | -| Dimension_2_1 9+ | 5 | 2 x 1. | - -## VisibilityType - -Enumerates the visibility types of the widget. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| FORM_VISIBLE9+ | 1 | The card is visible. | -| FORM_INVISIBLE9+ | 2 | The card is invisible.| +| Dimension_2_1 9+ | 5 | 2 x 1. | ## FormInfoFilter9+ @@ -138,7 +127,7 @@ Defines the widget information filter. Only the widget information that meets th | Name | Description | | ----------- | ------------ | -| moduleName9+ | Only the information about the widget whose **moduleName** is the same as the provided value is returned.| +| moduleName9+ | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.
If this parameter is not set, **moduleName** is not used for filtering.| ## VisibilityType9+ diff --git a/en/application-dev/reference/apis/js-apis-application-formProvider.md b/en/application-dev/reference/apis/js-apis-application-formProvider.md index 05318bda39a220c15a328368fd5bf54c29f0ad05..4d604ff7295eb9903d450bc96f9c00fde253ee11 100644 --- a/en/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -1,10 +1,10 @@ -# @ohos.application.formProvider +# @ohos.application.formProvider (formProvider) The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. > **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. -> This module is deprecated since API version 9. You are advised to use [FormProvider](js-apis-app-form-formProvider.md) instead. +> This module is deprecated since API version 9. You are advised to use [formProvider](js-apis-app-form-formProvider.md) instead. ## Modules to Import @@ -31,11 +31,13 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback **Example** ```ts - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { - if (error.code) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); - } + if (error.code) { + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + } }); ``` @@ -63,11 +65,13 @@ Sets the next refresh time for a widget. This API uses a promise to return the r **Example** ```ts - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log('formProvider setFormNextRefreshTime success'); + console.log('formProvider setFormNextRefreshTime success'); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); }); ``` @@ -84,19 +88,21 @@ Updates a widget. This API uses an asynchronous callback to return the result. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | + | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj, (error, data) => { - if (error.code) { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); - } + if (error.code) { + console.log('formProvider updateForm, error:' + JSON.stringify(error)); + } }); ``` @@ -113,7 +119,7 @@ Updates a widget. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdat) | Yes | Data to be used for the update. | + | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | **Return value** @@ -125,12 +131,14 @@ Updates a widget. This API uses a promise to return the result. ```ts import formBindingData from '@ohos.application.formBindingData'; - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj).then(() => { - console.log('formProvider updateForm success'); + console.log('formProvider updateForm success'); }).catch((error) => { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log('formProvider updateForm, error:' + JSON.stringify(error)); }); ``` @@ -146,17 +154,19 @@ Obtains the application's widget information on the device. This API uses an asy | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** ```ts +import formProvider from '@ohos.app.form.formProvider'; + formProvider.getFormsInfo((error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } }); ``` ## getFormsInfo9+ @@ -172,22 +182,24 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** ```ts import formInfo from '@ohos.application.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" + // get info of forms belong to module entry. + moduleName : "entry" }; formProvider.getFormsInfo(filter, (error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } }); ``` @@ -209,20 +221,22 @@ Obtains the application's widget information on the device. This API uses a prom | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| +| Promise<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| **Example** ```ts import formInfo from '@ohos.application.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" + // get info of forms belong to module entry. + moduleName : "entry" }; formProvider.getFormsInfo(filter).then((data) => { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); }); ``` @@ -241,28 +255,29 @@ Requests to publish a widget carrying data to the widget host. This API uses an | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| +| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| | callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + import formProvider from '@ohos.app.form.formProvider'; + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.requestPublishForm(want, obj, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } }); ``` @@ -286,20 +301,22 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c **Example** ```ts - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + import formProvider from '@ohos.app.form.formProvider'; + + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; formProvider.requestPublishForm(want, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } }); ``` @@ -318,7 +335,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | +| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| **Return value** @@ -329,18 +346,20 @@ Requests to publish a widget to the widget host. This API uses a promise to retu **Example** ```ts - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + import formProvider from '@ohos.app.form.formProvider'; + + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); }); ``` @@ -368,13 +387,13 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => { console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); } else { if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; formProvider.requestPublishForm(want, (error, data) => { if (error.code) { @@ -409,13 +428,13 @@ Checks whether a widget can be published to the widget host. This API uses a pro ```ts formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { + let want = { + abilityName: "FormAbility", + parameters: { "ohos.extra.param.key.form_dimension": 2, "ohos.extra.param.key.form_name": "widget", "ohos.extra.param.key.module_name": "entry" - } + } }; formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); diff --git a/en/application-dev/reference/apis/js-apis-application-missionManager.md b/en/application-dev/reference/apis/js-apis-application-missionManager.md index c30dda422ded7148e35ebab1cc26804290bc1ea6..17de66e19334dce9663017c3df9c18b575e14bd7 100644 --- a/en/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -1,10 +1,10 @@ -# @ohos.application.missionManager +# @ohos.application.missionManager (missionManager) The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. > **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 supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -32,13 +32,13 @@ Registers a listener to observe the mission status. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Listener to register.| + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.| **Return value** | Type| Description| | -------- | -------- | - | number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| + | number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.| **Example** @@ -73,7 +73,7 @@ Deregisters a mission status listener. This API uses an asynchronous callback to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -113,7 +113,7 @@ Deregisters a mission status listener. This API uses a promise to return the res | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.| **Return value** @@ -169,7 +169,12 @@ Obtains the information about a given mission. This API uses an asynchronous cal var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { - console.log("getMissionInfo is called, error.code = " + error.code) + if (error.code) { + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("mission.missionId = " + mission.missionId); console.log("mission.runningState = " + mission.runningState); console.log("mission.lockedState = " + mission.lockedState); @@ -242,7 +247,11 @@ Obtains information about all missions. This API uses an asynchronous callback t import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); }) @@ -311,14 +320,22 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); + if (error.code) { + console.log("getMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("bundleName = " + snapshot.ability.bundleName); }) }) ``` @@ -393,14 +410,22 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { - console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); + if (error.code) { + console.log("getLowResolutionMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("bundleName = " + snapshot.ability.bundleName); }) }) ``` @@ -475,7 +500,11 @@ Locks a given mission. This API uses an asynchronous callback to return the resu import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -554,7 +583,11 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -637,7 +670,11 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -768,7 +805,11 @@ Switches a given mission to the foreground. This API uses an asynchronous callba import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -806,7 +847,11 @@ Switches a given mission to the foreground, with the startup parameters for the import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; diff --git a/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md index ba59d9a6ea78434939ee99a6e25b3c2945874532..beb8c007b0fa58bdae058ac554c96425bdf93bd5 100644 --- a/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md @@ -1,10 +1,13 @@ -# @ohos.application.ServiceExtensionAbility +# @ohos.application.ServiceExtensionAbility (ServiceExtensionAbility) The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. +> +> Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -23,9 +26,9 @@ None. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate @@ -40,9 +43,9 @@ Called when a Service Extension ability is created to initialize the service log **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -88,10 +91,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** @@ -116,15 +119,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| +| Type| Description| +| -------- | -------- | +| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| **Example** @@ -158,9 +161,9 @@ Called when this Service Extension ability is disconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -184,9 +187,9 @@ Called when this Service Extension ability is reconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -210,9 +213,9 @@ Called when the configuration of this Service Extension ability is updated. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| **Example** @@ -236,9 +239,9 @@ Dumps the client information. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-startOptions.md b/en/application-dev/reference/apis/js-apis-application-startOptions.md index 40ad2a516377faf476cfe688914afe3cd3eccb6c..7634b276495d98e18bc7ec966f3483e526dd3ba3 100644 --- a/en/application-dev/reference/apis/js-apis-application-startOptions.md +++ b/en/application-dev/reference/apis/js-apis-application-startOptions.md @@ -1,10 +1,10 @@ -# @ohos.application.StartOptions +# @ohos.application.StartOptions (StartOptions) The **StartOptions** module implements ability startup options. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index b9086a6ce6cbd42c53730baa1531255c0d383ba9..5fc9b0999940310b10bf7b4e7227d5651153eb50 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -1,10 +1,11 @@ -# @ohos.application.StaticSubscriberExtensionAbility +# @ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility) The **StaticSubscriberExtensionAbility** module provides Extension abilities for static subscribers. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -26,9 +27,10 @@ Callback of the common event of a static subscriber. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.| +| event | [CommonEventData](js-apis-commonEventManager.md#commoneventdata) | Yes| Common event of a static subscriber.| -**Example** +**Example** + ```ts var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") { diff --git a/en/application-dev/reference/apis/js-apis-application-testRunner.md b/en/application-dev/reference/apis/js-apis-application-testRunner.md index 688774a0d4b840e19e398624be41ac85c07c8f37..d2146524c0c5249374e21c95762438d35dc48c35 100644 --- a/en/application-dev/reference/apis/js-apis-application-testRunner.md +++ b/en/application-dev/reference/apis/js-apis-application-testRunner.md @@ -1,4 +1,4 @@ -# @ohos.application.testRunner +# @ohos.application.testRunner (TestRunner) The **TestRunner** module provides a test framework. You can use the APIs of this module to prepare the unit test environment and run test cases. 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 620885945b572e8129e4f8c61b156ef658a6805d..44cc01a00c5057488b45a5a6a38cc02adbf1cbc2 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -1,10 +1,10 @@ -# @ohos.application.Want +# @ohos.application.Want (Want) -Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility()** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. > **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 supported since API version 8 and deprecated since API version 9. You are advised to use [Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -18,26 +18,26 @@ import Want from '@ohos.application.Want'; | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. | -| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| bundleName | string | No | Bundle name.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| -| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | +| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | | parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit **Want** and is used to filter ability types. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). | | moduleName9+ | string | No | Module to which the ability belongs.| **Example** -- Basic usage +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). ```ts - var want = { + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", "moduleName": "entry" // moduleName is optional. }; this.context.startAbility(want, (error) => { @@ -46,13 +46,13 @@ import Want from '@ohos.application.Want'; }) ``` -- Data is transferred through user-defined fields. The following data types are supported: +- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility): * String ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForString: "str", }, @@ -61,8 +61,8 @@ import Want from '@ohos.application.Want'; * Number ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForInt: 100, keyForDouble: 99.99, @@ -72,8 +72,8 @@ import Want from '@ohos.application.Want'; * Boolean ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForBool: true, }, @@ -82,8 +82,8 @@ import Want from '@ohos.application.Want'; * Object ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForObject: { keyForObjectString: "str", @@ -97,8 +97,8 @@ import Want from '@ohos.application.Want'; * Array ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForArrayString: ["str1", "str2", "str3"], keyForArrayInt: [100, 200, 300, 400], @@ -110,16 +110,16 @@ import Want from '@ohos.application.Want'; * File descriptor (FD) ```ts import fileio from '@ohos.fileio'; - var fd; + let fd; try { fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); } catch(e) { console.log("openSync fail:" + JSON.stringify(e)); } - var want = { + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", "moduleName": "entry", // moduleName is optional. "parameters": { "keyFd":{"type":"FD", "value":fd} @@ -131,4 +131,6 @@ import Want from '@ohos.application.Want'; }) ``` +- For more details and examples, see [Want](../../application-models/want-overview.md). + diff --git a/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md index 882578cc316716db9f2f8a3c1d355e6a07b292db..bd6d74bbcbbdb4b0d29ccad209b012a11f44c9af 100644 --- a/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md @@ -1,4 +1,5 @@ -# Window Extension Ability +# @ohos.application.WindowExtensionAbility (WindowExtensionAbility) + **WindowExtensionAbility** inherits from **ExtensionAbility**. The content in a **WindowExtensionAbility** object can be displayed as an ability component in other application windows. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index f6334ff328c76de2d9be97b9ad430065819e53c9..ebf538d3b5508c1ee26aa77d4db01aa995239c3b 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -1,7 +1,6 @@ # @ohos.util.ArrayList (Linear Container ArrayList) > **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. **ArrayList** is a linear data structure that is implemented based on arrays. **ArrayList** can dynamically adjust the capacity based on project requirements. It increases the capacity by 50% each time. @@ -42,7 +41,7 @@ A constructor used to create an **ArrayList** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -77,7 +76,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -113,12 +112,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -151,7 +150,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -188,7 +187,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -230,7 +229,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -272,12 +271,12 @@ Removes an element with the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -313,7 +312,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -347,12 +346,12 @@ Removes from this container all of the elements within a range, including the el **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByRange method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -391,7 +390,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -426,7 +425,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -439,7 +438,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -481,7 +480,7 @@ comparator **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -523,12 +522,12 @@ Obtains elements within a range in this container, including the element at the **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The subArrayList method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -553,7 +552,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -587,7 +586,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -620,7 +619,7 @@ Obtains the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -653,7 +652,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -686,7 +685,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -719,7 +718,7 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -747,7 +746,7 @@ Trims the capacity of this container to its current length. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -780,7 +779,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index 94ba3b3ca01982070588760ebdd757db7ee8d13b..5552792aadadd04fca72d4fe88ffdfc8219b3ec9 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -41,8 +41,8 @@ Creates a media session. This API uses a promise to return the result. An abilit | --------------------------------- | ------------------------------------------------------------ | | Promise<[AVSession](#avsession)\> | Promise used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| -**Error codes** +**Error codes** For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -84,7 +84,6 @@ Creates a media session. This API uses an asynchronous callback to return the re | callback | AsyncCallback<[AVSession](#avsession)\> | Yes | Callback used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -129,7 +128,6 @@ Obtains the descriptors of all sessions. This API uses a promise to return the r | Promise\\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -170,7 +168,6 @@ Obtains the descriptors of all sessions. This API uses an asynchronous callback | callback | AsyncCallback\>\> | Yes | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -219,7 +216,6 @@ Creates a session controller based on the session ID. Multiple session controlle | Promise<[AVSessionController](#avsessioncontroller)\> | Promise used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -272,7 +268,6 @@ Creates a session controller based on the session ID. Multiple session controlle | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -335,7 +330,6 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | Promise | Promise used to return the result. If the cast 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| @@ -388,7 +382,6 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | callback | AsyncCallback | Yes | Callback used to return the result. If the casting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -440,7 +433,6 @@ Subscribes to session creation, session destruction, and top session change even | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes | Callback used to report the session descriptor. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -489,7 +481,6 @@ Unsubscribes from session creation, session destruction, and top session change | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **session** parameter in the callback describes a media session. The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -520,7 +511,6 @@ Subscribes to session service death events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -551,7 +541,6 @@ Unsubscribes from session service death events. | callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -589,7 +578,6 @@ Sends a system key event to the top session. This API uses a promise to return t | Promise | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -632,7 +620,6 @@ Sends a system key event to the top session. This API uses an asynchronous callb | callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -680,7 +667,6 @@ Sends a system control command to the top session. This API uses a promise to re | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -735,7 +721,6 @@ Sends a system control command to the top session. This API uses an asynchronous | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -812,7 +797,6 @@ Sets session metadata. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -862,7 +846,6 @@ Sets session metadata. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -919,7 +902,6 @@ Sets information related to the session playback state. This API uses a promise | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -961,7 +943,6 @@ Sets information related to the session playback state. This API uses an asynchr | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1010,7 +991,6 @@ Sets a launcher ability. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1028,8 +1008,8 @@ let wantAgentInfo = { wants: [ { deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", action: "action1", entities: ["entity1"], type: "MIMETYPE", @@ -1076,7 +1056,6 @@ Sets a launcher ability. This API uses an asynchronous callback to return the re | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1094,8 +1073,8 @@ let wantAgentInfo = { wants: [ { deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", action: "action1", entities: ["entity1"], type: "MIMETYPE", @@ -1143,7 +1122,6 @@ Obtains the controller corresponding to this session. This API uses a promise to | Promise<[AVSessionController](#avsessioncontroller)> | Promise used to return the session controller.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1178,7 +1156,6 @@ Obtains the controller corresponding to this session. This API uses an asynchron | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1215,7 +1192,6 @@ Obtains information about the output device for this session. This API uses a pr | Promise<[OutputDeviceInfo](#outputdeviceinfo)> | Promise used to return the output device information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1248,7 +1224,6 @@ Obtains information about the output device for this session. This API uses an a | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1283,7 +1258,6 @@ Activates this session. A session can be used only after being activated. This A | Promise | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1316,7 +1290,6 @@ Activates this session. A session can be used only after being activated. This A | callback | AsyncCallback | Yes | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1351,7 +1324,6 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | Promise | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1386,7 +1358,6 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | callback | AsyncCallback | Yes | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1421,7 +1392,6 @@ Destroys this session. This API uses a promise to return the result. | Promise | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1455,7 +1425,6 @@ Destroys this session. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1491,7 +1460,6 @@ Subscribes to playback command events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1541,7 +1509,6 @@ Subscribes to the seek event. | callback | (time: number) => void | Yes | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1573,7 +1540,6 @@ Subscribes to the event for setting the playback speed. | callback | (speed: number) => void | Yes | Callback used for subscription. The **speed** parameter in the callback indicates the playback speed. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1605,7 +1571,6 @@ Subscribes to the event for setting the loop mode. | callback | (mode: [LoopMode](#loopmode)) => void | Yes | Callback used for subscription. The **mode** parameter in the callback indicates the loop mode. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1637,7 +1602,6 @@ Subscribes to the event for favoriting a media asset. | callback | (assetId: string) => void | Yes | Callback used for subscription. The **assetId** parameter in the callback indicates the media asset ID. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1669,7 +1633,6 @@ Subscribes to the key event. | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | Yes | Callback used for subscription. The **event** parameter in the callback indicates the key event. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1701,7 +1664,6 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1733,7 +1695,6 @@ Unsubscribes from playback command events. | callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1769,7 +1730,6 @@ Unsubscribes from the seek event. | callback | (time: number) => void | No | Callback used for unsubscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1799,7 +1759,6 @@ Unsubscribes from the event for setting the playback speed. | callback | (speed: number) => void | No | Callback used for unsubscription. The **speed** parameter in the callback indicates the playback speed.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1829,7 +1788,6 @@ Unsubscribes from the event for setting loop mode. | callback | (mode: [LoopMode](#loopmode)) => void | No | Callback used for unsubscription. The **mode** parameter in the callback indicates the loop mode.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1859,7 +1817,6 @@ Unsubscribes from the event for favoriting a media asset. | callback | (assetId: string) => void | No | Callback used for unsubscription. The **assetId** parameter in the callback indicates the media asset ID.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1889,7 +1846,6 @@ Unsubscribes from the key event. | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | No | Callback used for unsubscription. The **event** parameter in the callback indicates the key event.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1919,7 +1875,6 @@ Unsubscribes from playback device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -1974,7 +1929,6 @@ Obtains the information related to the playback state. This API uses a promise t | Promise<[AVPlaybackState](#avplaybackstate)\> | Promise used to return the **AVPlaybackState** object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2007,7 +1961,6 @@ Obtains the information related to the playback state. This API uses an asynchro | callback | AsyncCallback<[AVPlaybackState](#avplaybackstate)\> | Yes | Callback used to return the **AVPlaybackState** object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2042,7 +1995,6 @@ Obtains the session metadata. This API uses a promise to return the result. | Promise<[AVMetadata](#avmetadata)\> | Promise used to return the metadata obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2075,7 +2027,6 @@ Obtains the session metadata. This API uses an asynchronous callback to return t | callback | AsyncCallback<[AVMetadata](#avmetadata)\> | Yes | Callback used to return the metadata obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2110,7 +2061,6 @@ Obtains the output device information. This API uses a promise to return the res | Promise<[OutputDeviceInfo](#outputdeviceinfo)\> | Promise used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2142,7 +2092,6 @@ Obtains the output device information. This API uses an asynchronous callback to | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2177,7 +2126,6 @@ Sends a key event to the session corresponding to this controller. This API uses | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2223,7 +2171,6 @@ Sends a key event to the session corresponding to this controller. This API uses | callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2264,7 +2211,6 @@ Obtains the **WantAgent** object saved by the application in the session. This A | Promise<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2300,7 +2246,6 @@ Obtains the **WantAgent** object saved by the application in the session. This A | callback | AsyncCallback<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2338,7 +2283,6 @@ Obtains the playback position. | number | Playback position, in milliseconds.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2367,7 +2311,6 @@ Checks whether the session is activated. This API uses a promise to return the r | Promise | Promise used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2401,7 +2344,6 @@ Checks whether the session is activated. This API uses an asynchronous callback | callback | AsyncCallback | Yes | Callback used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2437,7 +2379,6 @@ Destroys this controller. A controller can no longer be used after being destroy | Promise | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2470,7 +2411,6 @@ Destroys this controller. A controller can no longer be used after being destroy | callback | AsyncCallback | Yes | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2505,7 +2445,6 @@ Obtains valid commands supported by the session. This API uses a promise to retu | Promise\> | Promise used to return a set of valid commands.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2539,7 +2478,6 @@ Obtains valid commands supported by the session. This API uses an asynchronous c | callback | AsyncCallback\\> | Yes | Callback used to return a set of valid commands.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2581,7 +2519,6 @@ Sends a control command to the session through the controller. This API uses a p | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2630,7 +2567,6 @@ Sends a control command to the session through the controller. This API uses an | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2682,7 +2618,6 @@ Subscribes to the metadata change event. | callback | (data: [AVMetadata](#avmetadata)) => void | Yes | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2720,7 +2655,6 @@ Subscribes to the playback state change event. | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | Yes | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2757,7 +2691,6 @@ Subscribes to the session destruction event. | callback | () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2789,7 +2722,6 @@ Subscribes to the session activation state change event. | callback | (isActive: boolean) => void | Yes | Callback used for subscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the service is activated, and **false** means the opposite. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2821,7 +2753,6 @@ Subscribes to valid command changes. | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | Yes | Callback used for subscription. The **commands** parameter in the callback is a set of valid commands. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2854,7 +2785,6 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2886,7 +2816,6 @@ Unsubscribes from metadata changes. | callback | (data: [AVMetadata](#avmetadata)) => void | No | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2915,7 +2844,6 @@ Unsubscribes from playback state changes. | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | No | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2944,7 +2872,6 @@ Unsubscribes from the session destruction event. | callback | () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -2973,7 +2900,6 @@ Unsubscribes from session activation state changes. | callback | (isActive: boolean) => void | No | Callback used for unsubscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the session is activated, and **false** means the opposite.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| @@ -3002,7 +2928,6 @@ Unsubscribes from valid command changes. | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | No | Callback used for unsubscription. The **commands** parameter in the command is a set of valid commands.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message | @@ -3031,7 +2956,6 @@ Unsubscribes from output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID | Error Message | diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 49032dcbd7b58a404bd779635fc109a5f2336c38..6080d2c9bc52e30b6fa987f9cb65ea9b42a28024 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -159,12 +159,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -187,7 +187,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -205,7 +205,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; @@ -217,13 +217,13 @@ function callback(err, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -251,11 +251,11 @@ Requests a continuous task from the system. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** @@ -276,7 +276,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -297,17 +297,17 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -365,7 +365,7 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callbac Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; function callback(err, data) { @@ -376,7 +376,7 @@ function callback(err, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { backgroundTaskManager.stopBackgroundRunning(this.context, callback); } @@ -422,10 +422,10 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { console.info("Operation stopBackgroundRunning succeeded"); diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index b5c914e7725c878305ff0235a33d8d98d6c6d6e4..72e65e53e63380ef4ea0aa9b33796e236bc7ee84 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -1,11 +1,12 @@ -# Buffer +# @ohos.buffer (Buffer) -> **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. +A **Buffer** object represents a byte sequence of a fixed length. It is used to store binary data. -A **Buffer** object represents a fixed-length sequence of bytes. It is used to store binary data. +You can use the APIs provided by the Buffer module to process images and a large amount of binary data, and receive or upload files. -You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, and receive or upload 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. ## Modules to Import @@ -21,55 +22,23 @@ Enumerates the supported encoding formats of strings. | Encoding Format | Description | | ------- | -------------------- | -| ascii | ASCII format. | -| utf8 | UTF-8 | -| utf-8 | UTF-8 format.| -| utf16le | UTF-16LE format.| -| ucs2 | UTF-16LE format.| -| ucs-2 | UTF-16LE format.| -| base64 | Base64 format.| -| base64url | Base64 format.| -| latin1 | ASCII format.| -| binary | Binary format.| -| hex | Hexadecimal format.| - -## Buffer - -### Attributes - -**System capability**: SystemCapability.Utils.Lang - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Length of the buffer, in bytes.| -| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| -| byteOffset | number | Yes| No| Offset of the buffer in the memory pool.| - -**Error codes** - -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). - -| ID| Error Message| -| -------- | -------- | -| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | - -**Example** - -```ts -import buffer from '@ohos.buffer'; - -let buf = buffer.from("1236"); -console.log(JSON.stringify(buf.length)); -let arrayBuffer = buf.buffer; -console.log(JSON.stringify(new Uint8Array(arrayBuffer))); -console.log(JSON.stringify(buf.byteOffset)); -``` - -### alloc +| 'ascii' | ASCII format, which is case insensitive.| +| 'utf8' | UTF-8 format, which is case insensitive.| +| 'utf-8' | UTF-8 format, which is case insensitive.| +| 'utf16le' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs2' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs-2' | UTF-16 little-endian format, which is case insensitive.| +| 'base64' | Base64 format, which is case insensitive.| +| 'base64url' | Base64 format, which is case insensitive.| +| 'latin1' | ASCII format, which is case insensitive.| +| 'binary' | Binary format, which is case insensitive.| +| 'hex' | Hexadecimal format, which is case insensitive.| + +## buffer.alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer -Allocates and initializes a **Buffer** instance of the specified size. +Creates and initializes a **Buffer** instance of the specified length. **System capability**: SystemCapability.Utils.Lang @@ -77,8 +46,8 @@ Allocates and initializes a **Buffer** instance of the specified size. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| -| fill | string \| Buffer \| number | No| Pre-filled value. The default value is **0**.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| +| fill | string \| Buffer \| number | No| Value to be filled in the buffer. The default value is **0**.| | encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.| **Return value** @@ -97,12 +66,12 @@ let buf2 = buffer.alloc(5, 'a'); let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); ``` -### allocUninitializedFromPool +## buffer.allocUninitializedFromPool allocUninitializedFromPool(size: number): Buffer -Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it. -To initialize the **Buffer** instance, call **fill()**. +Creates a **Buffer** instance of the specified size from the buffer pool, without initializing it. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -110,7 +79,7 @@ To initialize the **Buffer** instance, call **fill()**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -127,11 +96,12 @@ let buf = buffer.allocUninitializedFromPool(10); buf.fill(0); ``` -### allocUninitialized +## buffer.allocUninitialized allocUninitialized(size: number): Buffer -Allocates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +Creates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -139,7 +109,7 @@ Allocates a **Buffer** instance of the specified size, without initializing it. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes|Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes|Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -156,7 +126,7 @@ let buf = buffer.allocUninitialized(10); buf.fill(0); ``` -### byteLength +## buffer.byteLength byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number @@ -169,7 +139,7 @@ Obtains the number of bytes of a string based on the encoding format. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format of the string. The default value is **utf-8**.| **Return value** @@ -187,7 +157,7 @@ console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8') // Print: ½ + ¼ = ¾: 9 characters, 12 bytes ``` -### compare +## buffer.compare compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1 @@ -221,11 +191,11 @@ let res = buf1.compare(buf2); console.log(Number(res).toString()); // Print 1. ``` -### concat +## buffer.concat concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer -Concatenates an array of **Buffer** instances into a new instance of the specified length. +Concatenates an array of **Buffer** instances of the specified length into a new instance. **System capability**: SystemCapability.Utils.Lang @@ -234,7 +204,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.| -| totalLength | number | No| Total length of the new **Buffer** instance, in bytes.| +| totalLength | number | No| Total length of bytes to be copied.| **Return value** @@ -244,7 +214,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -261,7 +231,7 @@ let buf = buffer.concat([buf1, buf2]); console.log(buf.toString('hex')); // 3132333461626364 ``` -### from +## buffer.from from(array: number[]): Buffer; @@ -290,11 +260,11 @@ let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); console.log(buf.toString('hex')); // 627566666572 ``` -### from +## buffer.from from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer -Creates a **Buffer** instance that shares memory with the specified array of **Buffer** instances. +Creates a **Buffer** instance of the specified length that shares memory with **arrayBuffer**. **System capability**: SystemCapability.Utils.Lang @@ -314,7 +284,7 @@ Creates a **Buffer** instance that shares memory with the specified array of **B **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -329,7 +299,7 @@ let ab = new ArrayBuffer(10); let buf = buffer.from(ab, 0, 2); ``` -### from +## buffer.from from(buffer: Buffer | Uint8Array): Buffer @@ -341,7 +311,7 @@ Creates a **Buffer** instance with the copy of another instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy. | +| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy.| **Return value** @@ -358,7 +328,7 @@ let buf1 = buffer.from('buffer'); let buf2 = buffer.from(buf1); ``` -### from +## buffer.from from(object: Object, offsetOrEncoding: number | string, length: number): Buffer @@ -385,10 +355,10 @@ Creates a **Buffer** instance based on the specified object. ```ts import buffer from '@ohos.buffer'; -let buf = buffer.from(new String('this is a test')); +let buf = buffer.from(new String('this is a test'), 'utf8', 14); ``` -### from +## buffer.from from(string: String, encoding?: BufferEncoding): Buffer @@ -418,11 +388,11 @@ let buf1 = buffer.from('this is a test'); let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); console.log (buf1.toString()); // Print: this is a test -console.log(buf2.toString()); +console.log (buf2.toString()); // print: this is a test ``` -### isBuffer +## buffer.isBuffer isBuffer(obj: Object): boolean @@ -454,7 +424,7 @@ buffer.isBuffer([]); // false buffer.isBuffer(new Uint8Array(1024)); // false ``` -### isEncoding +## buffer.isEncoding isEncoding(encoding: string): boolean @@ -485,6 +455,70 @@ console.log(buffer.isEncoding('utf/8').toString()); // Print: false console.log(buffer.isEncoding('').toString()); // Print: false ``` +## buffer.transcode + +transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer + +Transcodes the given **Buffer** or **Uint8Array** object from one encoding format to another. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | Buffer \| Uint8Array | Yes| Instance to encode.| +| fromEnc | string | Yes| Current encoding format.| +| toEnc | string | Yes| Target encoding format.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | New **Buffer** instance in the target encoding format.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(50); +let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); +console.log(newBuf.toString('ascii')); +``` + +## Buffer + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Length of the **Buffer** instance, in bytes.| +| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| +| byteOffset | number | Yes| No| Offset of the **Buffer** instance in the memory pool.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from("1236"); +console.log(JSON.stringify(buf.length)); +let arrayBuffer = buf.buffer; +console.log(JSON.stringify(new Uint8Array(arrayBuffer))); +console.log(JSON.stringify(buf.byteOffset)); +``` + ### compare compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 @@ -507,7 +541,15 @@ Compares this **Buffer** instance with another instance. | Type| Description| | -------- | -------- | -| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted. | +| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[targetStart/targetEnd/sourceStart/sourceEnd]" is out of range. | **Example** @@ -547,7 +589,7 @@ Copies data at the specified position in this **Buffer** instance to the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -578,6 +620,13 @@ Creates and returns an iterator that contains key-value pairs of this **Buffer** **System capability**: SystemCapability.Utils.Lang +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Key of the iterator.| +| number | Value of the iterator.| + **Example** ```ts @@ -647,7 +696,7 @@ Fills this **Buffer** instance at the specified position. By default, data is fi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -739,7 +788,7 @@ Creates and returns an iterator that contains the keys of this **Buffer** instan | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator.| +| IterableIterator<number> | Iterator created.| **Example** @@ -789,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 signed, big-endian 64-bit integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -807,7 +856,7 @@ Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at t **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -848,7 +897,7 @@ Reads a signed, little-endian 64-bit Big integer from this **Buffer** instance a **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -889,7 +938,7 @@ Reads an unsigned, big-endian 64-bit Big integer from this **Buffer** instance a **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -930,7 +979,7 @@ Reads an unsigned, little-endian 64-bit Big integer from this **Buffer** instanc **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -971,7 +1020,7 @@ Reads a big-endian double-precision floating-point number from this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1011,7 +1060,7 @@ Reads a little-endian double-precision floating-point number from this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1051,7 +1100,7 @@ Reads a big-endian single-precision floating-point number from this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1091,7 +1140,7 @@ Reads a little-endian single-precision floating-point number from this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1131,7 +1180,7 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1172,7 +1221,7 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1212,7 +1261,7 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1252,7 +1301,7 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1292,7 +1341,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1334,7 +1383,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1378,7 +1427,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1419,7 +1468,7 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1461,7 +1510,7 @@ Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1503,7 +1552,7 @@ Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1545,7 +1594,7 @@ Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1586,7 +1635,7 @@ Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1628,7 +1677,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1670,7 +1719,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1741,7 +1790,7 @@ Interprets this **Buffer** instance as an array of unsigned 16-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1776,7 +1825,7 @@ Interprets this **Buffer** instance as an array of unsigned 32-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1811,7 +1860,7 @@ Interprets this **Buffer** instance as an array of unsigned 64-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1901,7 +1950,7 @@ Creates and returns an iterator that contains the values of this **Buffer** inst | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator created.| +| IterableIterator<number> | Iterator.| **Example** @@ -1940,7 +1989,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1984,7 +2033,7 @@ Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2023,7 +2072,7 @@ Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2062,7 +2111,7 @@ Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2101,7 +2150,7 @@ Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2140,7 +2189,7 @@ Writes a big-endian double-precision floating-point number to this **Buffer** in **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2179,7 +2228,7 @@ Writes a little-endian double-precision floating-point number to this **Buffer** **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2218,7 +2267,7 @@ Writes a big-endian single-precision floating-point number to this **Buffer** in **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2258,7 +2307,7 @@ Writes a little-endian single-precision floating-point number to this **Buffer** **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2297,7 +2346,7 @@ Writes a signed 8-bit integer to this **Buffer** instance at the specified offse **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2338,7 +2387,7 @@ Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the sp **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2378,7 +2427,7 @@ Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2417,7 +2466,7 @@ Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the sp **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2457,7 +2506,7 @@ Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2497,7 +2546,7 @@ Writes a big-endian signed value of the specified length to this **Buffer** inst **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2538,7 +2587,7 @@ Writes a little-endian signed value of the specified length to this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2577,7 +2626,7 @@ Writes an unsigned 8-bit integer to this **Buffer** instance at the specified of **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2619,7 +2668,7 @@ Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2659,7 +2708,7 @@ Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2699,7 +2748,7 @@ Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2738,7 +2787,7 @@ Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2778,7 +2827,7 @@ Writes an unsigned big-endian value of the specified length to this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2818,7 +2867,7 @@ Writes an unsigned little-endian value of the specified length to this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2833,38 +2882,6 @@ let buf = buffer.allocUninitializedFromPool(6); buf.writeUIntLE(0x1234567890ab, 0, 6); ``` -### transcode - -transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer - -Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| source | Buffer \| Uint8Array | Yes| Instance to transcode. | -| fromEnc | string | Yes| Current encoding format.| -| toEnc | string | Yes| Target encoding format.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Buffer | New **Buffer** instance in the target encoding format.| - -**Example** - -```ts -import buffer from '@ohos.buffer'; - -let buf = buffer.alloc(50); -let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); -console.log(newBuf.toString('ascii')); -``` - ## Blob ### Attributes @@ -2941,7 +2958,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc **Return value** | Type| Description| | -------- | -------- | -| Blob | **Blob** instance created. | +| Blob | New **Blob** instance created.| **Example** ```ts @@ -2954,7 +2971,7 @@ let blob3 = blob.slice(0, 2, "MIME"); text(): Promise<string> -Returns text in UTF-8 format. +Returns text in UTF-8 format. This API uses a promise to return the result. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 315e7c0f045ba3b26520ed2a69f41f242872b8e6..cc6e202d2d30e486563f3ed1f1f842f5d15a5a90 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated). > **NOTE** > @@ -12,32 +12,32 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| name | string | Yes | No | Ability name. | -| label | string | Yes | No | Ability name visible to users. | -| description | string | Yes | No | Ability description. | -| icon | string | Yes | No | Index of the ability icon resource file. | -| descriptionId | number | Yes | No | Ability description ID. | -| iconId | number | Yes | No | Ability icon ID. | -| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | -| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| -| targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| -| backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | -| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| -| type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | -| orientation | [DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | -| launchMode | [LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | -| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| -| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | -| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | -| readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| -| writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing [GET_ABILITY_INFO_WITH_APPLICATION](js-apis-Bundle.md).| -| uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| -| labelId | number | Yes | No | Ability label ID. | -| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| -| metadata8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| -| enabled8+ | boolean | Yes | No | Whether the ability is enabled. | +| Name | Type | Readable| Writable| Description | +| --------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | No | Bundle name. | +| name | string | Yes | No | Ability name. | +| label | string | Yes | No | Ability name visible to users. | +| description | string | Yes | No | Ability description. | +| icon | string | Yes | No | Index of the ability icon resource file. | +| descriptionId | number | Yes | No | ID of the ability description. | +| iconId | number | Yes | No | ID of the ability icon. | +| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | +| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used. | +| targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| +| backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | +| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | +| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| +| type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | +| orientation | [DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | +| launchMode | [LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing in GET_ABILITY_INFO_WITH_PERMISSION to [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated).| +| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | +| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | +| readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model. | +| writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model. | +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing in GET_ABILITY_INFO_WITH_APPLICATION to [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated).| +| uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| +| labelId | number | Yes | No | ID of the ability label. | +| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| +| metadata8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing in GET_ABILITY_INFO_WITH_METADATA to [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated).| +| enabled8+ | boolean | Yes | No | Whether the ability is enabled. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index c1667a66eb011d24a1b7ce79061eab0f454604a3..89444bc41bf2f3d55bf71c18b4c59c497dc37c20 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,6 +1,6 @@ # ApplicationInfo -The **ApplicationInfo** module provides application information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **ApplicationInfo** module provides application information. Unless otherwise specified, the information is obtained through [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated). > **NOTE** > @@ -16,21 +16,21 @@ The **ApplicationInfo** module provides application information. Unless otherwis |----------------------------|------------------------------------------------------------------------|-----|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | name | string | Yes | No | Application name. | | description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | +| descriptionId | number | Yes | No | ID of the application description. | | systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | | label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | +| labelId | string | Yes | No | ID of the application label. | | icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | +| iconId | string | Yes | No | ID of the application icon. | | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | -| supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units. | +| supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to telematics devices. | | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_PERMISSION](js-apis-Bundle.md). | +| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing in GET_APPLICATION_INFO_WITH_PERMISSION to [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated). | | moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | | entryDir | string | Yes | No | Path for storing application files. | | codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_METADATA](js-apis-Bundle.md). | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing in GET_APPLICATION_INFO_WITH_METADATA to [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated). | | removable8+ | boolean | Yes | No | Whether the application is removable. | | accessTokenId8+ | number | Yes | No | Access token ID of the application. | | uid8+ | number | Yes | No | UID of the application. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index c14419e736e1c2142fb47157826c42fb0d5cff34..16e4d3105d118613d1720dd2d0a8e4545e5c0344 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,6 +1,6 @@ # BundleInfo -The **BundleInfo** module provides bundle information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **BundleInfo** module defines the bundle information, which can be obtained through [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated). > **NOTE** > @@ -10,33 +10,33 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie > This API is deprecated since API version 9. You are advised to use [bundleManager-BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. -**System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type | Readable| Writable| Description | -| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Bundle name. | -| type | string | Yes | No | Bundle type. | -| appId | string | Yes | No | ID of the application to which the bundle belongs. | -| uid | number | Yes | No | UID of the application to which the bundle belongs. | -| installTime | number | Yes | No | Time when the HAP file was installed. | -| updateTime | number | Yes | No | Time when the HAP file was updated. | -| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | -| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| -| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetaildeprecated)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | -| versionName | string | Yes | No | Version description of the bundle. | -| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | -| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | -| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | -| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | + **System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Bundle name. | +| type | string | Yes | No | Bundle type. | +| appId | string | Yes | No | ID of the application to which the bundle belongs. | +| uid | number | Yes | No | UID of the application to which the bundle belongs. | +| installTime | number | Yes | No | Time when the HAP file was installed. | +| updateTime | number | Yes | No | Time when the HAP file was updated. | +| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | +| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing in GET_BUNDLE_WITH_ABILITIES to [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated).| +| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing in GET_BUNDLE_WITH_REQUESTED_PERMISSION to [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated).| +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetaildeprecated)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing in GET_BUNDLE_WITH_REQUESTED_PERMISSION to [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated).| +| vendor | string | Yes | No | Vendor of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | +| versionName | string | Yes | No | Version description of the bundle. | +| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | +| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | +| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | +| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index 0570453b5cb9c1bfa6a1e0f0acb9dda16562005e..7523cde56562a53a6129d810dff30ba95a718a64 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -8,7 +8,7 @@ The **BundleInstaller** module provides APIs for you to install, uninstall, and ## BundleInstaller.install(deprecated) -> This API is deprecated since API version 9. You are advised to use [install](js-apis-installer.md) instead. +> This API is deprecated since API version 9. You are advised to use [@ohos.bundle.installer.install](js-apis-installer.md) instead. install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; @@ -26,10 +26,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFilePaths | Array<string> | Yes | Sandbox path where the HAP files of the bundle are stored. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](#obtaining-the-sandbox-path).| -| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle installation. | +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFilePaths | Array<string> | Yes | Sandbox path where the HAP files of the bundle are stored. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](#obtaining-the-sandbox-path).| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle installation. | | callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status. | **Example** @@ -43,7 +43,7 @@ let installParam = { installFlag: 1, }; -bundle.getBundleInstaller().then(installer=>{ +bundle.getBundleInstaller().then(installer => { installer.install(hapFilePaths, installParam, err => { if (err) { console.error('install failed:' + JSON.stringify(err)); @@ -76,10 +76,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | -| bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle uninstall. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle uninstall. | | callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status.| **Example** @@ -93,7 +93,7 @@ let installParam = { installFlag: 1, }; -bundle.getBundleInstaller().then(installer=>{ +bundle.getBundleInstaller().then(installer => { installer.uninstall(bundleName, installParam, err => { if (err) { console.error('uninstall failed:' + JSON.stringify(err)); @@ -125,10 +125,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | -| bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle recovery. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle recovery. | | callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the recovery status.| **Example** @@ -143,7 +143,7 @@ let installParam = { installFlag: 1, }; -bundle.getBundleInstaller().then(installer=>{ +bundle.getBundleInstaller().then(installer => { installer.recover(bundleName, installParam, err => { if (err) { console.error('recover failed:' + JSON.stringify(err)); @@ -166,9 +166,9 @@ Describes the parameters required for bundle installation, recovery, or uninstal | Name | Type | Readable| Writable| Description | | ----------- | ------- | ---- | ---- | ------------------ | -| userId | number | Yes | No | User ID. | -| installFlag | number | Yes | No | Installation flag. | -| isKeepData | boolean | Yes | No | Whether data is kept.| +| userId | number | Yes | Yes | User ID. The default value is the user ID of the caller.| +| installFlag | number | Yes | Yes | Installation flag.
**1** (default): overwrite installation.
**16**: installation-free.| +| isKeepData | boolean | Yes | Yes | Whether data is kept. The default value is **false**.| ## InstallStatus(deprecated) @@ -180,17 +180,17 @@ Describes the bundle installation or uninstall status. | Name | Type | Readable| Writable| Description | | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | -| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. | -| statusMessage | string | Yes | No | Installation or uninstall status message.| +| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. The value must be defined in [InstallErrorCode](js-apis-Bundle.md#installerrorcode). | +| statusMessage | string | Yes | No | Installation or uninstall status message.
**SUCCESS**: install_succeed
**STATUS_INSTALL_FAILURE**: Installation failed (no installation file exists).
**STATUS_INSTALL_FAILURE_ABORTED**: Installation aborted.
**STATUS_INSTALL_FAILURE_INVALID**: Invalid installation parameter.
**STATUS_INSTALL_FAILURE_CONFLICT**: Installation conflict. (The basic information of the application to update is inconsistent with that of the existing application.)
**STATUS_INSTALL_FAILURE_STORAGE**: Failed to store the bundle information.
**STATUS_INSTALL_FAILURE_INCOMPATIBLE**: Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)
**STATUS_UNINSTALL_FAILURE**: Uninstallation failed. (The application to be uninstalled is not found.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation aborted. (This error code is not in use.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation conflict. (Failed to uninstall a system application or end the application process.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT**: Installation failed. (Download timed out.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED**: Installation failed. (Download failed.)
**STATUS_RECOVER_FAILURE_INVALID**: Failed to restore the pre-installed application.
**STATUS_ABILITY_NOT_FOUND**: Ability not found.
**STATUS_BMS_SERVICE_ERROR**: BMS service error.
**STATUS_FAILED_NO_SPACE_LEFT**: Insufficient device space.
**STATUS_GRANT_REQUEST_PERMISSIONS_FAILED**: Application authorization failed.
**STATUS_INSTALL_PERMISSION_DENIED**: No installation permission.
**STATUS_UNINSTALL_PERMISSION_DENIED**: No uninstallation permission. | ## Obtaining the Sandbox Path -For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the sage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. +For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the stage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. **Example** ``` ts // Stage model -import Ability from '@ohos.application.Ability'; -class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; +export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { let context = this.context; let pathDir = context.filesDir; diff --git a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index b20de58d074a83dea5cb0992e21087ae64b990bb..96bdaca69234ba8f22a69eb0dbbde6824f991b4d 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -17,7 +17,7 @@ Describes the element name information, which identifies the basic information a | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | | deviceId | string | Yes | Yes | Device ID. | -| bundleName | string | Yes | Yes | Bundle name of the application. | -| abilityName | string | Yes | Yes | Name of the ability. | +| bundleName | string | Yes | Yes | Bundle name. | +| abilityName | string | Yes | Yes | Ability name. | | uri | string | Yes | Yes | Resource ID. | | shortName | string | Yes | Yes | Short name of the ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index 5540aa2bc56b9f8e34fda11d11048b8177816b95..2b3f7eede2c099cd94f2a08bbba8bbc50d67e782 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -1,6 +1,6 @@ # HapModuleInfo -The **HapModuleInfo** module provides information about an HAP module. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **HapModuleInfo** module provides information about an HAP module. Unless otherwise specified, the information is obtained through [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated). > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md index 7df2416aa44dd60847a918fb982807cfc27fd058..2ba6d913831b33b67834fa24aa1c4307259019d7 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @@ -8,7 +8,7 @@ The **LauncherAbilityInfo** module provides information about the launcher abili ## LauncherAbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -18,7 +18,7 @@ The **LauncherAbilityInfo** module provides information about the launcher abili | --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.| | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. | -| labelId | number | Yes | No | Label ID of the launcher ability. | -| iconId | number | Yes | No | Icon ID of the launcher ability. | -| userId | number | Yes | No | User ID of the launcher ability. | +| labelId | number | Yes | No | ID of the launcher ability label. | +| iconId | number | Yes | No | ID of the launcher ability icon. | +| userId | number | Yes | No | ID of the launcher ability user. | | installTime | number | Yes | No | Time when the launcher ability is installed. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 18707feeb05902b5740b00544b3a23a43c09acce..be4782ca7915986bbf60cce82edd41fa924b3bbd 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -10,6 +10,7 @@ The **ModuleInfo** module provides module information of an application. > This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework + | Name | Type | Readable| Writable| Description | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | Yes | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md index ded02c772794179d9e8276292ab1be939a208d8f..b99bd49d939b65315f9cc8e983e5ffe4641fe1a3 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -18,5 +18,5 @@ The **PermissionDef** module provides permission details defined in the configur | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | | grantMode | number | Yes | No | Grant mode of the permission. The value **0** means that the system automatically grants the permission after the application installation, and **1** means that the application needs to dynamically request the permission from the user.| -| labelId | number | Yes | No | Label ID of the permission. | -| descriptionId | number | Yes | No | Description ID of the permission. | +| labelId | number | Yes | No | ID of the permission label. | +| descriptionId | number | Yes | No | ID of the permission description. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index 1a603da33b3403dafbac79e1bfcd31c5dde9896c..2cec8a9859984bb26d38e809b8bc0c8dbae8ff74 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -10,9 +10,9 @@ The **shortcutInfo** module defines shortcut information configured in the confi > This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework - **System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. | Name | Type | Readable| Writable| Description | | ------------------------- | ------ | ---- | ---- | -------------------- | @@ -23,13 +23,12 @@ The **shortcutInfo** module defines shortcut information configured in the confi > This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. - - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | | id | string | Yes | No | ID of the application to which the shortcut belongs. | -| bundleName | string | Yes | No | Name of the bundle that contains the shortcut. | +| bundleName | string | Yes | No | Name of the bundle that contains the shortcut.| | hostAbility | string | Yes | No | Local ability information of the shortcut. | | icon | string | Yes | No | Icon of the shortcut. | | iconId8+ | number | Yes | No | Icon ID of the shortcut. | @@ -40,5 +39,3 @@ The **shortcutInfo** module defines shortcut information configured in the confi | isStatic | boolean | Yes | No | Whether the shortcut is static. | | isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut.| | isEnabled | boolean | Yes | No | Whether the shortcut is enabled. | - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index f95125fb1c7228f9eade37f423b624c3289c0e34..47646ca01faf5e6915e3d4ecc42e6596697f79bf 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -19,3 +19,4 @@ The **RemoteAbilityInfo** module provides information about a remote ability. | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name information of the ability. | | label | string | Yes | No | Ability name. | | icon | string | Yes | No | Icon of the ability.| + diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md index 71f2ee6483c12ab65106208f58c902d0d04fa630..cacab28b20157441ee4f64bc69261c7f37f0809f 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [GET_ABILITY_INFO_DEFAULT](js-apis-bundleManager.md). +The **AbilityInfo** module defines the ability information. A system application can obtain the ability information through [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo). The input parameter [abilityFlags](js-apis-bundleManager.md#abilityflag) specifies the information to be contained in the returned [AbilityInfo](js-apis-bundleManager-abilityInfo.md) object. > **NOTE** > @@ -8,31 +8,31 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi ## AbilityInfo - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | -| --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | +| --------------------- | -------------------------------------------------------- | ---- | ---- | ------------------------------------------ | +| bundleName | string | Yes | No | Bundle name. | +| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | | name | string | Yes | No | Ability name. | | label | string | Yes | No | Ability name visible to users. | -| labelId | number | Yes | No | ID of the ability label. | +| labelId | number | Yes | No | ID of the ability label. | | description | string | Yes | No | Ability description. | | descriptionId | number | Yes | No | ID of the ability description. | | icon | string | Yes | No | Index of the ability icon resource file. | | iconId | number | Yes | No | ID of the ability icon. | | process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| | isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | -| type | [AbilityType](js-apis-bundleManager.md#abilitytype) | Yes | No | Ability type.
This attribute can be used only in the FA model. | +| type | [AbilityType](js-apis-bundleManager.md#abilitytype) | Yes | No | Ability type.
This attribute can be used only in the FA model.| | orientation | [DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | No | Ability display orientation. | | launchType | [LaunchType](js-apis-bundleManager.md#launchtype) | Yes | No | Ability launch mode. | -| permissions | Array\ | Yes | No | Permissions required for other bundles to call the ability. The information is obtained by using **GET_ABILITY_INFO_WITH_PERMISSION**.| +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability. The permissions can be obtained by passing in **GET_ABILITY_INFO_WITH_PERMISSION** to the **abilityFlags** parameter of [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo).| | readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| | writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| | uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| | deviceTypes | Array\ | Yes | No | Device types supported by the ability. | -| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information is obtained by using **GET_ABILITY_INFO_WITH_APPLICATION**.| -| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. The information is obtained by using **GET_ABILITY_INFO_WITH_METADATA**.| +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information can be obtained by passing in **GET_ABILITY_INFO_WITH_APPLICATION** to the **abilityFlags** parameter of [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo).| +| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. The information can be obtained by passing in **GET_ABILITY_INFO_WITH_METADATA** to the **abilityFlags** parameter of [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo).| | enabled | boolean | Yes | No | Whether the ability is enabled. | | supportWindowModes | Array\<[SupportWindowMode](js-apis-bundleManager.md#supportwindowmode)> | Yes | No | Window modes supported by the ability. | | windowSize|[WindowSize](#windowsize) | Yes | No | Window size.| @@ -41,7 +41,7 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi Describes the window size. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | -------------------| ------- | ---- | ---- | ---------------------------------- | @@ -50,4 +50,4 @@ Describes the window size. | maxWindowWidth | number | Yes | No | Maximum width of the window in free window mode. The unit is vp.| | minWindowWidth | number | Yes | No | Minimum width of the window in free window mode. The unit is vp.| | maxWindowHeight | number | Yes | No | Maximum height of the window in free window mode. The unit is vp.| -| minWindowHeight | number | Yes | No | Maximum height of the window in free window mode. The unit is vp.| +| minWindowHeight | number | Yes | No | Minimum height of the window in free window mode. The unit is vp.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md index d4c0b4f4c2bc803e04ee8d88416aed8351c5c86d..2537274b8d5bd50d6c47258be2770bd5d51a9733 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @@ -1,6 +1,6 @@ # ApplicationInfo -The **ApplicationInfo** module provides information about an application. Unless otherwise specified, the information is obtained through [GET_APPLICATION_INFO_DEFAULT](js-apis-bundleManager.md). +The **ApplicationInfo** module defines the application information. A system application can obtain its own or others' application information through [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo). The input parameter [appFlags](js-apis-bundleManager.md#applicationflag) specifies the information to be contained in the returned [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) object. > **NOTE** > @@ -9,21 +9,21 @@ The **ApplicationInfo** module provides information about an application. Unless ## ApplicationInfo **System capability**: SystemCapability.BundleManager.BundleFramework.Core + | Name | Type | Readable| Writable| Description | | -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Application name. | | description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | ID of the application description. | +| descriptionId | number | Yes | No | ID of the application description. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | | label | string | Yes | No | Application label. | -| labelId | number | Yes | No | ID of the application label. | +| labelId | number | Yes | No | ID of the application label. | | icon | string | Yes | No | Application icon. | -| iconId | number | Yes | No | ID of the application icon. | +| iconId | number | Yes | No | ID of the application icon. | | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application. The information is obtained by using **GET_APPLICATION_INFO_WITH_PERMISSION**.| -| entryDir | string | Yes | No | Path for storing application files. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application. The permissions can be obtained by passing in **GET_APPLICATION_INFO_WITH_PERMISSION** to the **appFlags** parameter of [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo).| | codePath | string | Yes | No | Installation directory of the application. | -| metadata | Map\> | Yes | No | Metadata of the application. The information is obtained by using **GET_APPLICATION_INFO_WITH_METADATA**.| +| metadata | Map\> | Yes | No | Metadata of the application. The information can be obtained by passing in **GET_APPLICATION_INFO_WITH_METADATA** to the **appFlags** parameter of [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo).| | removable | boolean | Yes | No | Whether the application is removable. | | accessTokenId | number | Yes | No | Access token ID of the application. | | uid | number | Yes | No | UID of the application. | @@ -32,3 +32,4 @@ The **ApplicationInfo** module provides information about an application. Unless | descriptionResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Description resource of the application. | | appDistributionType | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**. | | appProvisionType | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**. | +| systemApp | boolean | Yes | No | Whether the application is a system application. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md index 0f54e790c363ff484005ea27424180227a49a5a0..8e6821b79eb36a6bd93dd9aed2b9016a3029dad2 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md @@ -1,28 +1,30 @@ # BundleInfo -The **BundleInfo** module provides information about a bundle. Unless otherwise specified, the information is obtained through [GET_BUNDLE_INFO_DEFAULT](js-apis-bundle-bundleManager). +The **BundleInfo** module defines the bundle information. A system application can obtain its own or others' bundle information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own bundle information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). The input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) specifies the information to be contained in the returned [BundleInfo](js-apis-bundleManager-bundleInfo.md) object. > **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. + + ## BundleInfo - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Bundle name. | | vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | | versionName | string | Yes | No | Version description of the bundle. | | minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | | targetVersion | number | Yes | No | Target API version required for running the bundle. | -| appInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information is obtained by using **GET_BUNDLE_INFO_WITH_APPLICATION**. | -| hapModulesInfo | Array\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | No | Module configuration information. The information is obtained by using **GET_BUNDLE_INFO_WITH_HAP_MODULE**. | -| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system. The information is obtained by using **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION**.| -| permissionGrantStates | Array\<[PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate)> | Yes | No | Permission grant state. The information is obtained by using **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION**. | -| signatureInfo | [SignatureInfo](#signatureinfo) | Yes | No | Signature information of the bundle. The information is obtained by using **GET_BUNDLE_INFO_WITH_SIGNATURE_INFO**. | +| appInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_APPLICATION** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | +| hapModulesInfo | Array\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | No | Module configuration information. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo).| +| permissionGrantStates | Array\<[PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate)> | Yes | No | Permission grant state. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | +| signatureInfo | [SignatureInfo](#signatureinfo) | Yes | No | Signature information of the bundle. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_SIGNATURE_INFO** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | | installTime | number | Yes | No | Time when the bundle was installed. | | updateTime | number | Yes | No | Time when the bundle was updated. | @@ -31,12 +33,12 @@ The **BundleInfo** module provides information about a bundle. Unless otherwise Provides the detailed information of the permissions to request from the system. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------------------- | ----------------------- | ---- | ---- | ---------------------| | name | string | Yes | Yes | Name of the permission to request. | -| reason | string | Yes | Yes | Reason for requesting the permission. | +| reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId | number | Yes | Yes | ID of the reason for requesting the permission.| | usedScene | [UsedScene](#usedscene) | Yes | Yes | Application scenario and timing for using the permission.| @@ -46,7 +48,7 @@ Provides the detailed information of the permissions to request from the system. Describes the application scenario and timing for using the permission. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------- | -------------- | ---- | ---- | --------------------------- | @@ -57,7 +59,7 @@ Describes the application scenario and timing for using the permission. Describes the signature information of the bundle. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------- | -------------- | ---- | ---- | --------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md index 662f0e37640287de5e10273a45d8db327a4551da..9bed479551e9b4f6c9b198f83fd9ed0114d7f1f5 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -2,7 +2,6 @@ The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.md). - > **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. @@ -14,7 +13,7 @@ The **ElementName** module provides element name information, which can be obtai | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | | deviceId | string | Yes | Yes | Device ID. | -| bundleName | string | Yes | Yes | Bundle name of the application. | +| bundleName | string | Yes | Yes | Bundle name. | | abilityName | string | Yes | Yes | Name of the ability. | | uri | string | Yes | Yes | Resource ID. | | shortName | string | Yes | Yes | Short name of the ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md index bc1542325379ddd73d4bb123e1e09eb2131b7d20..016b7af13fded843c7c85f05834669aa5e45c2bd 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md @@ -1,6 +1,6 @@ # ExtensionAbilityInfo -The **ExtensionAbilityInfo** module provides information about an Extension ability. Unless otherwise specified, all attributes are obtained through [getBundleInfo](js-apis-bundleManager.md), and flags are obtained through [GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY](js-apis-bundleManager.md#bundleflag). +The **ExtensionAbilityInfo** module defines the ExtensionAbility information. A system application can obtain its own or others' ExtensionAbility information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own ExtensionAbility information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY** must be passed in to the input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) to obtain the information. > **NOTE** > @@ -10,19 +10,19 @@ The **ExtensionAbilityInfo** module provides information about an Extension abil **System capability**: SystemCapability.BundleManager.BundleFramework.Core -| Name | Type | Readable| Writable| Description | -| -------------------- | ----------------------------------------------------------- | ---- | ---- | -------------------------------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| moduleName | string | Yes | No | Name of the HAP file to which the Extension ability belongs. | -| name | string | Yes | No | Name of the Extension ability. | -| labelId | number | Yes | No | Label ID of the Extension ability. | -| descriptionId | number | Yes | No | Description ID of the Extension ability. | -| iconId | number | Yes | No | Icon ID of the Extension ability. | -| isVisible | boolean | Yes | No | Whether the Extension ability can be called by other bundles. | -| extensionAbilityType | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes | No | Type of the Extension ability. | -| permissions | Array\ | Yes | No | Permissions required for other bundles to call the Extension ability.| -| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information of the Extension ability. | -| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the Extension ability. | -| enabled | boolean | Yes | No | Whether the Extension ability is enabled. | -| readPermission | string | Yes | No | Permission required for reading data from the Extension ability. | -| writePermission | string | Yes | No | Permission required for writing data to the Extension ability. | +| Name | Type | Readable| Writable| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ---- | ---------------------------------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| moduleName | string | Yes | No | Name of the HAP file to which the ExtensionAbility belongs. | +| name | string | Yes | No | Name of the ExtensionAbility. | +| labelId | number | Yes | No | ID of the ExtensionAbility label. | +| descriptionId | number | Yes | No | ID of the ExtensionAbility description. | +| iconId | number | Yes | No | ID of the ExtensionAbility icon. | +| isVisible | boolean | Yes | No | Whether the ExtensionAbility can be called by other bundles. | +| extensionAbilityType | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes | No | Type of the ExtensionAbility. | +| permissions | Array\ | Yes | No | Permissions required for other bundles to call the ExtensionAbility.| +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. | +| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ExtensionAbility. | +| enabled | boolean | Yes | No | Whether the ExtensionAbility is enabled. | +| readPermission | string | Yes | No | Permission required for reading data from the ExtensionAbility. | +| writePermission | string | Yes | No | Permission required for writing data to the ExtensionAbility. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md index 23e9c8c5e547642d240474fe6cad459b793883c1..8fe0cc4768b4b0ac352fcd98d9cefad9cc2c1553 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md @@ -1,5 +1,7 @@ # HapModuleInfo +The **HapModuleInfo** module defines the HAP module information. A system application can obtain its own or others' HAP module information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own HAP module information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). **GET_BUNDLE_INFO_WITH_HAP_MODULE** must be passed in to the input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) to obtain the information. + > **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. @@ -16,12 +18,11 @@ | label | string | Yes | No | Module label. | | labelId | number | Yes | No | ID of the module label. | | description | string | Yes | No | Module description. | -| descriptionId | number | Yes | No | ID of the module mescription. | +| descriptionId | number | Yes | No | ID of the module description. | | mainElementName | string | Yes | No | Name of the main ability. | | abilitiesInfo | Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Yes | No | Ability information. | -| extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.| +| extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | Yes | No | ExtensionAbility information.| | metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. | -| deviceTypes | Array\ | Yes | No | Device types supported by the module. | +| deviceTypes | Array\ | Yes | No | Types of devices where the module can run. | | installationFree | boolean | Yes | No | Whether installation-free is supported. | | hashValue | string | Yes | No | Hash value of the module. | -| moduleSourceDir | string | Yes | No | Module path.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md index c1919df283304c5a7e64c12b919b3e8c337e11e4..95326049595c17027a48552e04fab2d5a57816bb 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md @@ -1,7 +1,11 @@ # LauncherAbilityInfo + +The **LauncherAbilityInfo** module defines the ability information of the home screen application. The information can be obtained through [bundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetlauncherabilityinfo9). + > **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. + ## LauncherAbilityInfo **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher @@ -12,7 +16,7 @@ | --------------- | ----------------------------------------------------------- | ---- | ---- | ------------------------------------ | | applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information of the launcher ability.| | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | No | Element name of the launcher ability. | -| labelId | number | Yes | No | Label ID of the launcher ability. | -| iconId | number | Yes | No | Icon ID of the launcher ability. | -| userId | number | Yes | No | User ID of the launcher ability. | +| labelId | number | Yes | No | ID of the launcher ability label. | +| iconId | number | Yes | No | ID of the launcher ability icon. | +| userId | number | Yes | No | ID of the launcher ability user. | | installTime | number | Yes | No | Time when the launcher ability was installed. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md b/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md index 203c5328b680e6c534e16b1a39d0943c3e31ab28..1f1c28b64a5263d5e7ff6e92f1c2711d948a7d46 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md @@ -1,13 +1,16 @@ # Metadata -The **metadata** module provides the configuration about the module, ability, and Extension ability. The value is of the array type. The configuration is valid only for the current module, ability, or Extension ability. +The **Metadata** module provides a metadata object, which can be obtained through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). This object is contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md), [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md), [AbilityInfo](js-apis-bundleManager-abilityInfo.md), and [ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md). > **NOTE** -> -The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The **Metadata** module provides the configuration about the module, UIAbility, and ExtensionAbility. The value is of the array type. The configuration is valid only for the current module, UIAbility, or ExtensionAbility. + ## Metadata -**System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | -------- | ------ | ---- | ---- | ---------- | | name | string | Yes | Yes | Metadata name.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md index 4a0e43c1932a029ed7367d5b597528260a146bb0..a9e4c359659c55169acdbf0e3bc8f583b67febe9 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md @@ -2,7 +2,6 @@ The **PackInfo** module provides information in the **pack.info** file. The information can be obtained using [freeInstall.getBundlePackInfo](js-apis-freeInstall.md). - > **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. @@ -49,10 +48,10 @@ The **PackInfo** module provides information in the **pack.info** file. The info **System capability**: SystemCapability.BundleManager.BundleFrameWork.FreeInstall -| Name | Type | Readable| Writable| Description | -| ---------- | ------------------- | ---- | ---- | ---------------------------------- | -| bundleName | string | Yes | No | Bundle name. It uniquely identifies the application.| -| version | [Version](#version) | Yes | No | Bundle version. | +| Name | Type | Readable| Writable| Description | +| ---------- | ------------------- | ---- | ---- | -------------------------------------- | +| bundleName | string | Yes | No | Bundle name. It uniquely identifies an application.| +| version | [Version](#version) | Yes | No | Bundle version. | ## ModuleConfigInfo @@ -67,7 +66,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info | deviceType | Array\ | Yes | No | Device types supported by the module. | | distro | [ModuleDistroInfo](#moduledistroinfo) | Yes | No | Distribution information of the module. | | abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | Yes | No | Ability information of the module. | -| extensionAbilities | Array\<[ExtensionAbilities](#extensionability)> | Yes | No | Extension ability information of the module.| +| extensionAbilities | Array\<[ExtensionAbilities](#extensionability)> | Yes | No | ExtensionAbility information of the module.| ## ModuleDistroInfo @@ -103,7 +102,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info | Name | Type | Readable| Writable| Description | | ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes| No| Name of the Extension ability.| +| name | string | Yes| No| Name of the ExtensionAbility.| | forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information.| ## AbilityFormInfo @@ -132,7 +131,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info | ----------- | ------ | ---- | ---- | -------------------- | | releaseType | string | Yes | No | Name of the API version. | | compatible | number | Yes | No | Minimum API version.| -| target | number | Yes | No | Target API version. | +| target | number | Yes | No | Target API version. | ## Version diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md b/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md index aa3d41a76fd67da1a9a59d405d054e01db889754..b94f1e738890d0b30f74ab0ccde7ef43232a607e 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md @@ -1,6 +1,6 @@ # PermissionDef -The **PermissionDef** module provides permission details defined in the configuration file. The information can be obtained using [bundleManager.getPermissionDef](js-apis-bundleManager.md). +The **PermissionDef** module provides permission details defined in the configuration file. The information can be obtained using [bundleManager.getPermissionDef](js-apis-bundleManager.md). > **NOTE** > @@ -16,5 +16,5 @@ The **PermissionDef** module provides permission details defined in the configur | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | | grantMode | number | Yes | No | Grant mode of the permission.| -| labelId | number | Yes | No | Label ID of the permission. | -| descriptionId | number | Yes | No | Description ID of the permission. | +| labelId | number | Yes | No | ID of the permission label. | +| descriptionId | number | Yes | No | ID of the permission description. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md index 2c06d138b5bfda6383fabc14e28d3fb008af0bf0..875c2ac9ce239430d86cf43d02071b327604184f 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -17,7 +17,7 @@ The **ShortcutInfo** module defines shortcut information configured in the confi | Name | Type | Readable| Writable| Description | | ------------------------- | ------ | ---- | ---- | -------------------- | | targetBundle | string | Yes | No | Target bundle name of the shortcut.| -| targetModule | string | Yes | No | Target module name of the shortcut. | +| targetModule | string | Yes | No | Target module name of the shortcut. | | targetAbility | string | Yes | No | Target ability name of the shortcut.| ## ShortcutInfo @@ -28,14 +28,14 @@ The **ShortcutInfo** module defines shortcut information configured in the confi | Name | Type | Readable| Writable| Description | | ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | -| id | string | Yes | No | ID of the application to which the shortcut belongs. | -| bundleName | string | Yes | No | Name of the bundle that contains the shortcut. | -| moduleName | string | Yes | No | Module name of the shortcut. | -| hostAbility | string | Yes | No | Local ability name of the shortcut. | -| icon | string | Yes | No | Icon of the shortcut. | -| iconId | number | Yes | No | Icon ID of the shortcut. | -| label | string | Yes | No | Label of the shortcut. | -| labelId | number | Yes | No | Label ID of the shortcut. | -| wants | Array\<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | - - \ No newline at end of file +| id | string | Yes | No | ID of the application to which the shortcut belongs. | +| bundleName | string | Yes | No | Name of the bundle that contains the shortcut.| +| moduleName | string | Yes | No | Module name of the shortcut. | +| hostAbility | string | Yes | No | Local ability name of the shortcut. | +| icon | string | Yes | No | Icon of the shortcut. | +| iconId | number | Yes | No | ID of the shortcut icon. | +| label | string | Yes | No | Label of the shortcut. | +| labelId | number | Yes | No | ID of the shortcut label. | +| wants | Array\<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | + + diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index 3dab120c4667c563047b5cc48da6ed378e4a29aa..38e42db4dc336dece5467e60c3a390d579fcac98 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -1,4 +1,4 @@ -# @ohos.bundle.bundleManager +# @ohos.bundle.bundleManager (bundleManager) The **bundleManager** module provides APIs for querying information about bundles, applications, abilities, Extension abilities, and more. diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index cf2d7aab46c5d8ea80d49fe66b61ae68e56885a0..11f54832d6556e24f35cd1baedee0d9abfe39079 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -1,4 +1,4 @@ -# @ohos.bundle.bundleMonitor +# @ohos.bundle.bundleMonitor (bundleMonitor) The **Bundle.bundleMonitor** module provides APIs for listens for bundle installation, uninstall, and updates. @@ -33,7 +33,7 @@ For details, see [Permission Levels](../../security/accesstoken-overview.md). ## bundleMonitor.on -on(type: BundleChangedEvent, callback: Callback\): void; +on(type: BundleChangedEvent, callback: callback\): void; Subscribes to bundle installation, uninstall, and update events. @@ -47,8 +47,8 @@ Subscribes to bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ------------------ | -| BundleChangedEvent | string | Yes | Type of the event to subscribe to.| -| Callback\ | callback | Yes | Callback used for the subscription.| +| type| BundleChangedEvent| Yes | Type of the event to subscribe to.| +| callback | callback\| Yes | Callback used for the subscription.| **Example** @@ -66,7 +66,7 @@ try { ## bundleMonitor.off -off(type: BundleChangedEvent, callback?: Callback\): void; +off(type: BundleChangedEvent, callback?: callback\): void; Unsubscribes from bundle installation, uninstall, and update events. @@ -80,8 +80,8 @@ Unsubscribes from bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ---------------------------------------------------------- | -| BundleChangedEvent | string | Yes | Type of the event to unsubscribe from. | -| Callback\ | callback | Yes | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| +| 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.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md new file mode 100644 index 0000000000000000000000000000000000000000..dc506245c6feef1b2c22b70613ce3359404162dc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cert.md @@ -0,0 +1,2109 @@ +# @ohos.security.cert (Certificate) + +The **certificate** module provides APIs for performing certificate operations. For details about the APIs for implementing the basic algorithm capabilities based on the cryptographic (crypto) framework, see [Crypto Framework](js-apis-cryptoFramework.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. + +## Modules to Import + +```javascript +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" +``` + +## CertResult + + Enumerates the error codes. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value | Description | +| --------------------------------------| -------- | -----------------------------| +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | This operation is not supported. | +| ERR_OUT_OF_MEMORY | 19020001 | Memory error. | +| ERR_RUNTIME_ERROR | 19020002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 19030001 | Crypto operation error. | +| ERR_CERT_SIGNATURE_FAILURE | 19030002 | The certificate signature verification failed. | +| ERR_CERT_NOT_YET_VALID | 19030003 | The certificate has not taken effect. | +| ERR_CERT_HAS_EXPIRED | 19030004 | The certificate has expired. | +| ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY | 19030005 | Failed to obtain the certificate issuer. | +| ERR_KEYUSAGE_NO_CERTSIGN | 19030006 | The key cannot be used for signing a certificate. | +| ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE | 19030007 | The key cannot be used for digital signature. | + +## DataBlob +Defines a binary data array. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data. | + +## DataArray + +Defines a list of data arrays. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data list. | + +## EncodingFormat + + Enumerates the certificate encoding formats. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value| Description | +| ---------- | ------ | --------- | +| FORMAT_DER | 0 | Distinguished Encoding Rules (DER) format.| +| FORMAT_PEM | 1 | Privacy-Enhanced Mail (PEM) format.| + + +## EncodingBlob + +Defines a certificate binary array in encoding format. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data.| +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## CertChainData + +Defines the certificate chain data, which is passed in as input parameters during certificate chain verification. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data, in the *length* (2 bytes) + *data* format. For example, **08ABCDEFGH07ABCDEFG**. The first two bytes indicate the length of the first certificate is eight bytes, and the following eight bytes indicate the certificate data. Then, the next two bytes indicate the length of another certificate is seven bytes, and the seven bytes followed indicate the certificate data.| +| count | number | Yes | Yes | Number of certificates contained in the input data. | +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Cert** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cer** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + } +}); +``` + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob) : Promise\ + +Creates an **X509Cert** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data.| + +**Return value** + +| Type | Description | +| ------- | ---------------- | +| Promise\ | **X509Cer** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Cert + +Provides APIs for X.509 certificate operations. + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the certificate signature. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the certificate signature. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 certificate data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized X.509 certificate data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + x509Cert.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 certificate data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | ---------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized X.509 certificate data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + x509Cert.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getPublicKey + +getPublicKey() : cryptoFramework.PubKey + +Obtains the public key of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| cryptoFramework.PubKey | X.509 certificate public key obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let pubKey = null; + try { + pubKey = x509Cert.getPublicKey(); + } catch (error) { + console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### checkValidityWithDate + +checkValidityWithDate(date: string) : void + +Checks the validity period of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------- | +| date | string | Yes | Date of the certificate to check. | + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let date = "150527000001Z"; + + // Verify the certificate validity period. + try { + x509Cert.checkValidityWithDate(date); + } catch (error) { + console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getVersion + +getVersion() : number + +Obtains the X.509 certificate version. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| number | X.509 certificate version obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let version = x509Cert.getVersion(); + } +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the X.509 certificate serial number. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | X.509 certificate serial number obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let serialNumber = x509Cert.getSerialNumber(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the X.509 certificate issuer. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- | +| [DataBlob](#datablob) | X.509 certificate issuer obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerName = x509Cert.getIssuerName(); + } +}); +``` + +### getSubjectName + +getSubjectName() : DataBlob + +Obtains the subject of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Subject name obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectName = x509Cert.getSubjectName(); + } +}); +``` + +### getNotBeforeTime + +getNotBeforeTime() : string + +Obtains the start time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Start time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notBefore = x509Cert.getNotBeforeTime(); + } +}); +``` + +### getNotAfterTime + +getNotAfterTime() : string + +Obtains the expiration time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Expiration time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notAfter = x509Cert.getNotAfterTime(); + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Signature data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let signature = x509Cert.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | X.509 certificate signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgName = x509Cert.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the object identifier (OID) of the X.509 certificate signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------- | +| string | OID obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgOid = x509Cert.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the signing algorithm parameters of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------ | +| [DataBlob](#datablob) | X.509 certificate signing algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgParams = x509Cert.getSignatureAlgParams(); + } +}); +``` + +### getKeyUsage + +getKeyUsage() : DataBlob + +Obtains the key usage of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Key usage of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let keyUsage = x509Cert.getKeyUsage(); + } +}); +``` + +### getExtKeyUsage + +getExtKeyUsage() : DataArray + +Obtains the usage of the extended key of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | Usage of the extended key obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let extKeyUsage = x509Cert.getExtKeyUsage(); + } +}); +``` + +### getBasicConstraints + +getBasicConstraints() : number + +Obtains the basic constraints for obtaining this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| number | Basic constraints obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let basicConstraints = x509Cert.getBasicConstraints(); + } +}); +``` + +### getSubjectAltNames + +getSubjectAltNames() : DataArray + +Obtains the Subject Alternative Names (SANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | SANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectAltNames = x509Cert.getSubjectAltNames(); + } +}); +``` + +### getIssuerAltNames + +getIssuerAltNames() : DataArray + +Obtains the Issuer Alternative Names (IANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | -------------------------- | +| [DataArray](#dataarray) | IANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerAltNames = x509Cert.getIssuerAltNames(); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Crl** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob) : Promise\ + +Creates an **X509Crl** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized CRL data.| + +**Return value** + +| Type | Description | +| ----------------- | -------------------- | +| Promise\ | Promise used to return the **X509Crl** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Crl + +Provides APIs for X.509 certificate CRL operations. + +### isRevoked + +isRevoked(cert : X509Cert) : boolean + +Checks whether an X.509 certificate is revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| cert | X509Cert | Yes | X.509 certificate to check.| + +**Return value** + +| Type | Description | +| --------- | --------------------------------------------- | +| boolean | Promise used to return the result. The value **true** indicates the certificate is revoked; the value **false** indicates the opposite.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let revokedFlag = x509Crl.isRevoked(x509Cert); + } catch (error) { + console.log("isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getType + +getType() : string + +Obtains the CRL type. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| string | CRL type obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let type = x509Crl.getType(); + } +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------ | +| callback | AsyncCallback\ | Yes | Callback invoked to return the serialized X.509 CRL data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 CRL data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ---------------------- | -------------------------------- | +| Promise\ | Promise used to return the serialized X.509 CRL data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the signature of the X.509 CRL. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type| Description | +| ---- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getVersion + +getVersion() : number + +Obtains the version of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| number | Version of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let version = x509Crl.getVersion(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the issuer of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Issuer of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let issuerName = x509Crl.getIssuerName(); + } +}); +``` + +### getLastUpdate + +getLastUpdate() : string + +Obtains the date when the X.509 CRL was last updated. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Last update date of the X.509 CRL.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let lastUpdate = x509Crl.getLastUpdate(); + } +}); +``` + +### getNextUpdate + +getNextUpdate() : string + +Obtains the date when the CRL will be updated the next time. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Next update date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let nextUpdate = x509Crl.getNextUpdate(); + } +}); +``` + +### getRevokedCert + +getRevokedCert(serialNumber : number) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified serial number of the certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | -------------- | +| serialNumber | number | Yes | Serial number of the certificate.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Set the serial number of the corresponding certificate. + let serialNumber = 1000; + try { + let entry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCertWithCert + +getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.| + +**Return value** + +| Type | Description | +| ------------ | -------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let entry = x509Crl.getRevokedCertWithCert(x509Cert); + } catch (error) { + console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCerts + +getRevokedCerts(callback : AsyncCallback>) : void + +Obtains all the revoked X.509 certificates. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts(function (error, array) { + if (error != null) { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getRevokedCerts success"); + } + }); + } +}); +``` + +### getRevokedCerts + +getRevokedCerts() : Promise> + +Obtains all the revoked X.509 certificates. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------------- | ---------------------- | +| Promise> | Promise used to return a list of revoked X.509 certificates.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts().then(array => { + console.log("getRevokedCerts success"); + }, error => { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getTbsInfo + +getTbsInfo() : DataBlob + +Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| [DataBlob](#datablob) | Promise used to return the **tbsCertList** information obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + try { + let tbsInfo = x509Crl.getTbsInfo(); + } catch (error) { + console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Signature data of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let signature = x509Crl.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| string | Signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgName = x509Crl.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------------------- | +| string | OID of the X.509 CRL signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgOid = x509Crl.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the parameters of the X.509 CRL signing algorithm. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------- | +| [DataBlob](#datablob) | Algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgParams = x509Crl.getSignatureAlgParams(); + } +}); +``` + +## cryptoCert.createCertChainValidator + +createCertChainValidator(algorithm :string) : CertChainValidator + +Creates a **CertChainValidator** object. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------ | +| algorithm | string | Yes | Certificate chain validator algorithm. Currently, only **PKIX** is supported.| + +**Return value** + +| Type | Description | +| ------------------ | -------------------- | +| CertChainValidator | **CertChainValidator** object created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +``` + +## CertChainValidator + +Provides APIs for certificate chain validator operations. + + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------- | +| algorithm | string | Yes | No | Algorithm used by the X509 certificate chain validator.| + + +### validate + +validate(certChain : CertChainData, callback : AsyncCallback\) : void + +Validates the X.509 certificate chain. This API uses an asynchronous callback to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the X.509 certificate chain is valid. If **error** is not **null**, the X.509 certificate chain is not valid.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData, function (error, data) { + if (error != null) { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("validate success"); + } +}); +``` + +### validate + +validate(certChain : CertChainData) : Promise\ + +Validates the X.509 certificate chain. This API uses a promise to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | -------------------------- | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData).then(result => { + console.log("validate success"); +}, error => { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### algorithm + +algorithm : string + +Obtains the algorithm of the X.509 certificate chain validator. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | Algorithm of the X.509 certificate chain validator obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +let algorithm = validator.algorithm; +``` + +## X509CrlEntry + +Provides APIs for operating the revoked certificates. + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized data of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized data of the revoked certificate obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized data of this revoked certificate. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized data of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded().then(result => { + console.log("getEncoded success"); +}, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the serial number of this revoked certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------------- | +| number | Serial number of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +let serialNumber = x509CrlEntry.getSerialNumber(); +``` + +### getCertIssuer + +getCertIssuer() : DataBlob + +Obtains the issuer of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- - | +| [DataBlob](#datablob) | Promise used to return the issuer of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let issuer = x509CrlEntry.getCertIssuer(); +} catch (error) { + console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` + +### getRevocationDate + +getRevocationDate() : string + +Obtains the date when the certificate was revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Promise used to return the certificate revocation date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let date = x509CrlEntry.getRevocationDate(); +} catch (error) { + console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-colorSpaceManager.md b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md index 044fab3c6456d47e9a342b78770f10dc8f58c87d..706838181628f3e95cf2a35660d78e2f9389d73c 100644 --- a/en/application-dev/reference/apis/js-apis-colorSpaceManager.md +++ b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md @@ -1,4 +1,4 @@ -# Color Space Management +# @ohos.graphics.colorSpaceManager (Color Space Management) The **colorSpaceManager** module provides APIs for creating and managing color space objects and obtaining basic color space attributes. diff --git a/en/application-dev/reference/apis/js-apis-configuration.md b/en/application-dev/reference/apis/js-apis-configuration.md deleted file mode 100644 index 25c57c7d5f0a6b7a1e8073fc9313bb92562b8576..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-configuration.md +++ /dev/null @@ -1,26 +0,0 @@ -# Configuration - -The **Configuration** module provides environment configuration information. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -```js -import Configuration from '@ohos.application.Configuration'; -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityBase - - | Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| language | string | Yes| Yes| Language of the application.| -| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction9+ | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity9+ | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| -| displayId9+ | number | Yes| No| ID of the display where the application is located.| -| hasPointerDevice9+ | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md index 0e0bd18e5e4a5d2abafcdbdf82b17f88a23357cd..d02b0dd61bffff14504bf77ca225c25ce953539e 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md @@ -1,7 +1,6 @@ # ContinuationResult > **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. ## ContinuationResult diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md index 30d79a672420f70d0ab3067857e8726ab8a7ba32..4b6210a18736d99c786a2a305dc5ed534445b488 100644 --- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -1,9 +1,9 @@ -# Crypto Framework +# @ohos.security.cryptoFramework (Crypto Framework) -The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for crytographic operations. +The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. ## Modules to Import @@ -18,20 +18,23 @@ import cryptoFramework from "@ohos.security.cryptoFramework" **System capability**: SystemCapability.Security.CryptoFramework -| Name | Default Value | Description | -| --------------------------------------| -------- | -------------------------| -| INVALID_PARAMS | 401 | Invalid parameters. | -| NOT_SUPPORT | 801 | This operation is not supported. | -| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | -| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | -| ERR_CRYPTO_OPERATION | 17630001 | Crypto operation error. | +| Name | Value | Description | +| ------------------------------------- | -------- | ---------------------------- | +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | Unsupported operation. | +| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | +| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. | ## DataBlob + Defines a binary data array. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------| -| data | Uint8Array | Yes | Yes | Data. | + +| Name| Type | Readable| Writable| Description | +| ---- | ---------- | ---- | ---- | ------ | +| data | Uint8Array | Yes | Yes | Data.| + ## cryptoFramework.createMac @@ -53,6 +56,12 @@ Creates a **Mac** instance for message authentication code (MAC) operations. | ---- | --------------------------------------- | | Mac | [Mac](#mac) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -60,6 +69,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var mac; try { + // Set algName based on the algorithm supported. mac = cryptoFramework.createMac("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -70,7 +80,7 @@ try { Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework @@ -88,10 +98,16 @@ Initializes the MAC computation using a symmetric key. This API uses an asynchro **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| key | SymKey | Yes | Shared symmetric key. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------ | +| key | SymKey | Yes | Shared symmetric key.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -118,8 +134,6 @@ symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { }); ``` - - ### init init(key : SymKey) : Promise\; @@ -136,10 +150,16 @@ Initializes the MAC computation using a symmetric key. This API uses a promise t **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -149,9 +169,7 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); - } console.error("Mac algName is: " + mac.algName); @@ -175,10 +193,18 @@ Updates the MAC computation data. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -190,7 +216,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -220,16 +245,26 @@ Updates the MAC computation data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + +**Example** + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -237,14 +272,11 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { @@ -260,8 +292,6 @@ promiseConvertKey.then(symKey => { ``` - - ### doFinal doFinal(callback : AsyncCallback\) : void; @@ -270,10 +300,19 @@ Finalizes the MAC computation. This API uses an asynchronous callback to return **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------- | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -284,7 +323,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -323,10 +361,17 @@ Finalizes the MAC computation. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -339,7 +384,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -375,6 +419,12 @@ Obtains the MAC length, in bytes. | ------ | ------------------------- | | number | MAC length obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -387,7 +437,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -405,7 +454,7 @@ promiseConvertKey.then(symKey => { }).then(macOutput => { console.error("[Promise]: HMAC result: " + macOutput.data); let macLen = mac.getMacLength(); - AlertDialog.show({message: "MAC len: " + macLen}); + console.error("MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -431,6 +480,12 @@ Creates an **Md** instance for message digest operations. | ---- | ------------------------------------- | | Md | [Md](#md) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -438,6 +493,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var md; try { + // Set algName based on the algorithm supported. md = cryptoFramework.createMd("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -448,27 +504,34 @@ try { Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm to use.| +| algName | string | Yes | No | Digest algorithm.| ### update update(input : DataBlob, callback : AsyncCallback\) : void; -Updates the message digest data with the message passed in. This API uses an asynchronous callback to return the result. +Updates the message digest data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------ | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -495,20 +558,26 @@ md.update(blob, (err,) => { update(input : DataBlob) : Promise\; -Updates the message digest data with the message passed in. This API uses a promise to return the result. +Updates the message digest data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -539,10 +608,17 @@ Generates a message digest. This API uses an asynchronous callback to return the **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -581,10 +657,17 @@ Generates a message digest. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -622,7 +705,13 @@ Obtains the message digest length, in bytes. | Type | Description | | ------ | ------------------------ | -| number | Message digest length obtained. | +| number | Message digest length obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -645,7 +734,7 @@ promiseMdUpdate.then(() => { }).then(mdOutput => { console.error("[Promise]: MD result: " + mdOutput.data); let mdLen = md.getMdLength(); - AlertDialog.show({message: "MD len: " + mdLen}); + console.error("MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -665,6 +754,12 @@ Creates a **Random** instance for generating random numbers and setting seeds. | ------ | --------------------------------------------- | | Random | [Random](#random) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -679,7 +774,7 @@ try { ## Random -Provides APIs for computing random numbers. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). +Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). ### generateRandom @@ -689,10 +784,19 @@ Generates a random number of the given length. This API uses an asynchronous cal **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | **Example** @@ -722,16 +826,25 @@ Generates a random number of the given length. This API uses a promise to return **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | len | number | Yes | Length of the random number to generate.| **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -754,16 +867,21 @@ promiseGenerateRand.then(randData => { ### setSeed -setSeed(seed : DataBlob, callback : AsyncCallback\) : void; +setSeed(seed : DataBlob) : void; Sets a seed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------ | -| seed | DataBlob | Yes | Seed to set. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| seed | DataBlob | Yes | Seed to set.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------- | +| 17620001 | memory error | **Example** @@ -782,94 +900,70 @@ rand.generateRandom(12, (err, randData) => { console.error("[Callback] err: " + err.code); } else { console.error("[Callback]: generate random result: " + randData.data); - rand.setSeed(randData, (err1, data) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: setSeed success"); - } - }); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } } }); ``` -### setSeed - -setSeed(seed : DataBlob) : Promise\; - -Sets a seed. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.CryptoFramework - -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| seed | DataBlob | Yes | Seed to set.| - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} - -var promiseGenerateRand = rand.generateRandom(12); -promiseGenerateRand.then(randData => { - console.error("[Promise]: rand result: " + randData.data); - var promiseSetSeed = rand.setSeed(randData); - return promiseSetSeed; -}).then(() => { - console.error("[Promise]: setSeed success"); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` - ## ParamsSpec -Defines the parameters for encryption and decryption. For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). You do not need to construct the child class object if the IV is not required. +Defines the parameters used for encryption and decryption.
For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2). **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters.
Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode. | +| Name | Type | Readable| Writable| Description | +| -------- | ------ | ---- | ---- | ----------------------- | +| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC,|CTR,|OFB, |and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| + +> **NOTE** +> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), while a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you must set **algoName** for the parent class **ParamsSpec** to let the algorithm library know the child class object to pass in in **init()**. ## IvParamsSpec -Defines the parameters for the CBC, CTR, OFB, and CFB modes, which require only an IV for each encryption operation. For the symmetric encryption and decryption that use the CBC, CTR, OFB, or CFB mode, you need to construct **IvParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption.
Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB or CFB mode: 8-byte IV | +| Name| Type | Readable| Writable| Description | +| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, |CTR, |OFB, |or CFB mode: 16-byte IV
- 3DES CBC,|OFB, or |CFB mode: 8-byte IV| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## GcmParamsSpec -Defines the parameters for the GCM mode. For the symmetric encryption and decryption that use the GCM mode, you need to construct **GcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**GcmParamsSpec** applies to the GCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes.| -| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes.| -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 16 bytes.
When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) for decryption.| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CcmParamsSpec -Defines the parameters for the CCM mode. For the symmetric encryption and decryption that use the CCM mode, you need to construct **CcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**CcmParamsSpec** applies to the CCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | -------- | ---- | ---- | -------------------------------| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | | iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | | aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 12 bytes.
When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) for decryption.| +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CryptoMode @@ -877,22 +971,22 @@ Enumerates the cryptographic operations. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Value | Description | -| ------------ | -------- | -------------------------------- | -| ENCRYPT_MODE | 0 | Encryption. | -| DECRYPT_MODE | 1 | Decryption. | +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| ENCRYPT_MODE | 0 | Encryption.| +| DECRYPT_MODE | 1 | Decryption.| ## Key -Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. Keys can be generated by a key generator. +Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -905,48 +999,50 @@ Obtains the key in hexadecimal format. This API returns the result synchronously **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## SymKey -Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). +Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); -console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. +console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. key.clearMem(); encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s. @@ -954,15 +1050,15 @@ console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display a ## PubKey -Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Public keys can be generated by an **AsyKeyGenerator**. +Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Public keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| @@ -976,30 +1072,37 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## PriKey -Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Private keys can be generated by an **AsyKeyGenerator**. +Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Private keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -1012,52 +1115,74 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. key.clearMem(); ``` +## KeyPair + +Defines an asymmetric key pair, which includes a public key and a private key.
Asymmetric key pairs can be generated by the **AsyKeyGenerator**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------ | +| priKey | [PriKey](#prikey) | Yes | No | Private key. | +| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | + + ## cryptoFramework.createSymKeyGenerator createSymKeyGenerator(algName : string) : SymKeyGenerator -Creates a **SymKeyGenerator** instance based on the specified algorithm. For details about the supported symmetric key parameters, see "String for Generating a Key" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Creates a **symKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ----------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String for Generating a Key" in [Key Generation Specifications] (../../security/cryptoFramework-overview.md#key-generation-specifications).| **Return value** -| Type | Description | +| Type | Description | | ----------------------------------- | -------------------------- | -| [SymKeyGenerator](#symkeygenerator) | **SymKeyGenerator** instance created.| +| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| **Example** @@ -1068,29 +1193,35 @@ let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); ## SymKeyGenerator -Provides APIs for using the **symKeyGenerator**. Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +Provides APIs for using the **symKeyGenerator**.
Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------ | | algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| ### generateSymKey generateSymKey(callback : AsyncCallback\) : void -Generates a key randomly. This API uses an asynchronous callback to return the result. +Generates a key randomly. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ------------------- | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | **Example** @@ -1099,11 +1230,11 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); symKeyGenerator.generateSymKey((err, symKey) => { - if (err) { - console.error('Failed to generate symKey'); - return; - } - console.log('Generate symKey success, algName: ' + symKey.algName); + if (err) { + console.error(`Generate symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Generate symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1111,24 +1242,33 @@ symKeyGenerator.generateSymKey((err, symKey) => { generateSymKey() : Promise\ -Generates a key randomly. This API uses a promise to return the result. +Generates a key randomly. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | + **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = 'AES128'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); -symKeyGenerator.generateSymKey().then((symKey) => { - console.log('Generate symKey success, algName:' + symKey.algName); +symKeyGenerator.generateSymKey() +.then(symKey => { + console.info(`Generate symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Generate symKey failed, ${error.code}, ${error.message}`); }) ``` @@ -1136,16 +1276,22 @@ symKeyGenerator.generateSymKey().then((symKey) => { convertKey(key : DataBlob, callback : AsyncCallback\) : void -Converts a key. This API uses an asynchronous callback to return the result. +Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ---------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert. | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| key | [DataBlob](#datablob) | Yes | Data to convert. | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------- | +| 17620001 | memory error. | **Example** @@ -1164,12 +1310,12 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { - if (err) { - console.error('Failed to convert symKey'); - return; - } - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { + if (err) { + console.error(`Convert symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Convert symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1177,22 +1323,28 @@ symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { convertKey(key : DataBlob) : Promise\ -Converts a key. This API uses a promise to return the result. +Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| key | [DataBlob](#datablob) | Yes | Data to convert.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------- | +| 17620001 | memory error. | + **Example** ```js @@ -1210,14 +1362,18 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial).then((symKey) => { - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob) +.then(symKey => { + console.info(`Convert symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Convert symKey failed, ${error.code}, ${error.message}`); }) ``` ## cryptoFramework.createAsyKeyGenerator createAsyKeyGenerator(algName : string) : AsyKeyGenerator + Creates an **AsyKeyGenerator** instance based on the specified algorithm. **System capability**: SystemCapability.Security.CryptoFramework @@ -1226,12 +1382,12 @@ Creates an **AsyKeyGenerator** instance based on the specified algorithm. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| **Return value** -| Type | Description | -| --------------- | -------------------------- | +| Type | Description | +| --------------- | ---------------------------- | | asyKeyGenerator | **AsyKeyGenerator** instance created.| **Example** @@ -1250,23 +1406,22 @@ Provides APIs for using the **AsKeyGenerator**. Before using any API of the **As **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------------------------| -| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**. | - - +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------------- | +| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| ### generateKeyPair generateKeyPair(callback : AsyncCallback\) : void; + Generates a key pair randomly. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** @@ -1288,14 +1443,15 @@ asyKeyGenerator.generateKeyPair((err, keyPair) => { ### generateKeyPair generateKeyPair() : Promise\ + Generates a key pair randomly. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1315,23 +1471,25 @@ keyGenPromise.then( keyPair => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void -Converts an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------ | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" - +let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here. +let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here. let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { if (err) { @@ -1345,21 +1503,22 @@ asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ -Converts an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------- | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1368,6 +1527,8 @@ Converts an asymmetric key. This API uses a promise to return the result. For de import cryptoFramework from "@ohos.security.cryptoFramework" let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here. +let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here. let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey); keyGenPromise.then( keyPair => { console.info("convertKey success."); @@ -1378,28 +1539,32 @@ keyGenPromise.then( keyPair => { **Key Conversion** -- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 and PKCS #8 formats is returned, respectively. The data can be used for cross-application transfer or persistent storage. +- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage. - The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -- In **convertKey()**, **pubKey** and **priKey** are optional. Either **pubKey** or **priKey** can be passed in. As a result, the returned **KeyPair** instance contains only the key converted from the data you passed in. +- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. ## cryptoFramework.createCipher createCipher(transformation : string) : Cipher -Creates a [Cipher](#cipher) instance based on the specified algorithm. -For details about the supported algorithms, see "Algorithm String" in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). + +Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | -------- | ------------------------------------------------------------ | -| transformation | string | Yes | Combination of the algorithm name, encryption mode, and padding algorithm of the **Cipher** instance to create. For example, **RSA1024\|PKCS1** or **RSA1024\|PKCS1_OAEP\|SHA256\|SHA256**.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details about, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). | + +> **NOTE** +> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. +> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. **Return value** -| Type | Description | -| ------ | ------------------------ | +| Type | Description | +| ----------------- | ------------------------ | | [Cipher](#cipher) | [Cipher](#cipher) instance created.| **Example** @@ -1414,39 +1579,51 @@ try { console.info(`cipher algName: ${cipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); - return; } ``` ## Cipher -Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. For details about the complete encryption and decryption process, see [Encryption and Decryption Operations](../../security/cryptoFramework-guidelines.md#encryption-and-decryption-operations). +Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). + +A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. + +- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation. +- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable | Writable | Description | -| ------- | ------ | -------- | ----------- | ---------------------------- | -| algName | string | Yes | No | Algorithm to use.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm.| ### init init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void -Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. +Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------ | ------- | ------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1454,13 +1631,14 @@ Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. + cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { if (err) { - console.error('Failed to init cipher'); - return; + console.error(`Failed to init cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. } - console.log('Init cipher success'); - // Perform subsequent operations such as update. }) ``` @@ -1468,23 +1646,31 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ -Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. +Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
**init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ---------- | ---- | ---------------------- | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption.| -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. | +| Name | Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| **Return value** -| Type | Description | -| ------------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1492,9 +1678,12 @@ Initializes a [cipher](#cipher) instance. This API uses a promise to return the import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { - console.log('Init cipher success'); +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) +.then(() => { + console.info(`Init cipher success`); // Perform subsequent operations such as update. +}, error => { + console.error(`Failed to init cipher, ${error.code}, ${error.message}`); }) ``` @@ -1502,16 +1691,29 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { update(data : DataBlob, callback : AsyncCallback\) : void -Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1531,11 +1733,14 @@ let cipher; // The process of creating a Cipher instance is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; cipher.update(plainText, (err, output) => { // Example of the encryption process. if (err) { - console.error('Failed to update cipher'); - return; + console.error(`Failed to update cipher`); + } else { + console.info(`Update cipher success`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). } - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. }) ``` @@ -1543,21 +1748,34 @@ cipher.update(plainText, (err, output) => { // Example of the encryption p update(data : DataBlob) : Promise\ -Updates the data to encrypt or decrypt by segment. This API uses a promise to return the result. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output. That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to returns the **DataBlob** (containing the encrypted or decrypted data).| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1575,9 +1793,15 @@ function stringToUint8Array(str) { let cipher; // The process of creating a Cipher instance is omitted here. // The init() process is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(data).then((output) => { - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. +cipher.update(plainText) +.then((output) => { + console.info(`Update cipher success.`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). +}, error => { + console.info(`Update cipher failed.`); }) ``` @@ -1585,23 +1809,33 @@ cipher.update(data).then((output) => { doFinal(data : DataBlob, callback : AsyncCallback\) : void -Finalizes the data encryption or decryption operation. This API uses an asynchronous callback to return the result. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. -- For symmetric encryption and decryption in other modes, the output can be either of the following: - (1) **Update()** returns part of the encryption and decryption result, and **doFinal()** returns the remaining encryption and decryption result. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. + +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.
If data is already passed in by [update()](#update-4), **data** can be **null**. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1613,10 +1847,13 @@ let data; // The process of preparing the data to encrypt or decrypt i // The init() and update() processes are omitted here. cipher.doFinal(data, (err, output) => { if (err) { - console.error('Failed to final cipher'); - return; + console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } } - console.log('Final cipher success'); }) ``` @@ -1624,31 +1861,38 @@ cipher.doFinal(data, (err, output) => { doFinal(data : DataBlob) : Promise\ -Finalizes the data encryption or decryption operation. This API uses a promise to return the result. - -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. - -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -- For symmetric encryption and decryption in other modes, the output includes the following: +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. **authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. - (1) **Update()** returns part of the encryption and decryption results, and **doFinal()** returns the remaining encryption and decryption results. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. If data is already passed in by [update()](#update-4), **data** can be **null**. | +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1658,22 +1902,37 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let cipher; // The process of creating a Cipher instance is omitted here. let data; // The process of preparing the data to encrypt or decrypt is omitted here. // The init() and update() processes are omitted here. -cipher.doFinal(data).then((output) => { - console.log('Final cipher success'); +cipher.doFinal(data) +.then(output => { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } +}, error => { + console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); }) ``` -**Callback example**: +**RSA encryption example (callback)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +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 rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); rsaGenerator.generateKeyPair(function (err, keyPair) { let pubKey = keyPair.pubKey; cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { - let input = {data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = {data : stringToUint8Array(plainText) }; cipher.doFinal(input, function (err, data) { AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); }); @@ -1681,11 +1940,19 @@ rsaGenerator.generateKeyPair(function (err, keyPair) { }); ``` -**Promise example**: +**RSA encryption example (promise)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +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 rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); let keyGenPromise = rsaGenerator.generateKeyPair(); @@ -1693,13 +1960,16 @@ keyGenPromise.then(rsaKeyPair => { let pubKey = rsaKeyPair.pubKey; return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. }).then(() => { - let input = { data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = { data : stringToUint8Array(plainText) }; return cipher.doFinal(input); }).then(dataBlob => { console.info("EncryptOutPut is " + dataBlob.data); }); ``` +> **NOTE** +> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data). ## cryptoFramework.createSign @@ -1717,9 +1987,9 @@ Creates a **Sign** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Sign | **Sign** instance created.| +| Type| Description | +| ---- | -------------------------------- | +| Sign | **Sign** instance created.| **Example** @@ -1728,46 +1998,58 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256") ``` ## Sign -Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. +Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. +The signing mode is determined in **createSign()**, and the key is set by **init()**. +If the data to be signed is short, you can call **sign()** to pass in the data for signing after **init()**. +If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. +If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to use.| ### init init(priKey : PriKey, callback : AsyncCallback\) : void -Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. +Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init -init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ +init(priKey : PriKey) : Promise\ -Initializes a **Sign** instance using a private key. This API uses a promise to return the result. +Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1780,10 +2062,10 @@ Updates the data to be signed. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1797,12 +2079,12 @@ Updates the data to be signed. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### sign @@ -1815,10 +2097,10 @@ Signs the data. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### sign @@ -1832,53 +2114,92 @@ Signs the data. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -rsaGenerator.generateKeyPair(function (err, keyPair) { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - signer.init(priKey, function (err, data) { - signer.update(input1, function (err, data) { - signer.sign(input2, function (err, data) { - SignMessageBlob = data; - console.info("sign output is " + SignMessageBlob.data); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessageCallback() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + rsaGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + signer.init(priKey, function (err, data) { + signer.update(input1, function (err, data) { // Add the first segment of the data. + signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. + SignMessageBlob = data; + AlertDialog.show({message : "res" + SignMessageBlob.data}); + }); }); }); }); -}); +} ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let keyGenPromise = rsaGenerator.generateKeyPair(); -keyGenPromise.then( keyPair => { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - return signer.init(priKey); -}).then(() => { - return signer.update(input1); -}).then(() => { - return signer.sign(input2); -}).then(dataBlob => { - SignMessageBlob = dataBlob; - console.info("sign output is " + SignMessageBlob.data); -}); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessagePromise() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let keyGenPromise = rsaGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + return signer.init(priKey); + }).then(() => { + return signer.update(input1); // Add the first segment of the data. + }).then(() => { + return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. + }).then(dataBlob => { + SignMessageBlob = dataBlob; + console.info("sign output is " + SignMessageBlob.data); + AlertDialog.show({message : "output" + SignMessageBlob.data}); + }); +} ``` ## cryptoFramework.createVerify @@ -1897,9 +2218,9 @@ Creates a **Verify** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Verify | **Verify** instance created.| +| Type | Description | +| ------ | ---------------------------------- | +| Verify | **Verify** instance created.| **Example** @@ -1908,11 +2229,27 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); -let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") ``` + ## Verify Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**. +The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. +The signature verification mode is determined in **createVerify()**, and key is set by **init()**. +If the data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**. +If the data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data. +If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to be used for signature verification.| + + ### init @@ -1924,12 +2261,13 @@ Initializes the **Verify** instance using a public key. This API uses an asynchr **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes| Public key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init + init(pubKey : PubKey) : Promise\ Initializes the **Verify** instance using a public key. This API uses a promise to return the result. @@ -1938,14 +2276,14 @@ Initializes the **Verify** instance using a public key. This API uses a promise **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes|Public key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1958,10 +2296,10 @@ Updates the data for signature verification. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1975,12 +2313,12 @@ Updates the data for signature verification. This API uses a promise to return t | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### verify @@ -1993,11 +2331,11 @@ Verifies the signature. This API uses an asynchronous callback to return the res **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| signatureData | DataBlob | Yes | Signature data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### verify @@ -2009,25 +2347,30 @@ Verifies the signature. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in.| -| signatureData | DataBlob| Yes| Signature data.| +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| ----------------- | ---------------------------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); verifyer.init(globalKeyPair.pubKey, function (err, data) { verifyer.update(input1, function(err, data) { - verifyer.verify(input2, SignMessageBlob, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { console.info("verify result is " + data); }) }); @@ -2035,19 +2378,25 @@ verifyer.init(globalKeyPair.pubKey, function (err, data) { ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. verifyInitPromise.then(() => { return verifyer.update(input1); }).then(() => { - return verifyer.verify(input2, SignMessageBlob); + return verifyer.verify(input2, signMessageBlob); }).then(res => { console.log("Verify result is " + res); }); ``` + ## cryptoFramework.createKeyAgreement createKeyAgreement(algName : string) : KeyAgreement @@ -2058,15 +2407,15 @@ Creates a **KeyAgreement** instance. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------- | +| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.| **Return value** -| Type| Description | -| ---- | ------------------------------ | -| KeyAgreement | **KeyAgreement** instance created.| +| Type | Description | +| ------------ | ---------------------------------------- | +| KeyAgreement | **KeyAgreement** instance created.| **Example** @@ -2079,7 +2428,15 @@ let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); ## KeyAgreement -Provides APIs for key agreement operations. Before using any API of the **keyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. +Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm used for key agreement.| ### generateSecret @@ -2091,13 +2448,14 @@ Generates a shared secret. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret generated. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret.| ### generateSecret + generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\ Generates a shared secret. This API uses a promise to return the result. @@ -2106,21 +2464,23 @@ Generates a shared secret. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| **Return value** -| Type | Description | -| --------------- | ------------ | -| Promise\ | Promise used to return the shared secret generated. | +| Type | Description | +| ------------------ | -------- | +| Promise\ | Promise used to return the shared secret.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { if (err) { @@ -2132,9 +2492,11 @@ keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); keyAgreementPromise.then((secret) => { diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index ccc1f7b4e26c0cbc6556f2ea767c5601ac3a477e..4cdef60fa628733e5be8cc6df783548b7b5bcd07 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,4 +1,4 @@ -# @ohos.data.dataShareResultSet +# @ohos.data.dataShareResultSet (DataShare Result Set) The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index 779d30c40263eecd1a8ecf70209a95008aa228dd..f41bea4da45a6f6c0224e126f698d45d274e25dc 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,4 +1,4 @@ -# DataAbilityPredicates +# @ohos.data.dataAbility (DataAbility Predicates) **DataAbility** provides APIs for creating predicates, which implement different query methods for relational database (RDB) stores. @@ -23,16 +23,16 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of a database table.| - | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a database table.| +| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | **Return value** - | Type| Description| - | -------- | -------- | - | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| +| Type| Description| +| -------- | -------- | +| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -56,16 +56,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -83,16 +83,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -110,9 +110,9 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** @@ -135,9 +135,9 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** @@ -160,9 +160,9 @@ Adds the OR condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** @@ -182,9 +182,9 @@ Adds the AND condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** @@ -204,16 +204,16 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -231,16 +231,16 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -258,16 +258,16 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -285,15 +285,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -311,15 +311,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -337,16 +337,16 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -364,16 +364,16 @@ Sets a **DataAbilityPredicates** object to match the specified string. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -391,17 +391,17 @@ Sets a **DataAbilityPredicates** object to match a field whose data type is **Va **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -419,17 +419,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -447,16 +447,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -474,16 +474,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -501,16 +501,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -528,16 +528,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -555,15 +555,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -581,15 +581,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -607,9 +607,9 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| **Example** @@ -627,15 +627,15 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Maximum number of records.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Maximum number of records.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| **Example** @@ -653,15 +653,15 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| **Example** @@ -680,15 +680,15 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fields | Array<string> | Yes| Names of columns to group.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fields | Array<string> | Yes| Names of columns to group.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| **Example** @@ -706,15 +706,15 @@ Sets a **DataAbilityPredicates** object to specify the index column. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | indexName | string | Yes| Name of the index column.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| indexName | string | Yes| Name of the index column.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| **Example** @@ -732,17 +732,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -760,16 +760,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index 2a476aaf33cc927b8c0ec5c392a083b6b42c8f80..82a333b14b2ea90e92540ee31142ea884c7f2593 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,4 +1,4 @@ -# @ohos.data.dataShare +# @ohos.data.dataShare (DataShare) The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 4d2df994d96b7b0986782774e9d531a12750cac7..78d896c54a2f1c1674825ddaff66088634129596 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,4 +1,4 @@ -# Data Share Predicates +# @ohos.data.dataSharePredicates (DataShare Predicates) You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. @@ -35,7 +35,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -65,7 +65,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -439,8 +439,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -470,8 +470,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -501,7 +501,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -531,7 +531,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -561,7 +561,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -591,7 +591,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -790,7 +790,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes| Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** @@ -820,7 +820,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 6f24aa3255f0340e0ad8ef248ae25d62092e0774..d3285fa80427790ba723737e20bc5559f0cc85ab 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,8 +1,8 @@ -# Distributed Data Object +# @ohos.data.distributedDataObject (Distributed Data Object) The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. -> **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. @@ -13,32 +13,58 @@ The **distributedDataObject** module provides basic data object management, incl import distributedObject from '@ohos.data.distributedDataObject'; ``` -## distributedDataObject.createDistributedObject - -createDistributedObject(source: object): DistributedObject +## distributedObject.create9+ +create(context: Context, source: object): DistributedObjectV9 Creates a distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | source | object | Yes| Attribute of the distributed data object to create.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| source | object | Yes| Attributes of the distributed data object.| **Return value** + | Type| Description| | -------- | -------- | -| [DistributedObject](#distributedobject) | Distributed data object created.| +| [DistributedObjectV9](#distributedobjectv9) | Distributed data object created.| **Example** + +FA model: + ```js +// Import the module. import distributedObject from '@ohos.data.distributedDataObject'; -// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); ``` +Stage model: + +```ts +// Import the module. +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +``` ## distributedObject.genSessionId @@ -49,14 +75,16 @@ Creates a random session ID. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Return value** - | Type| Description| - | -------- | -------- | - | string | Session ID created.| + +| Type| Description| +| -------- | -------- | +| string | Session ID created.| **Example** + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var sessionId = distributedObject.genSessionId(); +let sessionId = distributedObject.genSessionId(); ``` ## SaveSuccessResponse9+ @@ -65,11 +93,11 @@ Called when the **Save()** API is successfully called. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -| Name| Type| Description| -| -------- | -------- | -------- | -| sessionId | string | Unique ID for multi-device collaboration.| -| version | number |Version of the distributed data object saved.| -| deviceId | string | ID of the device where the distributed data object is stored. The default value is **local**, which identifies a local device. You can set it as required.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | Yes| Unique ID for multi-device collaboration.| +| version | number | Yes| Version of the distributed data object saved.| +| deviceId | string | Yes| ID of the device where the distributed data object is stored. The default value is **local**, which identifies a local device. You can set it as required.| ## RevokeSaveSuccessResponse9+ @@ -77,17 +105,144 @@ Called when the **revokeSave()** API is successfully called. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -| Name| Type| Description| -| -------- | -------- | -------- | -| sessionId | string | Unique ID for multi-device collaboration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | Yes| Unique ID for multi-device collaboration.| -## DistributedObject +## DistributedObjectV9 -Represents a distributed data object. +Provides APIs for managing a distributed data object. -### setSessionId +### setSessionId9+ -setSessionId(sessionId?: string): boolean +setSessionId(sessionId: string, callback: AsyncCallback<void>): void + +Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | Yes| ID of a distributed data object on a trusted network.| +| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the session ID is successfully set.| + +**Error codes** + + For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md). + +| ID| Error Message| +| -------- | -------- | +| 15400001 | Failed to create the in-memory database.| + +**Example** + +FA model: + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +``` +Stage model: + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +``` + +### setSessionId9+ + +setSessionId(callback: AsyncCallback<void>): void + +Exits all joined sessions. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.| + +**Error codes** + + For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md). + +| ID| Error Message| +| -------- | -------- | +| 15400001 | Failed to create the in-memory database.| + +**Example** + +FA model: + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +// Exit the distributed network. +g_object.setSessionId(() => { + console.log("leave all lession."); +}); +``` +Stage model: + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId(), ()=>{ + console.log("join session"); +}); +// Exit the distributed network. +g_object.setSessionId(() => { + console.log("leave all lession."); +}); +``` + +### setSessionId9+ + +setSessionId(sessionId?: string): Promise<void> Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. @@ -97,46 +252,100 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + + For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md). + +| ID| Error Message| +| -------- | -------- | +| 15400001 | Failed to create the in-memory database.| **Example** +FA model: + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // Add g_object to the distributed network. -g_object.setSessionId(distributedObject.genSessionId()); -// Remove g_object from the distributed network. -g_object.setSessionId(""); +g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ + console.log("join session."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); +// Exit the distributed network. +g_object.setSessionId().then (()=>{ + console.log("leave all lession."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); ``` +Stage model: +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ + console.info("join session."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); +// Exit the distributed network. +g_object.setSessionId().then (()=>{ + console.log("leave all lession."); + }).catch((error)=>{ + console.info("error:" + error.code + error.message); +}); +``` -### on('change') +### on('change')9+ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void -Subscribes to the changes of this distributed data object. +Subscribes to data changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** + +FA model: + ```js -import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.changeCallback = (sessionId, changeData) => { console.info("change" + sessionId); if (changeData != null && changeData != undefined) { @@ -148,81 +357,189 @@ globalThis.changeCallback = (sessionId, changeData) => { g_object.on("change", globalThis.changeCallback); ``` -### off('change') +Stage model: + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); + } +} +g_object.on("change", globalThis.changeCallback); +``` + +### off('change')9+ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void -Unsubscribes from the changes of this distributed data object. +Unsubscribes from the data changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes. | +| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** + +FA model: + ```js -import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // Unregister the specified data change callback. g_object.off("change", globalThis.changeCallback); // Unregister all data change callbacks. g_object.off("change"); ``` -### on('status') +Stage model: + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Unregister the specified data change callback. +g_object.off("change", globalThis.changeCallback); +// Unregister all data change callbacks. +g_object.off("change"); +``` + +### on('status')9+ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void -Subscribes to the status change (online or offline) of this distributed data object. +Subscribes to statue changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** + +FA model: + ```js import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); g_object.on("status", globalThis.statusCallback); ``` -### off('status') +Stage model: -off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +g_object.on("status", globalThis.statusCallback); +``` +### off('status')9+ + +off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void -Unsubscribes from the status change (online or offline) of this distributed data object. +Unsubscribes from the status change of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| **Example** + +FA model: + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } -// Unsubscribe from the specified status change callback for the distributed data object. +// Unregister the specified status change callback. g_object.off("status",globalThis.statusCallback); -// Unsubscribe from all status change callbacks for the distributed data object. +// Unregister all status change callbacks. +g_object.off("status"); +``` + +Stage model: + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +// Unregister the specified status change callback. +g_object.off("status",globalThis.statusCallback); +// Unregister all status change callbacks. g_object.off("status"); ``` @@ -243,18 +560,45 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| - | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| +| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** -```js + +FA model: +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local", (result) => { + console.log("save callback"); + console.info("save sessionId: " + result.sessionId); + console.info("save version: " + result.version); + console.info("save deviceId: " + result.deviceId); +}); +``` + +Stage model: +```ts import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); -g_object.save("local", (status, result)=>{ - console.log("save status = " + status); +g_object.save("local", (result) => { console.log("save callback"); console.info("save sessionId: " + result.sessionId); console.info("save version: " + result.version); @@ -279,28 +623,55 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Type| Description| +| -------- | -------- | +| Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); -g_object.save("local").then((result)=>{ +g_object.save("local").then((result) => { console.log("save callback"); console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}, ()=>{ +}, () => { + console.error("save failed"); +}); +``` + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} +let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local").then((result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, () => { console.error("save failed"); }); ``` @@ -317,18 +688,62 @@ If the object is stored on another device, the data on the local device will be **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** +FA model: + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); -g_object.revokeSave((result, data) =>{ +// Save data for persistence. +g_object.save("local", (result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}); +// Delete the persistence data. +g_object.revokeSave((result) => { console.log("revokeSave callback"); + console.log("revokeSave sessionId " + result.sessionId); +}); +``` + +Stage model: + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +// Save data for persistence. +g_object.save("local", (result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}); +// Delete the persistence data. +g_object.revokeSave((result) => { + console.log("revokeSave callback"); + console.log("revokeSave sessionId " + result.sessionId); }); ``` @@ -345,20 +760,272 @@ If the object is stored on another device, the data on the local device will be **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Type| Description| +| -------- | -------- | +| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** -```js +FA model: + +```ts import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); -g_object.revokeSave().then((result)=>{ +// Save data for persistence. +g_object.save("local").then((result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, () => { + console.error("save failed"); +}); +// Delete the persistence data. +g_object.revokeSave().then((result) => { + console.log("revokeSave callback"); + console.log("sessionId" + result.sessionId); +}, () => { + console.error("revokeSave failed"); +}); +``` + +Stage model: + +```ts +import distributedObject from '@ohos.data.distributedDataObject'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Obtain the context. +let context; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + context = this.context + } +} +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local").then((result) => { + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, () => { + console.error("save failed"); +}); + +// Delete the persistence data. +g_object.revokeSave().then((result) => { console.log("revokeSave callback"); console.log("sessionId" + result.sessionId); -}, ()=>{ +}, () => { console.error("revokeSave failed"); }); ``` + +## distributedObject.createDistributedObject(deprecated) + +createDistributedObject(source: object): DistributedObject + + +Creates a distributed data object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use **distributedObject.create**. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | object | Yes| Attributes of the distributed data object.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [DistributedObject](#distributedobjectdeprecated) | Distributed data object created.| + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +``` + +## DistributedObject(deprecated) + +Provides APIs for managing a distributed data object. + +### setSessionId(deprecated) + +setSessionId(sessionId?: string): boolean + +Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setSessionId](#setsessionid9). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId()); +// Remove g_object from the distributed network. +g_object.setSessionId(""); +``` + +### on('change')(deprecated) + +on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void + +Subscribes to data changes of this distributed data object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('change')](#onchange9). + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); + } +} +g_object.on("change", globalThis.changeCallback); +``` + +### off('change')(deprecated) + +off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void + +Unsubscribes from the data changes of this distributed data object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('change')](#offchange9). + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes. | +| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Unregister the specified data change callback. +g_object.off("change", globalThis.changeCallback); +// Unregister all data change callbacks. +g_object.off("change"); +``` + +### on('status')(deprecated) + +on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void + +Subscribes to status changes of this distributed data object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('status')](#onstatus9). + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +g_object.on("status", globalThis.statusCallback); +``` + +### off('status')(deprecated) + +off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void + +Unsubscribes from the status change of this distributed data object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('status')](#offstatus9) instead. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object. | +| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| + + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +// Unregister the specified status change callback. +g_object.off("status",globalThis.statusCallback); +// Unregister all status change callbacks. +g_object.off("status"); +``` diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index cad744cb266c3c5712de9d441fe0a56a1fc4ccbc..5ba79b73ed0370258a87975c1a4ee576816964b4 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,4 +1,4 @@ -# Preferences +# @ohos.data.preferences (Preferences) The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. @@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| | callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| @@ -103,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| **Return value** @@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| @@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** @@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| @@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** @@ -497,7 +497,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 89ebac58ef1f970c8c97c00bedb0fe5552491115..bcebd097f34c1337e5826e866302af9626696a32 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,4 +1,4 @@ -# @ohos.data.rdb +# @ohos.data.rdb (RDB) The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. diff --git a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md index 846f3f15481d700da9d738857bc217c64cbe6ac9..009ff71b091c7d91a92d92364450316e3aeecfa2 100644 --- a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md +++ b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md @@ -1,4 +1,4 @@ -# @ohos.data.ValuesBucket +# @ohos.data.ValuesBucket (Value Bucket) The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. @@ -34,6 +34,6 @@ Defines the types of the key and value in a KV pair. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core -| Key Type | Value Type | -| ------------- | --------------------------------------------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | +| Key Type | Value Type | +| ------------- | --------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index dd19bdb98680553ff3f66b3484ab95aa97b5b52d..ad8ab9f54dfd43754e6e00cdfbe5ba5c9e1d39c4 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -297,9 +297,9 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -308,9 +308,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -318,9 +318,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -365,9 +365,9 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -377,9 +377,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -424,9 +424,9 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -436,9 +436,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index e295a1cf9c72875727705c131b4342868daff54a..d227b545aa9f5ad3b719b2da86800cab6ccc5084 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -1,7 +1,6 @@ # @ohos.util.Deque (Linear Container Deque) > **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. Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects: @@ -41,7 +40,7 @@ A constructor used to create a **Deque** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -69,7 +68,7 @@ Inserts an element at the front of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -104,7 +103,7 @@ Inserts an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -145,7 +144,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -172,11 +171,11 @@ Removes the first element of this container. | Type| Description| | -------- | -------- | -| T | Element removed.| +| T | First element removed.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -206,11 +205,11 @@ Removes the last element of this container. | Type| Description| | -------- | -------- | -| T | Element removed.| +| T | Last element removed.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -254,7 +253,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -289,7 +288,7 @@ Obtains the first element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -322,7 +321,7 @@ Obtains the last element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -355,7 +354,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 21f8d30deacbcacd95e5da17012a3ba3c184c834..15f5d8bdbc7796954b7c7129f3ab43321bba5555 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,4 +1,4 @@ -# @ohos.display +# @ohos.display (Display) The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. @@ -189,7 +189,7 @@ Checks whether there is a visible privacy window on a display. The privacy windo | Type | Description | | -------------------------------- |-----------------------------------------------------------------------| -|boolean | Whether there is a visible privacy window on the display. The value **true** means that there is a visible privacy window on the display, and **false** means the opposite. | +|boolean | Whether there is a visible privacy window on the display. The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index 772a7372c276270eaa9a2e2d63d9eec009b06e58..23ee9ed06ec230543ed4ee8594954bc3d72871cf 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -1,4 +1,4 @@ -# Distributed Data Management +# @ohos.data.distributedData (Distributed Data Management) The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. @@ -119,7 +119,7 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | userInfo | [UserInfo](#userinfo) | Yes | User information.| -| bundleName | string | Yes | Bundle name.| +| bundleName | string | Yes | Bundle name of the caller.| ## UserInfo diff --git a/en/application-dev/reference/apis/js-apis-distributedBundle.md b/en/application-dev/reference/apis/js-apis-distributedBundleManager.md similarity index 80% rename from en/application-dev/reference/apis/js-apis-distributedBundle.md rename to en/application-dev/reference/apis/js-apis-distributedBundleManager.md index 2ddd4b91388067d0b301f8d7ba26bbf748eb15cb..71e153396ecfc529530cf2e9fae3869bd398a0fa 100644 --- a/en/application-dev/reference/apis/js-apis-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-distributedBundleManager.md @@ -1,4 +1,4 @@ -# @ohos.bundle.distributedBundle +# @ohos.bundle.distributedBundleManager (distributedBundleManager) The **distributedBundle** module provides APIs for managing distributed bundles. @@ -11,10 +11,10 @@ The **distributedBundle** module provides APIs for managing distributed bundles. ## Modules to Import ``` -import distributedBundle from '@ohos.bundle.distributedBundle'; +import distributedBundle from '@ohos.bundle.distributedBundleManager'; ``` -## System Capability +## System Capabilities SystemCapability.BundleManager.DistributedBundleFramework @@ -43,7 +43,7 @@ Obtains information about the remote ability that matches the given element name | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | -| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -64,16 +64,16 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -99,7 +99,7 @@ Obtains information about the remote ability that matches the given element name | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.| +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned.| **Error codes** @@ -120,14 +120,14 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }).then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -135,7 +135,7 @@ try { getRemoteAbilityInfo(elementNames: Array\, callback: AsyncCallback\>): void; -Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result. +Obtains information about the remote abilities that match the given element names. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -148,7 +148,7 @@ Obtains information about remote abilities that match the given element names. T | Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -170,22 +170,22 @@ try { { deviceId: '1', bundleName: 'com.example.application1', - abilityName: 'MainAbility1' + abilityName: 'EntryAbility1' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ], (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -193,7 +193,7 @@ try { getRemoteAbilityInfo(elementNames: Array\): Promise\>; -Obtains information about remote abilities that match the given element names and locales. This API uses a promise to return the result. +Obtains information about the remote abilities that match the given element names. This API uses a promise to return the result. **System API**: This is a system API. @@ -211,7 +211,7 @@ Obtains information about remote abilities that match the given element names an | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.| +| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned.| **Error codes** @@ -233,20 +233,20 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ]).then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -268,7 +268,7 @@ Obtains information about the remote ability that matches the given element name | ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | | locale | string |Yes| Target locale.| -| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -289,16 +289,16 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, 'zh-Hans-CN', (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -325,7 +325,7 @@ Obtains information about the remote ability that matches the given element name | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.| +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned.| **Error codes** @@ -346,14 +346,14 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, 'zh-Hans-CN').then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -361,7 +361,7 @@ try { getRemoteAbilityInfo(elementNames: Array\, locale: string, callback: AsyncCallback\>): void; -Obtains information about remote abilities that match the given element names and locales. This API uses an asynchronous callback to return the result. +Obtains information about the remote abilities that match the given element names and locale. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -375,7 +375,7 @@ Obtains information about remote abilities that match the given element names an | ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | | locale | string |Yes| Target locale.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -397,22 +397,22 @@ try { { deviceId: '1', bundleName: 'com.example.application1', - abilityName: 'MainAbility1' + abilityName: 'EntryAbility1' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ], 'zh-Hans-CN', (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -420,7 +420,7 @@ try { getRemoteAbilityInfo(elementNames: Array\, locale: string): Promise\>; -Obtains information about remote abilities that match the given element names and locales. This API uses a promise to return the result. +Obtains information about the remote abilities that match the given element names and locale. This API uses a promise to return the result. **System API**: This is a system API. @@ -439,7 +439,7 @@ Obtains information about remote abilities that match the given element names an | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.| +| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned.| **Error codes** @@ -461,19 +461,19 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ], 'zh-Hans-CN').then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md index 81308054abd5ef5f55ad9d4c78b52f427c16792c..440da83fd42e403b1ddd4d6ad7f20d02b58b5ba4 100644 --- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -1,4 +1,4 @@ -# Distributed KV Store +# @ohos.data.distributedKVStore (Distributed KV Store) The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. @@ -10,7 +10,7 @@ The **distributedKVStore** module provides the following functions: - [SingleKVStore](#singlekvstore): provides APIs for querying data in single KV stores and synchronizing data. The single KV stores manage data without distinguishing devices. - [DeviceKVStore](#devicekvstore): provides APIs for querying in device KV stores and synchronizing data. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. -> **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -248,79 +248,9 @@ try { ## distributedKVStore.createKVManager -createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void +createKVManager(config: KVManagerConfig): KVManager -Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ----------------------------------------------------------- | -| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name of the invoker and the context of the application.| -| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created. | - -**Example** - -Stage model: - -```js -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - } - try { - distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); - } catch (e) { - console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); - } - } -} -``` - -FA model: - -```js -import featureAbility from '@ohos.ability.featureAbility' -let kvManager; -let context = featureAbility.getContext() -const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', -} -try { - distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); -} catch (e) { - console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); -} -``` - -## distributedKVStore.createKVManager - -createKVManager(config: KVManagerConfig): Promise<KVManager> - -Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. +Creates a **KVManager** instance to manage KV stores. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -328,13 +258,13 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | --------------------------------------------------------- | -| config | [KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name and user information of the caller.| **Return value** | Type | Description | | -------------------------------------- | ------------------------------------------ | -| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| +| [KVManager](#kvmanager) | **KVManager** instance created.| **Example** @@ -352,12 +282,8 @@ export default class MyAbilityStage extends AbilityStage { bundleName: 'com.example.datamanagertest', } try { - distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; - }).catch((err) => { - console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); - }); + kvManager = distributedKVStore.createKVManager(kvManagerConfig); + console.log("Created KVManager successfully"); } catch (e) { console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); } @@ -376,12 +302,8 @@ const kvManagerConfig = { bundleName: 'com.example.datamanagertest', } try { - distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; - }).catch((err) => { - console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); - }); + kvManager = distributedKVStore.createKVManager(kvManagerConfig); + console.log("Created KVManager successfully"); } catch (e) { console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); } @@ -617,7 +539,7 @@ Deletes a distributed KV store. This API uses an asynchronous callback to return For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message**| +| ID| **Error Message**| | ------------ | ------------ | | 15100004 | Not found. | @@ -681,7 +603,7 @@ Deletes a distributed KV store. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message**| +| ID| **Error Message**| | ------------ | ------------ | | 15100004 | Not found. | @@ -799,7 +721,7 @@ Subscribes to service status changes. | Name | Type | Mandatory| Description | | ------------- | -------------------- | ---- | ------------------------------------------------------------ | | event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| -| deathCallback | Callback<void> | Yes | Callback invoked to return the result. | +| deathCallback | Callback<void> | Yes | Callback invoked to service status changes. | **Example** @@ -2185,7 +2107,7 @@ Adds a KV pair of the specified type to this KV store. This API uses an asynchro For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2234,7 +2156,7 @@ Adds a KV pair of the specified type to this KV store. This API uses a promise t For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2275,7 +2197,7 @@ Batch inserts KV pairs to this single KV store. This API uses an asynchronous ca For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2342,7 +2264,7 @@ Batch inserts KV pairs to this single KV store. This API uses a promise to retur For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2395,14 +2317,14 @@ Writes data to this single KV store. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write.| +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2447,7 +2369,7 @@ Write data to this KV store. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write. | +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write. | **Return value** @@ -2459,7 +2381,7 @@ Write data to this KV store. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2507,7 +2429,7 @@ Deletes a KV pair from this KV store. This API uses an asynchronous callback to For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2562,7 +2484,7 @@ Deletes a KV pair from this KV store. This API uses a promise to return the resu For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2610,7 +2532,7 @@ Deletes KV pairs from this KV store. This API uses an asynchronous callback to r For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2660,7 +2582,7 @@ Deletes KV pairs from this KV store. This API uses a promise to return the resul For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2709,7 +2631,7 @@ Batch deletes KV pairs from this single KV store. This API uses an asynchronous For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2777,7 +2699,7 @@ Batch deletes KV pairs from this single KV store. This API uses a promise to ret For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2836,7 +2758,7 @@ Deletes data of a device. This API uses an asynchronous callback to return the r For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -2890,7 +2812,7 @@ Deletes data of a device. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -2941,7 +2863,7 @@ Obtains the value of the specified key. This API uses an asynchronous callback t For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -2997,7 +2919,7 @@ Obtains the value of the specified key. This API uses a promise to return the re For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -3044,7 +2966,7 @@ Obtains all KV pairs that match the specified key prefix. This API uses an async For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3112,7 +3034,7 @@ Obtains all KV pairs that match the specified key prefix. This API uses a promis For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3170,7 +3092,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3237,7 +3159,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses a For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3298,7 +3220,7 @@ Obtains a result set with the specified prefix from this single KV store. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3372,7 +3294,7 @@ Obtains a result set with the specified prefix from this single KV store. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3435,7 +3357,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3503,7 +3425,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3565,7 +3487,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3626,7 +3548,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3745,7 +3667,7 @@ Obtains the number of results that matches the specified **Query** object. This For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3808,7 +3730,7 @@ Obtains the number of results that matches the specified **Query** object. This For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3866,7 +3788,7 @@ Backs up a distributed KV store. This API uses an asynchronous callback to retur For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -3912,7 +3834,7 @@ Backs up an RDB store. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -3951,7 +3873,7 @@ Restores a distributed KV store from a database file. This API uses an asynchron For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -3997,7 +3919,7 @@ Restores a distributed KV store from a database file. This API uses a promise to For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4104,7 +4026,7 @@ Starts the transaction in this single KV store. This API uses an asynchronous ca For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4172,7 +4094,7 @@ Starts the transaction in this single KV store. This API uses a promise to retur For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4214,7 +4136,7 @@ Commits the transaction in this single KV store. This API uses an asynchronous c For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4253,7 +4175,7 @@ Commits the transaction in this single KV store. This API uses a promise to retu For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4290,7 +4212,7 @@ Rolls back the transaction in this single KV store. This API uses an asynchronou For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4329,7 +4251,7 @@ Rolls back the transaction in this single KV store. This API uses a promise to r For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4579,7 +4501,7 @@ Synchronizes the KV store manually. For details about the synchronization modes For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | ------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -4632,7 +4554,7 @@ Synchronizes the KV store manually. This API returns the result synchronously. F For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | ------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -4679,13 +4601,13 @@ Subscribes to data changes of the specified type. | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | | event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| | type | [SubscribeType](#subscribetype) | Yes | Type of data change. | -| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | +| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the data change. | **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100001 | Over max subscribe limits. | | 15100005 | Database or result set already closed. | @@ -4716,7 +4638,7 @@ Subscribes to synchronization complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | | event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return the synchronization result. | +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return the synchronization complete event. | **Example** @@ -4751,13 +4673,13 @@ Unsubscribes from data changes. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | | event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| -| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback invoked to return the result. | +| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback for data changes. | **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4805,7 +4727,7 @@ Unsubscribes from synchronization complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | | event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback | Callback<Array<[string, number]>> | No | Callback used to return the synchronization result. | +| syncCallback | Callback<Array<[string, number]>> | No | Callback for the synchronization complete event. | **Example** @@ -4856,7 +4778,7 @@ Obtains the security level of this KV store. This API uses an asynchronous callb For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4895,7 +4817,7 @@ Obtains the security level of this KV store. This API uses a promise to return t For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4943,7 +4865,7 @@ Obtains the value of the specified key for this device. This API uses an asynchr For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -4999,7 +4921,7 @@ Obtains the value of the specified key for this device. This API uses a promise For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -5047,7 +4969,7 @@ Obtains a string value that matches the specified device ID and key. This API us For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -5104,7 +5026,7 @@ Obtains a string value that matches the specified device ID and key. This API us For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -5151,7 +5073,7 @@ Obtains all KV pairs that match the specified key prefix for this device. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5219,7 +5141,7 @@ Obtains all KV pairs that match the specified key prefix for this device. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5278,7 +5200,7 @@ Obtains all KV pairs that match the specified device ID and key prefix. This API For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5347,7 +5269,7 @@ Obtains all KV pairs that match the specified device ID and key prefix. This API For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5402,13 +5324,13 @@ Obtains all KV pairs that match the specified **Query** object for this device. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ----------------------------------------------------- | | query | [Query](query) | Yes | Key prefix to match. | -| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs obtained.| +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5475,7 +5397,7 @@ Obtains all KV pairs that match the specified **Query** object for this device. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5537,7 +5459,7 @@ Obtains the KV pairs that match the specified device ID and **Query** object. Th For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5611,7 +5533,7 @@ Obtains the KV pairs that match the specified device ID and **Query** object. Th For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5673,7 +5595,7 @@ Obtains a result set with the specified prefix for this device. This API uses an For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5747,7 +5669,7 @@ Obtains a result set with the specified prefix for this device. This API uses a For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5811,7 +5733,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5867,7 +5789,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5914,7 +5836,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5991,7 +5913,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6064,7 +5986,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6130,7 +6052,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6200,7 +6122,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6261,7 +6183,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6314,7 +6236,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6376,7 +6298,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6425,7 +6347,7 @@ Obtains the number of results that match the specified **Query** object for this For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6488,7 +6410,7 @@ Obtains the number of results that match the specified **Query** object for this For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6547,7 +6469,7 @@ Obtains the number of results that matches the specified device ID and **Query** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6616,7 +6538,7 @@ Obtains the number of results that matches the specified device ID and **Query** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | diff --git a/en/application-dev/reference/apis/js-apis-effectKit.md b/en/application-dev/reference/apis/js-apis-effectKit.md index d44645af1980b3a963bd73878dc040db60abe205..7826d164b3c3f9cfbcde07dd9989b1fce3021e4b 100644 --- a/en/application-dev/reference/apis/js-apis-effectKit.md +++ b/en/application-dev/reference/apis/js-apis-effectKit.md @@ -1,4 +1,4 @@ -# Image Effect +# @ohos.effectKit (Image Effects) The **EffectKit** module provides basic image processing capabilities, including brightness adjustment, blurring, grayscale adjustment, and color picker. diff --git a/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md index 173baa4aabaea2fc2c9846e7fcfc4cc35f47f880..0fd78714ed4bdf8a177fa46a814c16107e05b3ff 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md @@ -1,4 +1,4 @@ -# @ohos.enterprise.adminManager +# @ohos.enterprise.adminManager (Enterprise Device Management) The **adminManager** module provides enterprise device management capabilities so that devices have the custom capabilities required in enterprise settings. @@ -48,7 +48,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -100,7 +100,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -157,7 +157,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -324,7 +324,7 @@ Disables a device super administrator application based on the specified bundle For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). -| ID| Error Message | +| ID| Error Message | | ------- | ----------------------------------------------------------------- | | 9200005 | failed to disable the administrator application of the device. | @@ -582,7 +582,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -635,7 +635,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -676,7 +676,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; adminManager.getEnterpriseInfo(wantTemp, (error, result) => { if (error != null) { @@ -723,7 +723,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; adminManager.getEnterpriseInfo(wantTemp).then((result) => { console.log(result.name); diff --git a/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md b/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md index 4953081a07f6d1df20c441f669ed1b507e488dc1..5442a147c0a45781ccbdeee3ede23b8ac3d3d87c 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @@ -1,4 +1,4 @@ -# @ohos.enterprise.deviceInfo +# @ohos.enterprise.deviceInfo (Device Information Management) The **deviceInfo** module provides APIs for enterprise device information management, including the API for obtaining device serial numbers. These APIs can only be called by device administrator applications. @@ -45,7 +45,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceSerial(wantTemp, (error, result) => { if (error != null) { @@ -94,7 +94,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceSerial(wantTemp).then((result) => { console.log(result); @@ -136,7 +136,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDisplayVersion(wantTemp, (error, result) => { if (error != null) { @@ -185,7 +185,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDisplayVersion(wantTemp).then((result) => { console.log(result); @@ -227,7 +227,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceName(wantTemp, (error, result) => { if (error != null) { @@ -276,7 +276,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceName(wantTemp).then((result) => { console.log(result); diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index 2a6c9e6c8670b70ce80b59b6eea5cf5defa98234..dba3fb3f36ce7a0043738ff1c7bce26f22ae4973 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -1,8 +1,7 @@ -# @ohos.faultLogger (Fault Logger) +# @ohos.faultLogger (FaultLogger) -The **faultLogger** module implements fault logging functions. - -> **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 diff --git a/en/application-dev/reference/apis/js-apis-freeInstall.md b/en/application-dev/reference/apis/js-apis-freeInstall.md index 94ab3e8ac8cad4c8a41a4820741e595535f388a3..73d618e2f6eeed9df97b72dd4df8ba5839b1864c 100644 --- a/en/application-dev/reference/apis/js-apis-freeInstall.md +++ b/en/application-dev/reference/apis/js-apis-freeInstall.md @@ -1,4 +1,4 @@ -# @ohos.bundle.freeInstall +# @ohos.bundle.freeInstall (freeInstall) The **Bundle.freeInstall** module provides APIs for setting and obtaining installation-free information and APIs for obtaining **BundlePackInfo** and **DispatchInfo**. @@ -63,7 +63,7 @@ Sets an upgrade flag for a module. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **null**; otherwise, **err** is an error object.| @@ -113,7 +113,7 @@ Sets an upgrade flag for a module. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| @@ -166,7 +166,7 @@ Checks whether a module can be removed. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | --------------------------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the module can be removed, **true** is returned; otherwise, **false** is returned.| @@ -266,7 +266,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This | Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | bundleName | string | Yes | Bundle name. | -| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package. | +| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package. | | callback | AsyncCallback<[BundlePackInfo](js-apis-bundleManager-packInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **BundlePackInfo** object obtained; otherwise, **err** is an error object.| **Error codes** @@ -311,7 +311,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundleFlag**. This API | Name | Type | Mandatory| Description | | -------------- | --------------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 86b62bd76ff14cdd0aaa46d60f532b2b52220e4d..147ce8af9468e56116112b3af3c46e9a39527ab0 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -48,7 +48,7 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange). **Required permissions**: ohos.permission.LOCATION @@ -64,7 +64,6 @@ Registers a listener for location changes with a location request initiated. The | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| - **Example** ```ts @@ -83,7 +82,7 @@ off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange). **Required permissions**: ohos.permission.LOCATION @@ -117,7 +116,7 @@ on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationenabledchange). **Required permissions**: ohos.permission.LOCATION @@ -149,7 +148,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationenabledchange). **Required permissions**: ohos.permission.LOCATION @@ -183,6 +182,7 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca Registers a listener for cached GNSS location reports. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroncachedgnsslocationschange). @@ -218,6 +218,7 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati Unregisters the listener for cached GNSS location reports. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroffcachedgnsslocationschange). @@ -253,6 +254,7 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): voi Registers a listener for GNSS satellite status change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageronsatellitestatuschange). @@ -286,6 +288,7 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): v Unregisters the listener for GNSS satellite status change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffsatellitestatuschange). @@ -319,6 +322,7 @@ on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageronnmeamessage). @@ -352,6 +356,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageroffnmeamessage). @@ -386,6 +391,7 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanagerongnssfencestatuschange). @@ -435,6 +441,7 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffgnssfencestatuschange). @@ -483,7 +490,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L Obtains the current location. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). **Required permissions**: ohos.permission.LOCATION @@ -521,7 +528,7 @@ getCurrentLocation(callback: AsyncCallback<Location>): void Obtains the current location. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). **Required permissions**: ohos.permission.LOCATION @@ -556,7 +563,7 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> Obtains the current location. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation-2). **Required permissions**: ohos.permission.LOCATION @@ -593,7 +600,7 @@ getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). **Required permissions**: ohos.permission.LOCATION @@ -628,7 +635,7 @@ getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). **Required permissions**: ohos.permission.LOCATION @@ -658,7 +665,7 @@ isLocationEnabled(callback: AsyncCallback<boolean>): void Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). **Required permissions**: ohos.permission.LOCATION @@ -692,7 +699,7 @@ isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). **Required permissions**: ohos.permission.LOCATION @@ -721,7 +728,7 @@ requestEnableLocation(callback: AsyncCallback<boolean>): void Requests to enable the location service. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation). **Required permissions**: ohos.permission.LOCATION @@ -755,7 +762,7 @@ requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation-1). **Required permissions**: ohos.permission.LOCATION @@ -784,7 +791,7 @@ isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). **Required permissions**: ohos.permission.LOCATION @@ -818,7 +825,7 @@ isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). **Required permissions**: ohos.permission.LOCATION @@ -847,7 +854,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation). **Required permissions**: ohos.permission.LOCATION @@ -883,7 +890,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<Ge Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation-1). **Required permissions**: ohos.permission.LOCATION @@ -919,7 +926,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname). **Required permissions**: ohos.permission.LOCATION @@ -955,7 +962,7 @@ getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAd Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname-1). **Required permissions**: ohos.permission.LOCATION @@ -992,6 +999,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize). @@ -1027,6 +1035,7 @@ getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize-1). @@ -1057,6 +1066,7 @@ flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations). @@ -1092,6 +1102,7 @@ flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations-1). @@ -1122,6 +1133,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): v Sends an extended command to the location subsystem. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). @@ -1159,6 +1171,7 @@ sendCommand(command: LocationCommand): Promise<boolean>; Sends an extended command to the location subsystem. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). @@ -1193,7 +1206,7 @@ Sends an extended command to the location subsystem. Sets the priority of the location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestPriority](js-apis-geoLocationManager.md#locationrequestpriority). **Required permissions**: ohos.permission.LOCATION @@ -1212,7 +1225,7 @@ Sets the priority of the location request. Sets the scenario of the location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestScenario](js-apis-geoLocationManager.md#locationrequestscenario). **Required permissions**: ohos.permission.LOCATION @@ -1233,7 +1246,7 @@ Sets the priority of the location request. Enumerates error codes of the location service. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. **Required permissions**: ohos.permission.LOCATION @@ -1255,7 +1268,7 @@ Enumerates error codes of the location service. Defines a reverse geocoding request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.ReverseGeoCodeRequest](js-apis-geoLocationManager.md#reversegeocoderequest). **Required permissions**: ohos.permission.LOCATION @@ -1274,7 +1287,7 @@ Defines a reverse geocoding request. Defines a geocoding request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoCodeRequest](js-apis-geoLocationManager.md#geocoderequest). **Required permissions**: ohos.permission.LOCATION @@ -1296,7 +1309,7 @@ Defines a geocoding request. Defines a geographic location. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoAddress](js-apis-geoLocationManager.md#geoaddress). **Required permissions**: ohos.permission.LOCATION @@ -1329,7 +1342,7 @@ Defines a geographic location. Defines a location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequest](js-apis-geoLocationManager.md#locationrequest). **Required permissions**: ohos.permission.LOCATION @@ -1349,7 +1362,7 @@ Defines a location request. Defines the current location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#currentlocationrequest). **Required permissions**: ohos.permission.LOCATION @@ -1369,6 +1382,7 @@ Defines the current location request. Defines the satellite status information. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.SatelliteStatusInfo](js-apis-geoLocationManager.md#satellitestatusinfo). @@ -1391,6 +1405,7 @@ Defines the satellite status information. Represents a request for reporting cached GNSS locations. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.CachedGnssLocationsRequest](js-apis-geoLocationManager.md#cachedgnsslocationsrequest). @@ -1409,6 +1424,7 @@ Represents a request for reporting cached GNSS locations. Defines a GNSS geofence. Currently, only circular geofences are supported. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.Geofence](js-apis-geoLocationManager.md#geofence). @@ -1429,6 +1445,7 @@ Defines a GNSS geofence. Currently, only circular geofences are supported. Represents a GNSS geofencing request. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeofenceRequest](js-apis-geoLocationManager.md#geofencerequest). @@ -1448,6 +1465,7 @@ Represents a GNSS geofencing request. Defines the privacy statement type. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationPrivacyType](js-apis-geoLocationManager.md#locationprivacytype). @@ -1467,6 +1485,7 @@ Defines the privacy statement type. Defines an extended command. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationCommand](js-apis-geoLocationManager.md#locationcommand). @@ -1484,7 +1503,7 @@ Defines an extended command. Defines a location. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Location](js-apis-geoLocationManager.md#location). **Required permissions**: ohos.permission.LOCATION diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index d8da0f628f90a5090e9b2ccf0576b6ffb03ff69d..d39dbd1e6649359d5e6433fe11b0a2d68febf953 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -1,7 +1,6 @@ # @ohos.util.HashMap (Nonlinear Container HashMap) > **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. **HashMap** is a map implemented based on the array, linked list, and red-black tree. It provides efficient data query, insertion, and removal. The elements in a **HashMap** instance are mappings of key-value pairs. Each key must be unique and have only one value. @@ -43,7 +42,7 @@ A constructor used to create a **HashMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -72,7 +71,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -108,7 +107,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -146,7 +145,7 @@ Checks whether this container contains the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -184,7 +183,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -216,7 +215,7 @@ Adds all elements in a **HashMap** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -256,7 +255,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -292,7 +291,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -318,7 +317,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -350,7 +349,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -387,7 +386,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -431,7 +430,7 @@ Replaces an element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -470,7 +469,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -504,7 +503,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -542,14 +541,13 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The Symbol.iterator method cannot be bound. | **Example** - ```ts let hashMap = new HashMap(); hashMap.set("squirrel", 123); diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 2c52b1268a1ee4d61f3c89c26949823baa28e566..f2ece05248321395e2ca3f651ff32a462503d5c4 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -1,7 +1,6 @@ # @ohos.util.HashSet (Nonlinear Container HashSet) > **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. **HashSet** is implemented based on [HashMap](js-apis-hashmap.md). In **HashSet**, only the **value** object is processed. @@ -51,7 +50,7 @@ A constructor used to create a **HashSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -80,7 +79,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -116,7 +115,7 @@ Checks whether this container contains the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -154,7 +153,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -190,7 +189,7 @@ Removes an element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -216,7 +215,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -248,7 +247,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -293,7 +292,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -326,7 +325,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -364,7 +363,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 3a5687e9ee0b31e29450d72ad7f618a128b30050..1a6339e406c98eb2dfd81239da3e852bcb4afe47 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -1,8 +1,9 @@ # @ohos.hichecker (HiChecker) -The **hichecker** module is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. +The HiChecker module allows you to check issues that may be easily ignored during development of applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. -> **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. @@ -13,7 +14,7 @@ import hichecker from '@ohos.hichecker'; ``` -## Constant +## Constants Provides the constants of all rule types. @@ -26,10 +27,8 @@ Provides the constants of all rule types. | RULE_THREAD_CHECK_SLOW_PROCESS | bigint | Caution rule, which is programmed to detect whether any time-consuming function is invoked. | | RULE_CHECK_ABILITY_CONNECTION_LEAK | bigint | Caution rule, which is programmed to detect whether ability leakage has occurred. | - ## hichecker.addCheckRule9+ -## hichecker.addRule addCheckRule(rule: bigint): void Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. @@ -121,12 +120,10 @@ catch (err) { ## hichecker.addRule(deprecated) -## hichecker.addRule +addRule(rule: bigint): void > **NOTE**
This API is deprecated since API version 9. You are advised to use [hichecker.addCheckRule](#hicheckeraddcheckrule9) instead. -addRule(rule: bigint): void - Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. **System capability**: SystemCapability.HiviewDFX.HiChecker diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 2a75e1015411c92c75f58d32dc236283fd24f266..cda33f5434360fe5ca3f21f9f2c0a04ad5b50474 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,15 +1,18 @@ # @ohos.i18n (Internationalization) -The **i18n** module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. -The [intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. +The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. +The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities. + +> **NOTE** +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For details about the basic i18n capabilities, see [intl](js-apis-intl.md). -> **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 i18n from '@ohos.i18n'; +import I18n from '@ohos.i18n'; ``` @@ -39,16 +42,16 @@ Obtains the localized script for the specified country. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayCountry = i18n.System.getDisplayCountry("zh-CN", "en-GB"); + let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China" } catch(error) { console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`) } @@ -78,16 +81,16 @@ Obtains the localized script for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayLanguage = i18n.System.getDisplayLanguage("zh", "en-GB"); + let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese } catch(error) { console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -109,16 +112,16 @@ Obtains the list of system languages. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguages = i18n.System.getSystemLanguages(); + let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ] } catch(error) { console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`) } @@ -134,9 +137,9 @@ Obtains the list of countries and regions supported for the specified language. **Parameters** -| Name | Type | Description | -| -------- | ------ | ----- | -| language | string | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Return value** @@ -146,16 +149,16 @@ Obtains the list of countries and regions supported for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemCountries = i18n.System.getSystemCountries('zh'); + let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total } catch(error) { console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`) } @@ -184,16 +187,16 @@ Checks whether the system language matches the specified region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var res = i18n.System.isSuggested('zh', 'CN'); + let res = I18n.System.isSuggested('zh', 'CN'); // res = true } catch(error) { console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`) } @@ -215,16 +218,16 @@ Obtains the system language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguage = i18n.System.getSystemLanguage(); + let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language. } catch(error) { console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -236,7 +239,7 @@ static setSystemLanguage(language: string): void Sets the system language. Currently, this API does not support real-time updating of the system language. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -244,22 +247,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| language | string | Yes | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLanguage('zh'); + I18n.System.setSystemLanguage('zh'); // Set the current system language to zh. } catch(error) { console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -281,16 +284,16 @@ Obtains the system region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemRegion = i18n.System.getSystemRegion(); + let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region. } catch(error) { console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) } @@ -302,7 +305,7 @@ static setSystemRegion(region: string): void Sets the system region. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -310,22 +313,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| region | string | Yes | Region ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| region | string | Yes | Region ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemRegion('CN'); + I18n.System.setSystemRegion('CN'); // Set the current system region to CN. } catch(error) { console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) } @@ -347,16 +350,16 @@ Obtains the system locale. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLocale = i18n.System.getSystemLocale(); + let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale. } catch(error) { console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) } @@ -368,7 +371,7 @@ static setSystemLocale(locale: string): void Sets the system locale. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -376,22 +379,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| locale | string | Yes | System locale ID, for example, **zh-CN**.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| locale | string | Yes | System locale ID, for example, **zh-CN**.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLocale('zh-CN'); + I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN. } catch(error) { console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) } @@ -413,16 +416,16 @@ Checks whether the 24-hour clock is used. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var is24HourClock = i18n.System.is24HourClock(); + let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled. } catch(error) { console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`) } @@ -434,7 +437,7 @@ static set24HourClock(option: boolean): void Sets the 24-hour clock. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -448,17 +451,17 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Set the system time to the 24-hour clock. try { - i18n.System.set24HourClock(true); + I18n.System.set24HourClock(true); } catch(error) { console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`) } @@ -470,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void Adds a preferred language to the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -485,19 +488,19 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; + let language = 'zh-CN'; + let index = 0; try { - i18n.System.addPreferredLanguage(language, index); + I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list. } catch(error) { console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -509,7 +512,7 @@ static removePreferredLanguage(index: number): void Deletes a preferred language from the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -523,18 +526,18 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; + let index = 0; try { - i18n.System.removePreferredLanguage(index); + I18n.System.removePreferredLanguage(index); } catch(error) { console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -544,7 +547,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. **System capability**: SystemCapability.Global.I18n @@ -552,20 +555,20 @@ Obtains the list of preferred languages. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var preferredLanguageList = i18n.System.getPreferredLanguageList(); + let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list. } catch(error) { console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`) } @@ -587,16 +590,16 @@ Obtains the first language in the preferred language list. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var firstPreferredLanguage = i18n.System.getFirstPreferredLanguage(); + let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list. } catch(error) { console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -618,16 +621,16 @@ Obtains the preferred language of an application. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var appPreferredLanguage = i18n.System.getAppPreferredLanguage(); + let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application. } catch(error) { console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -637,9 +640,9 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static setUsingLocalDigit(flag: boolean): void -Sets whether to turn on the local digit switch. +Sets whether to enable the local digit switch. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -649,20 +652,20 @@ This is a system API. | Name | Type | Mandatory | Description | | ---- | ------- | ---- | ------------------------------- | -| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.| +| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - i18n.System.setUsingLocalDigit(true); + I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. } catch(error) { console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) } @@ -684,23 +687,23 @@ Checks whether the local digit switch is turned on. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - var status = i18n.System.getUsingLocalDigit(); + let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled. } catch(error) { console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) } ``` -## i18n.isRTL7+ +## I18n.isRTL7+ isRTL(locale: string): boolean @@ -710,9 +713,9 @@ Checks whether the localized script for the specified language is displayed from **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| locale | string | Yes | Locale ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| locale | string | Yes | Locale ID.| **Return value** @@ -727,7 +730,7 @@ Checks whether the localized script for the specified language is displayed from ``` -## i18n.getCalendar8+ +## I18n.getCalendar8+ getCalendar(locale: string, type? : string): Calendar @@ -750,7 +753,7 @@ Obtains a **Calendar** object. **Example** ```js - i18n.getCalendar("zh-Hans", "gregory"); + I18n.getCalendar("zh-Hans", "chinese"); // Obtain the Calendar object for the Chinese lunar calendar. ``` @@ -773,8 +776,8 @@ Sets the date for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - var date = new Date(2021, 10, 7, 8, 0, 0, 0); + let calendar = I18n.getCalendar("en-US", "gregory"); + let date = new Date(2021, 10, 7, 8, 0, 0, 0); calendar.setTime(date); ``` @@ -795,7 +798,7 @@ Sets the date and time for this **Calendar** object. The value is represented by **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); + let calendar = I18n.getCalendar("en-US", "gregory"); calendar.setTime(10540800000); ``` @@ -821,7 +824,7 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 ``` @@ -842,7 +845,7 @@ Sets the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); ``` @@ -863,9 +866,9 @@ Obtains the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); - calendar.getTimeZone(); // Asia/Shanghai" + let timezone = calendar.getTimeZone(); // timezone = "Asia/Shanghai" ``` @@ -885,8 +888,8 @@ Obtains the start day of a week for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - calendar.getFirstDayOfWeek(); + let calendar = I18n.getCalendar("en-US", "gregory"); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` @@ -906,8 +909,9 @@ Sets the start day of a week for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.setFirstDayOfWeek(0); + let calendar = I18n.getCalendar("zh-Hans"); + calendar.setFirstDayOfWeek(3); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3 ``` @@ -927,8 +931,8 @@ Obtains the minimum number of days in the first week of a year. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.getMinimalDaysInFirstWeek(); + let calendar = I18n.getCalendar("zh-Hans"); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1 ``` @@ -948,8 +952,9 @@ Sets the minimum number of days in the first week of a year. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setMinimalDaysInFirstWeek(3); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 ``` @@ -975,9 +980,9 @@ Obtains the value of the specified field in the **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 - calendar.get("hour_of_day"); // 8 + let hourOfDay = calendar.get("hour_of_day"); // hourOfDay = 8 ``` @@ -1003,8 +1008,8 @@ Obtains the **Calendar** object name displayed for the specified locale. **Example** ```js - var calendar = i18n.getCalendar("en-US", "buddhist"); - calendar.getDisplayName("zh"); // Obtain the name of the Buddhist calendar in zh. + let calendar = I18n.getCalendar("en-US", "buddhist"); + let calendarName = calendar.getDisplayName("zh"); // calendarName = "Buddhist Calendar" ``` @@ -1030,10 +1035,10 @@ Checks whether the specified date in this **Calendar** object is a weekend. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 calendar.isWeekend(); // false - var date = new Date(2011, 11, 6, 9, 0, 0); + let date = new Date(2011, 11, 6, 9, 0, 0); calendar.isWeekend(date); // true ``` @@ -1058,7 +1063,7 @@ Creates a **PhoneNumberFormat** object. **Example** ```js - var phoneNumberFormat= new i18n.PhoneNumberFormat("CN", {"type": "E164"}); + let phoneNumberFormat= new I18n.PhoneNumberFormat("CN", {"type": "E164"}); ``` @@ -1084,8 +1089,8 @@ Checks whether the format of the specified phone number is valid. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.isValidNumber("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let isValidNumber = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true ``` @@ -1111,8 +1116,8 @@ Formats a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.format("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let formattedPhoneNumber = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312" ``` @@ -1139,8 +1144,8 @@ Obtains the home location of a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.getLocationName("15812312345", "zh-CN"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let locationName = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "Zhanjiang, Guangdong Province" ``` @@ -1150,7 +1155,7 @@ Defines the options for this PhoneNumberFormat object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | | type | string | Yes | Yes | Format type of a phone number. The available options are as follows: E164, INTERNATIONAL, NATIONAL, and RFC3966.| @@ -1161,7 +1166,7 @@ Defines the measurement unit information. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | unit | string | Yes | Yes | Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| | measureSystem | string | Yes | Yes | Measurement system. The value can be **SI**, **US**, or **UK**.| @@ -1189,7 +1194,7 @@ Creates an **IndexUtil** object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); + let indexUtil= I18n.getInstance("zh-CN"); ``` @@ -1212,8 +1217,10 @@ Obtains the index list for this **locale** object. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); - var indexList = indexUtil.getIndexList(); + let indexUtil = I18n.getInstance("zh-CN"); + // indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", + // "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ] + let indexList = indexUtil.getIndexList(); ``` @@ -1233,7 +1240,7 @@ Adds the index of the new **locale** object to the index list. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); indexUtil.addLocale("en-US"); ``` @@ -1260,12 +1267,12 @@ Obtains the index of a text object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); - indexUtil.getIndex("hi"); // Return hi. + let indexUtil= I18n.getInstance("zh-CN"); + let index = indexUtil.getIndex("hi"); // index = "H" ``` -## i18n.getLineInstance8+ +## I18n.getLineInstance8+ getLineInstance(locale: string): BreakIterator @@ -1287,7 +1294,7 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); ``` @@ -1310,8 +1317,8 @@ Sets the text to be processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); - iterator.setLineBreakText("Apple is my favorite fruit."); + let iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit ."); // Set a short sentence as the text to be processed by the BreakIterator object. ``` @@ -1331,9 +1338,9 @@ Obtains the text being processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.getLineBreakText(); // Apple is my favorite fruit. + let breakText = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit." ``` @@ -1353,9 +1360,9 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.current(); // 0 + let currentPos = iterator.current(); // currentPos = 0 ``` @@ -1375,9 +1382,9 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 + let firstPos = iterator.first(); // firstPos = 0 ``` @@ -1397,9 +1404,9 @@ Puts the [BreakIterator](#breakiterator8) object to the last text boundary, whic **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.last(); // 27 + let lastPos = iterator.last(); // lastPos = 27 ``` @@ -1425,11 +1432,11 @@ Moves the [BreakIterator](#breakiterator8) object backward by the specified numb **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(); // 6 - iterator.next(10); // -1 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(); // pos = 6 + pos = iterator.next(10); // pos = -1 ``` @@ -1449,11 +1456,11 @@ Moves the [BreakIterator](#breakiterator8) object to the previous text boundary. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(3); // 12 - iterator.previous(); // 9 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(3); // pos = 12 + pos = iterator.previous(); // pos = 9 ``` @@ -1479,11 +1486,11 @@ Moves the [BreakIterator](#breakiterator8) object to the text boundary after the **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.following(0); // 6 - iterator.following(100); // -1 - iterator.current(); // 27 + let pos = iterator.following(0); // pos = 6 + pos = iterator.following(100); // pos = -1 + pos = iterator.current(); // pos = 27 ``` @@ -1509,14 +1516,14 @@ Checks whether the position specified by the offset is a text boundary. If **tru **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.isBoundary(0); // true; - iterator.isBoundary(5); // false; + let isBoundary = iterator.isBoundary(0); // isBoundary = true; + isBoundary = iterator.isBoundary(5); // isBoundary = false; ``` -## i18n.getTimeZone7+ +## I18n.getTimeZone7+ getTimeZone(zoneID?: string): TimeZone @@ -1538,7 +1545,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. **Example** ```js - var timezone = i18n.getTimeZone(); + let timezone = I18n.getTimeZone(); ``` @@ -1561,8 +1568,8 @@ Obtains the ID of the specified **TimeZone** object. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getID(); + let timezone = I18n.getTimeZone(); + let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" ``` @@ -1570,7 +1577,7 @@ Obtains the ID of the specified **TimeZone** object. getDisplayName(locale?: string, isDST?: boolean): string -Obtains the representation of a **TimeZone** object in the specified locale. +Obtains the localized representation of the time zone. **System capability**: SystemCapability.Global.I18n @@ -1589,8 +1596,8 @@ Obtains the representation of a **TimeZone** object in the specified locale. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getDisplayName("zh-CN", false); + let timezone = I18n.getTimeZone(); + let timezoneName = timezone.getDisplayName("zh-CN", false); // timezoneName = "China Standard Time" ``` @@ -1610,8 +1617,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getRawOffset(); + let timezone = I18n.getTimeZone(); + let offset = timezone.getRawOffset(); // offset = 28800000 ``` @@ -1631,8 +1638,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getOffset(1234567890); + let timezone = I18n.getTimeZone(); + let offset = timezone.getOffset(1234567890); // offset = 28800000 ``` @@ -1652,7 +1659,8 @@ Obtains the list of time zone IDs supported by the system. **Example** ```ts - var ids = i18n.TimeZone.getAvailableIDs(); + // ids = ["America/Adak", "America/Anchorage", "America/Bogota", "America/Denver", "America/Los_Angeles", "America/Montevideo", "America/Santiago", "America/Sao_Paulo", "Asia/Ashgabat", "Asia/Hovd", "Asia/Jerusalem", "Asia/Magadan", "Asia/Omsk", "Asia/Shanghai", "Asia/Tokyo", "Asia/Yerevan", "Atlantic/Cape_Verde", "Australia/Lord_Howe", "Europe/Dublin", "Europe/London", "Europe/Moscow", "Pacific/Auckland", "Pacific/Easter", "Pacific/Pago-Pago"], 24 time zones supported in total + let ids = I18n.TimeZone.getAvailableIDs(); ``` @@ -1672,7 +1680,8 @@ Obtains the list of time zone city IDs supported by the system. **Example** ```ts - var cityIDs = i18n.TimeZone.getAvailableZoneCityIDs(); + // cityIDs = ["Auckland", "Magadan", "Lord Howe Island", "Tokyo", "Shanghai", "Hovd", "Omsk", "Ashgabat", "Yerevan", "Moscow", "Tel Aviv", "Dublin", "London", "Praia", "Montevideo", "Brasília", "Santiago", "Bogotá", "Easter Island", "Salt Lake City", "Los Angeles", "Anchorage", "Adak", "Pago Pago"], 24 time zone cities supported in total + let cityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); ``` @@ -1680,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. static getCityDisplayName(cityID: string, locale: string): string -Obtains the localized display of a time zone city in the specified locale. +Obtains the localized representation of a time zone city in the specified locale. **System capability**: SystemCapability.Global.I18n @@ -1699,7 +1708,7 @@ Obtains the localized display of a time zone city in the specified locale. **Example** ```ts - var displayName = i18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); + let displayName = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "Shanghai (China)" ``` @@ -1725,7 +1734,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID **Example** ```ts - var timezone = i18n.TimeZone.getTimezoneFromCity("Shanghai"); + let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai"); ``` @@ -1748,7 +1757,9 @@ Obtains a list of IDs supported by the **Transliterator** object. **Example** ```ts - i18n.Transliterator.getAvailableIDs(); + // ids = ["ASCII-Latin", "Accents-Any", "Amharic-Latin/BGN", ...], 671 IDs supported in total + // Each ID consists of two parts separated by a hyphen (-). The format is source-destination. + let ids = I18n.Transliterator.getAvailableIDs(); ``` @@ -1774,7 +1785,7 @@ Creates a **Transliterator** object. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); ``` @@ -1800,8 +1811,8 @@ Converts the input string from the source format to the target format. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); - transliterator.transform ("China"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); + let res = transliterator.transform("China"); // res = "zhōng guó" ``` @@ -1830,7 +1841,7 @@ Checks whether the input character string is composed of digits. **Example** ```js - var isdigit = i18n.Unicode.isDigit("1"); // Return true. + let isdigit = I18n.Unicode.isDigit("1"); // isdigit = true ``` @@ -1856,7 +1867,7 @@ Checks whether the input character is a space. **Example** ```js - var isspacechar = i18n.Unicode.isSpaceChar("a"); // Return false. + let isspacechar = I18n.Unicode.isSpaceChar("a"); // isspacechar = false ``` @@ -1882,7 +1893,7 @@ Checks whether the input character is a white space. **Example** ```js - var iswhitespace = i18n.Unicode.isWhitespace("a"); // Return false. + let iswhitespace = I18n.Unicode.isWhitespace("a"); // iswhitespace = false ``` @@ -1908,7 +1919,7 @@ Checks whether the input character is of the right to left (RTL) language. **Example** ```js - var isrtl = i18n.Unicode.isRTL("a"); // Return false. + let isrtl = I18n.Unicode.isRTL("a"); // isrtl = false ``` @@ -1934,7 +1945,7 @@ Checks whether the input character is an ideographic character. **Example** ```js - var isideograph = i18n.Unicode.isIdeograph("a"); // Return false. + let isideograph = I18n.Unicode.isIdeograph("a"); // isideograph = false ``` @@ -1960,7 +1971,7 @@ Checks whether the input character is a letter. **Example** ```js - var isletter = i18n.Unicode.isLetter("a"); // Return true. + let isletter = I18n.Unicode.isLetter("a"); // isletter = true ``` @@ -1986,7 +1997,7 @@ Checks whether the input character is a lowercase letter. **Example** ```js - var islowercase = i18n.Unicode.isLowerCase("a"); // Return true. + let islowercase = I18n.Unicode.isLowerCase("a"); // islowercase = true ``` @@ -2012,7 +2023,7 @@ Checks whether the input character is an uppercase letter. **Example** ```js - var isuppercase = i18n.Unicode.isUpperCase("a"); // Return false. + let isuppercase = I18n.Unicode.isUpperCase("a"); // isuppercase = false ``` @@ -2038,7 +2049,7 @@ Obtains the type of the input character string. **Example** ```js - var type = i18n.Unicode.getType("a"); + let type = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER" ``` @@ -2071,7 +2082,7 @@ Converts one measurement unit into another and formats the unit based on the spe **Example** ```js - i18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); + let res = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters ``` @@ -2097,11 +2108,11 @@ Obtains the sequence of the year, month, and day in the specified locale. **Example** ```js - i18n.I18NUtil.getDateOrder("zh-CN"); + let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" ``` -## i18n.getDisplayCountry(deprecated) +## I18n.getDisplayCountry(deprecated) getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string @@ -2127,12 +2138,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayCountry("zh-CN", "en-GB", true); - i18n.getDisplayCountry("zh-CN", "en-GB"); + let countryName = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true + countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true ``` -## i18n.getDisplayLanguage(deprecated) +## I18n.getDisplayLanguage(deprecated) getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string @@ -2158,12 +2169,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayLanguage("zh", "en-GB", true); - i18n.getDisplayLanguage("zh", "en-GB"); + let languageName = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese" + languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese" ``` -## i18n.getSystemLanguage(deprecated) +## I18n.getSystemLanguage(deprecated) getSystemLanguage(): string @@ -2181,11 +2192,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLanguage(); + let systemLanguage = I18n.getSystemLanguage(); // Obtain the current system language. ``` -## i18n.getSystemRegion(deprecated) +## I18n.getSystemRegion(deprecated) getSystemRegion(): string @@ -2203,11 +2214,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemRegion(); + let region = I18n.getSystemRegion(); // Obtain the current system region. ``` -## i18n.getSystemLocale(deprecated) +## I18n.getSystemLocale(deprecated) getSystemLocale(): string @@ -2225,11 +2236,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLocale(); + let locale = I18n.getSystemLocale (); // Obtain the system locale. ``` -## i18n.is24HourClock(deprecated) +## I18n.is24HourClock(deprecated) is24HourClock(): boolean @@ -2247,11 +2258,11 @@ This API is deprecated since API version 9. You are advised to use [System.is24H **Example** ```js - var is24HourClock = i18n.is24HourClock(); + let is24HourClock = I18n.is24HourClock(); ``` -## i18n.set24HourClock(deprecated) +## I18n.set24HourClock(deprecated) set24HourClock(option: boolean): boolean @@ -2278,11 +2289,11 @@ This API is deprecated since API version 9. You are advised to use [System.set24 **Example** ```js // Set the system time to the 24-hour clock. - var success = i18n.set24HourClock(true); + let success = I18n.set24HourClock(true); ``` -## i18n.addPreferredLanguage(deprecated) +## I18n.addPreferredLanguage(deprecated) addPreferredLanguage(language: string, index?: number): boolean @@ -2310,13 +2321,13 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; - var success = i18n.addPreferredLanguage(language, index); + let language = 'zh-CN'; + let index = 0; + let success = I18n.addPreferredLanguage(language, index); ``` -## i18n.removePreferredLanguage(deprecated) +## I18n.removePreferredLanguage(deprecated) removePreferredLanguage(index: number): boolean @@ -2343,16 +2354,16 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; - var success = i18n.removePreferredLanguage(index); + let index = 0; + let success = I18n.removePreferredLanguage(index); ``` -## i18n.getPreferredLanguageList(deprecated) +## I18n.getPreferredLanguageList(deprecated) getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead. @@ -2362,15 +2373,15 @@ This API is supported since API version 8 and is deprecated since API version 9. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Example** ```js - var preferredLanguageList = i18n.getPreferredLanguageList(); + let preferredLanguageList = I18n.getPreferredLanguageList(); // Obtain the preferred language list. ``` -## i18n.getFirstPreferredLanguage(deprecated) +## I18n.getFirstPreferredLanguage(deprecated) getFirstPreferredLanguage(): string @@ -2388,7 +2399,7 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js - var firstPreferredLanguage = i18n.getFirstPreferredLanguage(); + let firstPreferredLanguage = I18n.getFirstPreferredLanguage(); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index f776c56334112c2b739b5b6a85ef7153c4da1564..54c8f0400be1f1e8b9f9b836098a94ace0c4f637 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -1,6 +1,6 @@ # AbilityResult -The **AbilityResult** module defines the result code and data returned when an ability is started or destroyed. +The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-context.md#abilitycontextstartabilityforresult) to obtain the **AbilityResult** object returned after the started ability is terminated. The startedability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-context.md#abilitycontextterminateselfwithresult). > **NOTE** > @@ -10,17 +10,5 @@ The **AbilityResult** module defines the result code and data returned when an a | Name | Readable | Writable | Type | Mandatory| Description | | ----------- | -------- |-------- | -------------------- | ---- | ------------------------------------------------------------ | -| resultCode | Yes | No | number | No | Result code returned when the ability is started or destroyed. | -| want | Yes | No | [Want](./js-apis-app-ability-want.md) | No | Data returned when the ability is destroyed.| - -**Example** - ```ts - let want = { - bundleName: 'com.example.mydocapplication', - abilityName: 'MainAbility', - }; - this.context.startAbilityForResult(want, (error, data) => { - let resultCode = data.resultCode; - let want = data.want; - }); - ``` +| resultCode | Yes | Yes | number | Yes | Result code returned after the started ability is terminated. | +| want | Yes | Yes | [Want](./js-apis-app-ability-want.md) | No | Data returned after the started ability is terminated. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md index 685329b15fe26618c4b2a3be2242d4912415a66d..db0814fa146e09114eeb4fa635dfa78564ee595e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -1,45 +1,11 @@ # ConnectOptions -The **ConnectOptions** module defines the options for connection. +**ConnectOptions** can be used as an input parameter to receive status changes during the connection to a background service. For example, it is used as an input parameter of [connectServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) to connect to a ServiceExtensionAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Mandatory | Description | | ------------ | -------- | ---- | ------------------------- | -| onConnect7+ | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect7+ | function | Yes | Callback invoked when the connection fails. | -| onFailed7+ | function | Yes | Callback invoked when **connectAbility** fails to be called.| - -**Return value** - -| Type | Description | -| ------ | -------------------- | -| number | ID of the Service ability connected.| - -**Example** - -```ts -import rpc from '@ohos.rpc'; -import featureAbility from '@ohos.ability.featureAbility'; -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` +| onConnect7+ | function | Yes | Callback invoked when a connection is set up. | +| onDisconnect7+ | function | Yes | Callback invoked when a connection is interrupted. | +| onFailed7+ | function | Yes | Callback invoked when a connection fails.| 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 f06df85ac59ffe3074519efd2c9aef95a5093cd7..d6b0c51051feb92f30495bdc552f84cae5e06018 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 @@ -1,5 +1,7 @@ # DataAbilityHelper +The **DataAbilityHelper** object is obtained through [acquireDataAbilityHelper](js-apis-ability-featureAbility.md#featureabilityacquiredataabilityhelper7). + > **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. @@ -9,15 +11,15 @@ Import the following modules based on the actual situation before using the current module: ```ts -import ohos_data_ability from '@ohos.data.dataAbility' -import ohos_data_rdb from '@ohos.data.rdb' +import ohos_data_ability from '@ohos.data.dataAbility'; +import ohos_data_rdb from '@ohos.data.rdb'; ``` ## DataAbilityHelper.openFile openFile(uri: string, mode: string, callback: AsyncCallback\): void -Opens a file with a specified URI. This API uses an asynchronous callback to return the result. +Opens a file with a specified URI. This API uses an asynchronous callback to return a file descriptor. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -26,22 +28,19 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ---------------------------------- | | uri | string | Yes | URI of the file to open. | -| mode | string | Yes | Mode for opening the file. The value can be **rwt**. | +| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. | | callback | AsyncCallback\ | Yes | Callback used to return the file descriptor.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rwt"; -DAHelper.openFile( - "dataability:///com.example.DataAbility", - mode, - (err) => { - console.info("==========================>Called=======================>"); +var mode = "rw"; +DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => { + console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -49,7 +48,7 @@ DAHelper.openFile( openFile(uri: string, mode: string): Promise\ -Opens a file with a specified URI. This API uses a promise to return the result. +Opens a file with a specified URI. This API uses a promise to return a file descriptor. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -58,7 +57,7 @@ Opens a file with a specified URI. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------------ | | uri | string | Yes | URI of the file to open.| -| mode | string | Yes | Mode for opening the file. The value can be **rwt**. | +| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. | **Return value** @@ -69,15 +68,13 @@ Opens a file with a specified URI. This API uses a promise to return the result. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rwt"; -DAHelper.openFile( - "dataability:///com.example.DataAbility", - mode).then((data) => { - console.info("==========================>openFileCallback=======================>"); +var mode = "rw"; +DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => { + console.info("openFile data: " + JSON.stringify(data)); }); ``` @@ -85,7 +82,7 @@ DAHelper.openFile( on(type: 'dataChange', uri: string, callback: AsyncCallback\): void -Registers an observer to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Registers an observer to listen for changes in the data specified by a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -93,32 +90,32 @@ Registers an observer to observe data specified by a given URI. This API uses an | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Type of the event to observe. The value is **dataChange**. | +| type | string | Yes | The value **dataChange** means data changes. | | uri | string | Yes | URI of the data.| | callback | AsyncCallback\ | Yes | Callback invoked when the data is changed. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { - console.info("==========================>onChangeNotify=======================>"); + console.info("onChangeNotify call back"); }; -helper.on( +DAHelper.on( "dataChange", "dataability:///com.example.DataAbility", onChangeNotify -) +); ``` ## DataAbilityHelper.off off(type: 'dataChange', uri: string, callback?: AsyncCallback\): void -Deregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Deregisters the observer that listens for changes in the data specified by a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -126,36 +123,36 @@ Deregisters the observer used to observe data specified by a given URI. This API | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Type of the event to observe. The value is **dataChange**. | +| type | string | Yes | The value **dataChange** means data changes. | | uri | string | Yes | URI of the data.| -| callback | AsyncCallback\ | No | Callback used to return the result. | +| callback | AsyncCallback\ | No | Callback of the listener to deregister. If the callback is set to **null**, all data change listeners are canceled. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { - console.info("==========================>onChangeNotify=======================>"); + console.info("onChangeNotify call back"); }; -helper.off( +DAHelper.off( "dataChange", "dataability:///com.example.DataAbility", -) -helper.off( + onChangeNotify +); +DAHelper.off( "dataChange", "dataability:///com.example.DataAbility", - onChangeNotify -) +); ``` ## DataAbilityHelper.getType getType(uri: string, callback: AsyncCallback\): void -Obtains the MIME type of the data specified by a given URI. This API uses an asynchronous callback to return the result. +Obtains the media resource type of the data specified by a given URI. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -164,19 +161,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses an asy | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------------------------- | | uri | string | Yes | URI of the data. | -| callback | AsyncCallback\ | Yes | Callback used to return the MIME type.| +| callback | AsyncCallback\ | Yes | Callback used to return the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getType( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => { + console.info("getType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -184,7 +179,7 @@ DAHelper.getType( getType(uri: string): Promise\ -Obtains the MIME type of the data specified by a given URI. This API uses a promise to return the result. +Obtains the media resource type of the data specified by a given URI. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -198,19 +193,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses a prom | Type | Description | | ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the MIME type.| +| Promise\ | Promise used to return the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getType( - "dataability:///com.example.DataAbility" - ).then((data) => { - console.info("==========================>getTypeCallback=======================>"); +DAHelper.getType("dataability:///com.example.DataAbility").then((data) => { + console.info("getType data: " + JSON.stringify(data)); }); ``` @@ -218,7 +211,7 @@ DAHelper.getType( getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback>): void -Obtains the supported MIME types of a specified file. This API uses an asynchronous callback to return the result. +Obtains the supported media resource types of a specified file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -227,31 +220,26 @@ Obtains the supported MIME types of a specified file. This API uses an asynchron | Name | Type | Mandatory| Description | | -------------- | ------------------------------ | ---- | ---------------------------------- | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME type of the file. | -| callback | AsyncCallback\> | Yes | Callback used to return the supported MIME types.| +| mimeTypeFilter | string | Yes | Media resource type of the file to obtain. | +| callback | AsyncCallback\> | Yes | Callback used to return an array holding the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getFileTypes( - "dataability:///com.example.DataAbility", - "image/*", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.getFileTypes( "dataability:///com.example.DataAbility", "image/*", (err, data) => { + console.info("getFileTypes err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` - - ## DataAbilityHelper.getFileTypes getFileTypes(uri: string, mimeTypeFilter: string): Promise\> -Obtains the supported MIME types of a specified file. This API uses a promise to return the result. +Obtains the supported media resource types of a specified file. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -260,26 +248,23 @@ Obtains the supported MIME types of a specified file. This API uses a promise to | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ---------------------------- | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME type of the file.| +| mimeTypeFilter | string | Yes | Media resource type of the file to obtain.| **Return value** | Type | Description | | ------------------------ | ------------------------ | -| Promise\> | Promise used to return the supported MIME types.| +| Promise\> | Promise used to return an array holding the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getFileTypes( - "dataability:///com.example.DataAbility", - "image/*" - ).then((data) => { - console.info("==========================>getFileTypesCallback=======================>"); +DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => { + console.info("getFileTypes data: " + JSON.stringify(data)); }); ``` @@ -301,14 +286,12 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.normalizeUri( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => { + console.info("normalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -335,14 +318,12 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.normalizeUri( - "dataability:///com.example.DataAbility", - ).then((data) => { - console.info("==========================>normalizeUriCallback=======================>"); +DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => { + console.info("normalizeUri data: " + JSON.stringify(data)); }); ``` @@ -358,25 +339,21 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------------------------------- | -| uri | string | Yes | URI object to normalize. | +| uri | string | Yes | URI object to denormalize. | | callback | AsyncCallback\ | Yes | Callback used to return the denormalized URI object.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.denormalizeUri( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => { + console.info("denormalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` - - ## DataAbilityHelper.denormalizeUri denormalizeUri(uri: string): Promise\ @@ -400,14 +377,12 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.denormalizeUri( - "dataability:///com.example.DataAbility", - ).then((data) => { - console.info("==========================>denormalizeUriCallback=======================>"); +DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => { + console.info("denormalizeUri data: " + JSON.stringify(data)); }); ``` @@ -423,20 +398,18 @@ Notifies the registered observer of a change to the data specified by the URI. T | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| uri | string | Yes | URI of the data.| +| uri | string | Yes | URI of the data that changes.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -helper.notifyChange( - "dataability:///com.example.DataAbility", - (err) => { - console.info("==========================>Called=======================>"); +DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => { + console.info("==========================>Called=======================>"); }); ``` @@ -452,7 +425,7 @@ Notifies the registered observer of a change to the data specified by the URI. T | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------------ | -| uri | string | Yes | URI of the data.| +| uri | string | Yes | URI of the data that changes.| **Return value** @@ -463,14 +436,12 @@ Notifies the registered observer of a change to the data specified by the URI. T **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.notifyChange( - "dataability:///com.example.DataAbility", - ).then(() => { - console.info("==========================>notifyChangeCallback=======================>"); +DAHelper.notifyChange("dataability:///com.example.DataAbility").then(() => { + console.info("================>notifyChangeCallback================>"); }); ``` @@ -493,7 +464,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -502,12 +473,9 @@ const valueBucket = { "age": 22, "salary": 200.5, "blobType": "u8", -} -DAHelper.insert( - "dataability:///com.example.DataAbility", - valueBucket, - (err, data) => { - console.info("==========================>Called=======================>"); +}; +DAHelper.insert("dataability:///com.example.DataAbility", valueBucket, (err, data) => { + console.info("insert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -535,7 +503,7 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -544,12 +512,9 @@ const valueBucket = { "age": 221, "salary": 20.5, "blobType": "u8", -} -DAHelper.insert( - "dataability:///com.example.DataAbility", - valueBucket - ).then((data) => { - console.info("==========================>insertCallback=======================>"); +}; +DAHelper.insert("dataability:///com.example.DataAbility", valueBucket).then((data) => { + console.info("insert data: " + JSON.stringify(data)); }); ``` @@ -572,18 +537,15 @@ Inserts multiple data records into the database. This API uses an asynchronous c **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}) -DAHelper.batchInsert( - "dataability:///com.example.DataAbility", - cars, - (err, data) => { - console.info("==========================>Called=======================>"); + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); +DAHelper.batchInsert("dataability:///com.example.DataAbility", cars, (err, data) => { + console.info("batchInsert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -600,7 +562,7 @@ Inserts multiple data records into the database. This API uses a promise to retu | Name | Type | Mandatory| Description | | ------------ | ----------------------- | ---- | ------------------------ | | uri | string | Yes | URI of the data to insert.| -| valuesBucket | Array | Yes | Data record to insert. | +| valuesBucket | Array | Yes | Data records to insert. | **Return value** @@ -611,18 +573,15 @@ Inserts multiple data records into the database. This API uses a promise to retu **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}) -DAHelper.batchInsert( - "dataability:///com.example.DataAbility", - cars - ).then((data) => { - console.info("==========================>batchInsertCallback=======================>"); + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); +DAHelper.batchInsert("dataability:///com.example.DataAbility", cars).then((data) => { + console.info("batchInsert data: " + JSON.stringify(data)); }); ``` @@ -645,17 +604,14 @@ Deletes one or more data records from the database. This API uses an asynchronou **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.delete( - "dataability:///com.example.DataAbility", - da, - (err, data) => { - console.info("==========================>Called=======================>"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.delete("dataability:///com.example.DataAbility", da, (err, data) => { + console.info("delete err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -683,17 +639,14 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.delete( - "dataability:///com.example.DataAbility", - da - ).then((data) => { - console.info("==========================>deleteCallback=======================>"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.delete("dataability:///com.example.DataAbility", da).then((data) => { + console.info("delete data: " + JSON.stringify(data)); }); ``` @@ -717,8 +670,8 @@ Updates data records in the database. This API uses an asynchronous callback to **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -727,14 +680,10 @@ const va = { "age": 21, "salary": 20.5, "blobType": "u8", -} -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.update( - "dataability:///com.example.DataAbility", - va, - da, - (err, data) => { - console.info("==========================>Called=======================>"); +}; +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.update("dataability:///com.example.DataAbility", va, da, (err, data) => { + console.info("update err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -763,8 +712,8 @@ Updates data records in the database. This API uses a promise to return the resu **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -773,14 +722,10 @@ const va = { "age": 21, "salary": 20.5, "blobType": "u8", -} -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.update( - "dataability:///com.example.DataAbility", - va, - da - ).then((data) => { - console.info("==========================>updateCallback=======================>"); +}; +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.update("dataability:///com.example.DataAbility", va, da).then((data) => { + console.info("update data: " + JSON.stringify(data)); }); ``` @@ -804,19 +749,15 @@ Queries data in the database. This API uses an asynchronous callback to return t **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); var cars=new Array("value1", "value2", "value3", "value4"); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.query( - "dataability:///com.example.DataAbility", - cars, - da, - (err, data) => { - console.info("==========================>Called=======================>"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.query("dataability:///com.example.DataAbility", cars, da, (err, data) => { + console.info("query err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -847,27 +788,23 @@ Queries data in the database. This API uses a promise to return the result. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var cars=new Array("value1", "value2", "value3", "value4"); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.query( - "dataability:///com.example.DataAbility", - cars, - da - ).then((data) => { - console.info("==========================>queryCallback=======================>"); +var cars = new Array("value1", "value2", "value3", "value4"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.query("dataability:///com.example.DataAbility", cars, da).then((data) => { + console.info("query data: " + JSON.stringify(data)); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap): Promise\ +call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void -Calls the extended API of the Data ability. This API uses a promise to return the result. +Calls an extended API of the DataAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -875,35 +812,35 @@ Calls the extended API of the Data ability. This API uses a promise to return th | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| 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. | +| arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | - -**Return value** - -| Type| Description| -|------ | ------- | -|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| +| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | **Example** ```ts import featureAbility from '@ohos.ability.featureAbility'; -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "method", "arg", {"key1":"value1"}).then((data) => { +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", + "method", "arg", {"key1":"value1"}, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + err); + return; + } console.info('Operation succeeded: ' + data); -}).catch((error) => { - console.error('Operation failed. Cause: ' + error); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void +call(uri: string, method: string, arg: string, extras: PacMap): Promise\ -Calls the extended API of the Data ability. This API uses an asynchronous callback to return the result. +Calls an extended API of the DataAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -911,24 +848,30 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| 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. | +| arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | -| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | + +**Return value** + +| Type| Description| +|------ | ------- | +|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| **Example** ```ts import featureAbility from '@ohos.ability.featureAbility'; -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "method", "arg", {"key1":"value1"}, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + err); - return; - } +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", + "method", "arg", {"key1":"value1"}).then((data) => { console.info('Operation succeeded: ' + data); +}).catch((error) => { + console.error('Operation failed. Cause: ' + error); }); ``` @@ -936,17 +879,17 @@ dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", " executeBatch(uri: string, operations: Array\, callback: AsyncCallback\>): void; -Operates data in the database. This API uses an asynchronous callback to return the result. +Operates data in the database in batches. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. | -| callback | AsyncCallback\> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. | +| Name | Type | Mandatory| Description | +| ----------| ---------------------------------| ---- | ------------------------------------------------ | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. | +| callback | AsyncCallback\> | Yes | Callback used to return the result of each operation in the **DataAbilityResult** array. | **Example** @@ -955,7 +898,9 @@ import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + err); @@ -969,7 +914,7 @@ dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbi executeBatch(uri: string, operations: Array\): Promise\>; -Operates data in the database. This API uses a promise to return the result. +Operates data in the database in batches. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -977,14 +922,14 @@ Operates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | -------------------------------| ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. | **Return value** | Type| Description| |------ | ------- | -|Promise\> | Callback used to return the result of each operation in the **DataAbilityResult** array.| +|Promise\> | Promise used to return the result of each operation in the **DataAbilityResult** array.| **Example** @@ -993,8 +938,10 @@ import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility",op ).then((data) => { +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op).then((data) => { console.info('Operation succeeded: ' + data); }).catch((error) => { console.error('Operation failed. Cause: ' + error); diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md index 30148ab3a64188abe2aef5a8c5cf2814f297da3e..0b96b8caa97bb28e7515bbc00ee1d7852ad2d21a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md @@ -1,6 +1,6 @@ # DataAbilityOperation -The **DataAbilityOperation** module defines the operation on Data abilities. +The **DataAbilityOperation** module defines the operation on DataAbilities. It can be used as an input parameter of [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to specify the database operation information. > **NOTE** > @@ -11,56 +11,11 @@ The **DataAbilityOperation** module defines the operation on Data abilities. | Name | Template | Mandatory| Description | | -------- | -------- | --------| -------- | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | -| type | featureAbility.DataAbilityOperationType | Yes | Operation type. | -| valuesBucket? | rdb.ValuesBucket | No | Data value to set. | -| valueBackReferences? | rdb.ValuesBucket | No | **ValuesBucket** object that contains a set of key-value pairs. | -| predicates? | dataAbility.DataAbilityPredicates | No | Predicates to set. If no predicate is set, all data records are displayed. | -| predicatesBackReferences? | Map\ | No | Back references of the predicates. | -| interrupted? | boolean | No | Whether batch operations can be interrupted. | -| expectedCount? | number | No | Expected number of rows to be updated or deleted. | - -**Example** -```ts -import featureAbility from '@ohos.ability.featureAbility' - -let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); -let DAHelper; -try { - DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); - if(DAHelper == null){ - console.error('DAHelper is null'); - return; - } -} catch (err) { - console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); - return; -} - -let valueBucket = { - "name": "DataAbilityHelperTest", - "age": 24, - "salary": 2024.20, -}; -let dataAbilityOperation = { - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true -} -let operations = [ - dataAbilityOperation -]; -try { - DAHelper.executeBatch(dataAbilityUri, operations, - (err, data) => { - console.log("executeBatch, data: " + JSON.stringify(data)); - } - ); -} catch (err) { - console.error('executeBatch fail: ' + JSON.stringify(err)); -} -``` +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| type | featureAbility.DataAbilityOperationType | Yes | Operation type. | +| valuesBucket? | rdb.ValuesBucket | No | Data value to set. | +| valueBackReferences? | rdb.ValuesBucket | No | **ValuesBucket** object that contains a set of key-value pairs. | +| predicates? | dataAbility.DataAbilityPredicates | No | Predicates to set. If no predicate is set, all data records are displayed. | +| predicatesBackReferences? | Map\ | No | Back references of the predicates. | +| interrupted? | boolean | No | Whether batch operations can be interrupted. | +| expectedCount? | number | No | Expected number of rows to be updated or deleted. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md index fe602f38efcbcbb8619a29e1d05c3a6f92bf2635..49b14bebedfaa76b495e8a127e3f4bd243c649b7 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -1,6 +1,6 @@ # DataAbilityResult -The **DataAbilityResult** module defines the operation result on Data abilities. +The **DataAbilityResult** module defines the operation result on DataAbilities. When you call [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to operate the database, the operation result is returned through the **DataAbilityResult** object. > **NOTE** > @@ -11,63 +11,67 @@ The **DataAbilityResult** module defines the operation result on Data abilities. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| uri? | string | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | -| count? | number | No | Number of rows affected by the operation. | +| uri? | string | No | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| count? | number | No | Number of rows affected by the operation. | **Example** + ```ts import featureAbility from '@ohos.ability.featureAbility' -let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); -let DAHelper; -try { - DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); - if(DAHelper == null){ - console.error('DAHelper is null'); +// Perform database operations in batches. +function executeBatchOperation() { + let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); + let DAHelper; + try { + DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); + if (DAHelper == null) { + console.error('DAHelper is null'); + return; + } + } catch (err) { + console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); return; } -} catch (err) { - console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); - return; -} -let valueBucket = { - "name": "DataAbilityHelperTest", - "age": 24, - "salary": 2024.20, -}; -let operations = [ -{ - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true, -}, -{ - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true, -} -]; + let valueBucket = { + "name": "DataAbilityHelperTest", + "age": 24, + "salary": 2024.20, + }; + let operations = [ + { + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, + }, + { + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, + } + ]; -try { - let promise = DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { - for (let i = 0; i < data.length; i++) { - let dataAbilityResult = data[i]; - console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); - console.log('dataAbilityResult.count: ' + dataAbilityResult.count); - } - }).catch(err => { + try { + DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { + for (let i = 0; i < data.length; i++) { + let dataAbilityResult = data[i]; + console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); + console.log('dataAbilityResult.count: ' + dataAbilityResult.count); + } + }).catch(err => { + console.error('executeBatch error: ' + JSON.stringify(err)); + }); + } catch (err) { console.error('executeBatch error: ' + JSON.stringify(err)); - }); -} catch (err) { - console.error('executeBatch error: ' + JSON.stringify(err)); + } } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md index bbb025920d5a49ec02cc9fc84fed7c1bee8e6fca..71b8d529703d28e01072d8f18f92ebe30b82c556 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -1,6 +1,6 @@ # StartAbilityParameter -The **StartAbilityParameter** module defines the parameters for starting an ability. +The **StartAbilityParameter** module defines the parameters for starting an ability. The parameters can be used as input parameters in [startAbility](js-apis-ability-featureAbility.md#featureabilitystartability) to start the specified ability. > **NOTE** > @@ -11,8 +11,8 @@ The **StartAbilityParameter** module defines the parameters for starting an abil | Name | Type | Mandatory | Description | | ------------------- | -------- | ---- | -------------------------------------- | -| want | [Want](js-apis-application-want.md)| Yes | Information about the ability to start. | -| abilityStartSetting | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| +| want | [Want](js-apis-application-want.md)| Yes | Want information about the target ability. | +| abilityStartSetting | {[key: string]: any} | No | Special attribute of the target ability. This attribute can be passed in the call.| **Example** ```ts @@ -20,7 +20,7 @@ import featureAbility from '@ohos.ability.featureAbility' let Want = { bundleName: "com.example.abilityStartSettingApp2", - abilityName: "com.example.abilityStartSettingApp.MainAbility", + abilityName: "com.example.abilityStartSettingApp.EntryAbility", } let abilityStartSetting ={ @@ -31,13 +31,15 @@ let abilityStartSetting ={ } let startAbilityParameter = { - want:Want, - abilityStartSetting:abilityStartSetting + want : Want, + abilityStartSetting : abilityStartSetting } -featureAbility.startAbility(startAbilityParameter, (err,data)=>{ - console.log('errCode : ' + JSON.stringify(err)); - console.log('data : ' + JSON.stringify(data)); +try { + featureAbility.startAbility(startAbilityParameter, (err, data) => { + console.log('errCode : ' + JSON.stringify(err)); + console.log('data : ' + JSON.stringify(data)); + }); } catch(error) { console.log("startAbility error: " + JSON.stringify(error)); } 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 4eea38a4e28c3e344a8ecdc60118af0fe93ddf19..afb331b3fc2cb610025dd741e94abe0392fe4a5b 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 @@ -1,6 +1,6 @@ # Want -Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. > **NOTE** > @@ -10,56 +10,62 @@ Want is a carrier for information transfer between objects (application componen | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. | -| bundleName | string | No | Bundle name of the application. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| bundleName | string | No | Bundle name.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | -| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| -| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | +| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags). | +| action | string | No | Action to take, such as viewing and sharing application details. 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 details, see [action](js-apis-app-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | | parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). | | moduleName9+ | string | No | Module to which the ability belongs.| **Example** -- Basic usage +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). ```ts - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry" // moduleName is optional. - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", + "moduleName": "entry" // moduleName is optional. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) ``` -- Passing a file descriptor (FD) +- Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility): ```ts - import fileio from '@ohos.fileio'; - var fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); - } - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} - } - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + import fileio from '@ohos.fileio'; + + // ... + let fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", + "moduleName": "entry", // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + // ... ``` - + +- For more details and examples, see [Want](../../application-models/want-overview.md). + + diff --git a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md index a8eb10e600ef981de57a8acc227b1b6371efde26..39c846bb6e96a2e8db53b71c6685e3e1ce3a4579 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md @@ -1,24 +1,15 @@ # AppVersionInfo -The **AppVersionInfo** module defines the application version information. +The **AppVersionInfo** module defines the application version information. You can use [getAppVersionInfo](js-apis-inner-app-context.md#contextgetappversioninfo7) to obtain the version information of the current application. -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +> **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. -| Name | Type | Readable | Writable | Description | -| ----------- | ------ | ---- | ---- | ------- | -| appName | string | Yes | No | Module name. | -| versionCode | number | Yes | No | Module description.| -| versionName | string | Yes | No | Module description ID.| +**System capability**: SystemCapability.Ability.AbilityRuntime.Core -**Example** -```ts -let appName; -let versionCode; -let versionName; -this.context.getAppVersionInfo((error, data) => { - console.info('getAppVersionInfo data is:' + JSON.stringify(data)); - appName = data.appName; - versionCode = data.versionCode; - versionName = data.versionName; -}); -``` +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | -------------- | +| appName | string | Yes | No | Application name. | +| versionCode | number | Yes | No | Application version code.| +| versionName | string | Yes | No | Application version name. | diff --git a/en/application-dev/reference/apis/js-apis-inner-app-context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md index 84b46fd028782c8517e3c6aca5bad324c8eac179..ec729194807c24ea49b7b117cb308628c031a75a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md @@ -5,11 +5,12 @@ The **Context** module provides context for abilities or applications. It allows > **NOTE** > > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the FA model. ## Usage -The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: +The **Context** object is created in a **featureAbility** and returned through its [getContext](js-apis-ability-featureAbility.md#featureabilitygetcontext) API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: ```ts import featureAbility from '@ohos.ability.featureAbility'; @@ -93,14 +94,15 @@ Verifies whether a specific PID and UID have the given permission. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -import bundle from '@ohos.bundle'; +import bundle from '@ohos.bundle.bundleManager'; var context = featureAbility.getContext(); bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ - context.verifyPermission("com.example.permission", {uid:datainfo.uid}, (err, data) =>{ + context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{ console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); }); ``` +For details about **getBundleInfo** in the sample code, see [bundleManager](js-apis-bundleManager.md). @@ -250,7 +252,7 @@ Obtains information about the current application. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ------------ | -| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information.| +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | Yes | Callback used to return the application information.| **Example** @@ -352,7 +354,7 @@ Obtains the display orientation of this ability. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Yes | Callback used to return the display orientation.| **Example** @@ -376,7 +378,7 @@ Obtains the display orientation of this ability. This API uses a promise to retu | Type | Description | | ---------------------------------------- | --------- | -| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation.| +| Promise\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Promise used to return the display orientation.| **Example** @@ -448,7 +450,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | ------------ | -| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.| +| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | Display orientation to set.| | callback | AsyncCallback\ | Yes | Callback used to return the display orientation. | **Example** @@ -457,7 +459,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); -var orientation=bundle.DisplayOrientation.UNSPECIFIED +var orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation, (err) => { console.info("setDisplayOrientation err: " + JSON.stringify(err)); }); @@ -475,7 +477,7 @@ Sets the display orientation for this ability. This API uses a promise to return | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | +| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | | Promise\ | Promise used to return the display orientation. | **Example** @@ -484,7 +486,7 @@ Sets the display orientation for this ability. This API uses a promise to return import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); -var orientation=bundle.DisplayOrientation.UNSPECIFIED +var orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation).then((data) => { console.info("setDisplayOrientation data: " + JSON.stringify(data)); }); @@ -510,7 +512,7 @@ Sets whether to show this feature at the top of the lock screen so that the feat ```ts import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var show=true +var show = true; context.setShowOnLockScreen(show, (err) => { console.info("setShowOnLockScreen err: " + JSON.stringify(err)); }); @@ -541,7 +543,7 @@ Sets whether to show this feature at the top of the lock screen so that the feat ```ts import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var show=true +var show = true; context.setShowOnLockScreen(show).then((data) => { console.info("setShowOnLockScreen data: " + JSON.stringify(data)); }); @@ -567,7 +569,7 @@ Sets whether to wake up the screen when this feature is restored. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var wakeUp=true +var wakeUp = true; context.setWakeUpScreen(wakeUp, (err) => { console.info("setWakeUpScreen err: " + JSON.stringify(err)); }); @@ -598,7 +600,7 @@ Sets whether to wake up the screen when this feature is restored. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var wakeUp=true +var wakeUp = true; context.setWakeUpScreen(wakeUp).then((data) => { console.info("setWakeUpScreen data: " + JSON.stringify(data)); }); @@ -673,7 +675,7 @@ This API is available only to Page abilities. | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[ElementName](js-apis-bundle-ElementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.| +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.| **Example** @@ -701,7 +703,7 @@ This API is available only to Page abilities. | Type | Description | | --------------------- | ------------------------------------ | -| Promise\<[ElementName](js-apis-bundle-ElementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.| **Example** @@ -769,7 +771,7 @@ context.getProcessName().then((data) => { getCallingBundle(callback: AsyncCallback\): void -Obtains the bundle name of the calling ability. This API uses an asynchronous callback to return the result. +Obtains the bundle name of the caller ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -795,7 +797,7 @@ context.getCallingBundle((err, data) => { getCallingBundle(): Promise\ -Obtains the bundle name of the calling ability. This API uses a promise to return the result. +Obtains the bundle name of the caller ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -925,7 +927,7 @@ If the distributed file path does not exist, the system will create one and retu | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| +| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path.
If the path does not exist, the system will create one and return the created path.| **Example** @@ -951,7 +953,7 @@ If the distributed file path does not exist, the system will create one and retu | Type | Description | | ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a new path will be created.| +| Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a path will be created.| **Example** @@ -1023,7 +1025,7 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| +| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| **Example** @@ -1047,7 +1049,7 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to | Type | Description | | ---------------------------------------- | ------------------ | -| Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| +| Promise\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| **Example** @@ -1119,7 +1121,7 @@ Obtains information about this ability. This API uses an asynchronous callback t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| +| callback | AsyncCallback\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** @@ -1143,7 +1145,7 @@ Obtains information about this ability. This API uses a promise to return the re | Type | Description | | ---------------------------------------- | ------------------ | -| Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise used to return the ability information.| +| Promise\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Promise used to return the ability information.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md index 0da1d45efcd3ae56473a37ec28da8e056dbf3def..351d6ad145824d0eba37a3a1eadc846034763c97 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -1,13 +1,19 @@ # ProcessInfo -The **ProcessInfo** module defines process information. +The **ProcessInfo** module defines process information. You can use [getProcessInfo](js-apis-inner-app-context.md#contextgetprocessinfo7) to obtain information about the processes running on the current ability. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module can be used only in the FA model. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| processName | string | Yes| No| Process name.| +| pid | number | Yes| No| Process ID.| +| processName | string | Yes| No| Process name.| **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 71163a1d857e897306e1c90ed3262943fe898e98..ad4f7e19a9fd40b82684c0acc11a458073bbb16b 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -8,14 +8,11 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in ## Usage -The ability delegator can be obtained by calling **getAbilityDelegator** in **AbilityDelegatorRegistry**. +An **AbilityDelegator** object is obtained by calling [getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator) in **AbilityDelegatorRegistry**. ```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -var abilityDelegator; - -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); - +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ## AbilityDelegator @@ -1044,7 +1041,7 @@ abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => { console.info("waitAbilityStageMonitor callback"); }); ``` - + ### waitAbilityStageMonitor9+ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index 97ecb0ed8bf03802ac2a8e1dcab4516d45acc36d..a5f131c3e02071f3d55cbfdc73955ffef42889d3 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -1,6 +1,6 @@ # AbilityDelegatorArgs -The **AbilityDelegatorArgs** module provides a global register to store the registered **AbilityDelegator** and **AbilityDelegatorArgs** instances during application startup. +The **AbilityDelegatorArgs** module provides APIs to obtain an **AbilityDelegatorArgs** object during the execution of test cases. > **NOTE** > @@ -8,7 +8,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi ## Usage -The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**. +An **AbilityDelegatorArgs** object is obtained by calling [getArguments](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetarguments) in **AbilityDelegatorRegistry**. ## AbilityDelegatorArgs diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md index 7aef3303481563008a79f7f8a43be66cbbbfa7fa..d8726205b8caec547f270e8efe6472e37cd99eb4 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -8,7 +8,7 @@ The **AbilityMonitor** module provides monitors for abilities that meet specifie ## Usage -The ability monitor can be set by calling **addAbilityMonitor** in **abilityDelegator**. +**AbilityMonitor** can be used as an input parameter of [addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9) in **abilityDelegator** to listen for lifecycle changes of an ability. ## AbilityMonitor @@ -31,7 +31,6 @@ Describes an ability monitor. ```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -var abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); @@ -42,7 +41,7 @@ var monitor = { onAbilityCreate: onAbilityCreateCallback } -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityMonitor(monitor, (err : any) => { console.info("addAbilityMonitor callback"); }); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index 4f553001c63881441b23a3ce42ba429497775b2d..62b1f7e1fae204f2e6b1f6dcdc76521da3c51777 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -8,7 +8,7 @@ The **AbilityRunningInfo** module defines the running information and state of a ## Usage -The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**. +The ability running information is obtained by calling [getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos) in **abilityManager**. ## Attributes diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 99a2453d84124b1eee3d7dc6a5aa7c2d8e5b8663..79f750797c12bfd9c323e2f613650c016ea2930b 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -26,7 +26,7 @@ class MyAbilityStage extends AbilityStage { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.| +| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration for the environment where the application is running.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md index b86ba33545181076833461e4a63650290d15be9b..eb539bd981610af81a6e9598bcab3da8dc3f9279 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md @@ -1,33 +1,36 @@ # AbilityStateData -The **AbilityStateData** module defines the ability state information. +The **AbilityStateData** module defines the ability state information, which can be obtained through the **onAbilityStateChanged** lifecycle callback of [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md). The callback can be invoked after a lifecycle change listener is registered through [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8). **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | | pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name of an application. | +| bundleName8+ | string | Yes | No | Bundle name. | | abilityName8+ | string | Yes | No | Ability name. | | uid8+ | number | Yes | No | User ID. | -| state8+ | number | Yes | No | Ability state. | +| state8+ | number | Yes | No | [Ability state](#ability-states). | | moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | -| abilityType8+ | string | Yes | No | Ability type. | +| abilityType8+ | number | Yes | No | [Ability type](#ability-types), which can be **page** or **service**.| -**Example** -```ts -import appManager from "@ohos.application.appManager" +#### Ability States -appManager.getForegroundApplications((error, data) => { - for(let i=0; i { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index 15925c305ab652b9b4426c169b430af358e89331..e6d3137582ee3b485e4a342a4a5a3b6b5473ed32 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -1,18 +1,18 @@ # ApplicationStateObserver -The **ApplicationStateObserver** module defines the listener to observe the application state. +The **ApplicationStateObserver** module defines an observer to listen for application state changes. It can be used as an input parameter in [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8) to listen for lifecycle changes of the current application. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| onForegroundApplicationChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | -| onAbilityStateChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | -| onProcessCreated8+ | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | -| onProcessDied8+ | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | -| onProcessStateChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | +| Name | | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | ------------------------- | +| onForegroundApplicationChanged8+ | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | +| onAbilityStateChanged8+ | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | +| onProcessCreated8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | +| onProcessDied8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | +| onProcessStateChanged8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md index 24b284ed85986d96e58afba9c2bc4ff75804ebca..3c0e5e3806181cbff0492cfe4faa387f315e516b 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md @@ -1,23 +1,28 @@ # BaseContext -The abstract class **BaseContext** specifies whether its child class **Context** is used for the stage model or FA model. +**BaseContext** is an abstract class that specifies whether a child class **Context** is used for the stage model or FA model. It is the parent class for all types of **Context**. > **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 initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ------- | -| stageMode | boolean | Yes | Yes | Whether the context is used for the stage model.| +| stageMode | boolean | Yes | Yes | Whether the child class **Context** is used for the stage model.
**true**: used for the stage model.
**false**: used for the FA model.| **Example** - - ```ts - class MyContext extends BaseContext { - constructor(stageMode) { - this.stageMode = stageMode; - } - } - ``` + +Take the stage model as an example. You can access the **stageMode** field through **UIAbilityContext**. + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // EntryAbility onCreate, isStageMode: true + console.log("EntryAbility onCreate, isStageMode: " + this.context.stageMode); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md index 15e249798f9f731427b8b514b020abde8e924053..2a4fe5eaaf05dd8f7e6c907966a8a411382a6daa 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -1,11 +1,11 @@ # Context -The **Context** module provides context for abilities or applications. It allows access to application-specific resources, as well as permission requests and verification. +The **Context** module provides context for abilities or applications. It allows access to application-specific resources. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module can be used only in the stage model. ## Attributes @@ -13,8 +13,8 @@ The **Context** module provides context for abilities or applications. It allows | Name | Type | Readable | Writable | Description | | ----------- | ------ | ---- | ---- | ------- | -| resourceManager | resmgr.ResourceManager | Yes | No | Object for resource management. | -| applicationInfo | ApplicationInfo | Yes | No | Application information.| +| resourceManager | resmgr.[ResourceManager](js-apis-resource-manager.md) | Yes | No | Object for resource management. | +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information.| | cacheDir | string | Yes | No | Cache directory.| | tempDir | string | Yes | No | Temporary directory.| | filesDir | string | Yes | No | File directory.| @@ -25,20 +25,21 @@ The **Context** module provides context for abilities or applications. It allows | eventHub | string | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.| | area | [AreaMode](#areamode) | Yes | No | Area in which the file to be access is located.| - ## Context.createBundleContext createBundleContext(bundleName: string): Context; Creates the context based on the bundle name. +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** @@ -46,10 +47,24 @@ Creates the context based on the bundle name. | -------- | -------- | | Context | Context created.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts -let bundleContext = this.context.createBundleContext("com.example.test"); +let bundleContext; +try { + bundleContext = this.context.createBundleContext("com.example.test"); +} catch (error) { + console.log('createBundleContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} ``` ## Context.createModuleContext @@ -72,10 +87,24 @@ Creates the context based on the module name. | -------- | -------- | | Context | Context created.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts -let moduleContext = this.context.createModuleContext("entry"); +let moduleContext; +try { + moduleContext = this.context.createModuleContext("entry"); +} catch (error) { + console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} ``` createModuleContext(bundleName: string, moduleName: string): Context; @@ -88,7 +117,7 @@ Creates the context based on the bundle name and module name. | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| | moduleName | string | Yes | Module name.| **Return value** @@ -97,17 +126,31 @@ Creates the context based on the bundle name and module name. | -------- | -------- | | Context | Context created.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts -let moduleContext = this.context.createModuleContext("com.example.test", "entry"); +let moduleContext; +try { + moduleContext = this.context.createModuleContext("com.example.test", "entry"); +} catch (error) { + console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} ``` ## Context.getApplicationContext getApplicationContext(): ApplicationContext; -Obtains the application context. +Obtains the context of this application. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -115,12 +158,18 @@ Obtains the application context. | Type| Description| | -------- | -------- | -| Context | Application context obtained.| +| [ApplicationContext](js-apis-inner-application-applicationContext.md) | Application context obtained.| **Example** ```ts -let applicationContext = this.context.getApplicationContext(); +let applicationContext; +try { + applicationContext = this.context.getApplicationContext(); +} catch (error) { + console.log('getApplicationContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} ``` ## AreaMode @@ -129,7 +178,7 @@ Enumerates the areas in which the file to be access can be located. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| EL1 | 0 | Device-level encryption area.| -| EL2 | 1 | User credential encryption area.| +| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.| +| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md index 93d138db23255a3c312e55a423411cdb29f211e5..b67c612c1b3b6dd82537b6dd5e6e7fcad2d6bdcb 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md @@ -1,37 +1,46 @@ # ContinueCallback -The **ContinueCallback** module defines the callback invoked when the mission continuation is complete. +The **ContinueCallback** module defines the callback function that indicates the result of mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission). + +## ContinueCallback.onContinueDone + +onContinueDone(result: number): void; + +Called when the mission continuation is complete. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -| Name | Type | Readable | Writable | Description | -| --------------------- | -------- | ---- | ---- | ------------------ | -| onContinueDone | function | Yes | No | Callback used to notify the user that the mission continuation is complete and return the continuation result. | +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | result | number | No| Mission continuation result.| **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager'; + import distributedMissionManager from '@ohos.distributedMissionManager' let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", - missionId: 123, - wantParam: { - "key":"value" - } + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } }; let continueCallback = { onContinueDone(result) { console.log('onContinueDone, result: ' + JSON.stringify(result)); } - } + }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { - if (error.code != 0) { - console.error('continueMission failed, cause: ' + JSON.stringify(error)) - } - console.info('continueMission finished') + if (error && error.code) { + console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + console.log('continueMission finished'); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md index b42044ef893ebd23f97549ad378f21dcf8067c93..5582132e3f610a76175cbb73796b6283498c4395 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md @@ -1,6 +1,6 @@ # ContinueDeviceInfo -The **ContinueDeviceInfo** module defines the parameters required for mission continuation. +The **ContinueDeviceInfo** module defines the parameters required for initiating mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -14,27 +14,28 @@ The **ContinueDeviceInfo** module defines the parameters required for mission co **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager'; + import distributedMissionManager from '@ohos.distributedMissionManager' let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", - missionId: 123, - wantParam: { - "key":"value" - } + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } }; let continueCallback = { onContinueDone(result) { console.log('onContinueDone, result: ' + JSON.stringify(result)); } - } + }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { - if (error.code != 0) { - console.error('continueMission failed, cause: ' + JSON.stringify(error)) - } - console.info('continueMission finished') + if (error && error.code) { + console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + console.log('continueMission finished'); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md index 056a2313dd1aeffdcd69812c491e9e03a77f5f41..271f2697803dde9d0b3f78c3bb661a03d925b95e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md @@ -1,8 +1,8 @@ # ErrorObserver -The **ErrorObserver** module defines the listener to observe errors. +The **ErrorObserver** module defines an observer to listen for application errors. It can be used as an input parameter in [ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron) to listen for errors that occur in the current application. -## onUnhandledException +## ErrorObserver.onUnhandledException onUnhandledException(errMsg: string): void; @@ -16,15 +16,21 @@ Called when an unhandled exception occurs in the JS runtime. | -------- | -------- | -------- | -------- | | errMsg | string | No| Message and error stack trace about the exception.| -**Example** +**Example** ```ts -import errorManager from '@ohos.application.errorManager'; +import errorManager from '@ohos.app.ability.errorManager' let observer = { onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ' + JSON.stringify(errorMsg)); + console.log('HXW onUnhandledException, errorMsg: ', errorMsg); } } -errorManager.registerErrorObserver(observer) + +try { + errorManager.on("error", observer); +} catch (error) { + console.log('registerErrorObserver' + ' failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md index 9c45684cd9faaf03a8de66ba73541ae75ded9cc3..8b580177c7622b33b0d2c06749a928e825ae84bc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md @@ -3,22 +3,24 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and trigger events. > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module can be used only in the stage model. ## Usage -Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. +Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **UIAbility** instance. ```ts -import Ability from '@ohos.application.Ability'; -export default class MainAbility extends Ability { - func1(){ - console.log("func1 is called"); +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + eventFunc(){ + console.log("eventFunc is called"); } + onForeground() { - this.context.eventHub.on("123", this.func1); + this.context.eventHub.on("myEvent", this.eventFunc); } } ``` @@ -38,34 +40,37 @@ Subscribes to an event. | event | string | Yes| Event name.| | callback | Function | Yes| Callback invoked when the event is triggered.| -**Example** - - ```ts - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", () => { - console.log("call anonymous func 1"); - }); - // Result - // func1 is called - // call anonymous func 1 - this.context.eventHub.emit("123"); - } - func1() { - console.log("func1 is called"); - } - } - ``` +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc); + // Anonymous functions can be used to subscribe to events. + this.context.eventHub.on("myEvent", () => { + console.log("call anonymous eventFunc"); + }); + // Result + // eventFunc is called + // call anonymous eventFunc + this.context.eventHub.emit("myEvent"); + } + + eventFunc() { + console.log("eventFunc is called"); + } +} +``` ## EventHub.off off(event: string, callback?: Function): void; -Unsubscribes from an event. If **callback** is specified, this API unsubscribes from the specified callback. If **callback** is not specified, this API unsubscribes from all callbacks in the event. +Unsubscribes from an event. + - If **callback** is specified, this API unsubscribes from the given event with the specified callback. + - If **callback** is not specified, this API unsubscribes from the given event with all callbacks. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -74,30 +79,31 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| Event name.| -| callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| - -**Example** - - ```ts - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.off("123", this.func1); // Unsubscribe from func1. - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", this.func2); - this.context.eventHub.off("123"); // Unsubscribe from func1 and func2. - } - func1() { - console.log("func1 is called"); - } - func2() { - console.log("func2 is called"); - } - } - ``` +| callback | Function | No| Callback for the event. If **callback** is unspecified, the given event with all callbacks is unsubscribed.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc1); + this.context.eventHub.off("myEvent", this.eventFunc1); // Unsubscribe from the myEvent event with the callback eventFunc1. + this.context.eventHub.on("myEvent", this.eventFunc1); + this.context.eventHub.on("myEvent", this.eventFunc2); + this.context.eventHub.off("myEvent"); // Unsubscribe from the myEvent event with all the callbacks (eventFunc1 and eventFunc2). + } + + eventFunc1() { + console.log("eventFunc1 is called"); + } + eventFunc2() { + console.log("eventFunc2 is called"); + } +} +``` ## EventHub.emit @@ -114,26 +120,27 @@ Triggers an event. | event | string | Yes| Event name.| | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| -**Example** - - ```ts - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - // Result - // func1 is called,undefined,undefined - this.context.eventHub.emit("123"); - // Result - // func1 is called,1,undefined - this.context.eventHub.emit("123", 1); - // Result - // func1 is called,1,2 - this.context.eventHub.emit("123", 1, 2); - } - func1(a, b) { - console.log("func1 is called," + a + "," + b); - } - } - ``` +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc); + // Result + // eventFunc is called,undefined,undefined + this.context.eventHub.emit("myEvent"); + // Result + // eventFunc is called,1,undefined + this.context.eventHub.emit("myEvent", 1); + // Result + // eventFunc is called,1,2 + this.context.eventHub.emit("myEvent", 1, 2); + } + + eventFunc(argOne, argTwo) { + console.log("eventFunc is called," + argOne + "," + argTwo); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index 1ed64e2a07cc8e92a7d8310d4fb4d0c42d36ff5b..a855d9577c9ef364caa7436a89983ca58d320d3c 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -5,7 +5,7 @@ The **ExtensionContext** module, inherited from **Context**, implements the cont This module provides APIs for accessing resources of a specific Extension ability. An Extension ability can use the context directly provided by **ExtensionContext** or that extended from **ExtensionContext**. For example, **ServiceExtension** uses [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md), which extends the capabilities of starting, stopping, binding, and unbinding abilities based on **ExtensionContext**. > **NOTE** -> +> > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. @@ -61,10 +61,11 @@ export default class TheServiceExtension extends ServiceExtension { Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry. ```ts -import Ability from '@ohos.app.ability.Ability' -export default class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate"); + console.log("[Demo] EntryAbility onCreate"); let wantExt = { deviceId: "", bundleName: "com.example.TheServiceExtension", diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md index 9184ae6ce0f0b4b8dee355d96a4c28cf84013ef2..9485de9efd0dc76d78a905725fb742225b50340f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md @@ -1,15 +1,15 @@ # ExtensionRunningInfo -The **ExtensionRunningInfo** module provides running information and states for Extension abilities. +The **ExtensionRunningInfo** module encapsulates ExtensionAbility running information, which can be obtained through [getExtensionRunningInfos](js-apis-app-ability-abilityManager.md#getextensionrunninginfos). > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module are system APIs and cannot be called by third-party applications. +> - 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. +> - This module is marked as @systemapi and not visible to third-party applications. ## Usage -The Extension ability running information is obtained through an **abilityManager** instance. +Import the **abilityManager** module and obtain the ExtensionAbility running information by calling the method in the **abilityManager** module. ## Attributes @@ -17,29 +17,37 @@ The Extension ability running information is obtained through an **abilityManage | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extension | ElementName | Yes| No| Information that matches an Extension ability.| +| extension | [ElementName](js-apis-bundleManager-elementName.md) | Yes| No| ExtensionAbility information.| | pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| +| uid | number | Yes| No| UID of the application.| | processName | string | Yes| No| Process name.| -| startTime | number | Yes| No| Start time of the Extension ability.| +| startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.| | clientPackage | Array<String> | Yes| No| Names of all packages in the process.| -| type | [bundle.ExtensionAbilityType](js-apis-Bundle.md) | Yes| No| Extension ability type.| +| type | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes| No| ExtensionAbility type.| **Example** ```ts -import abilityManager from '@ohos.application.abilityManager'; -let upperLimit=1; -abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); - for (let i=0; i { + if (error && error.code) { + console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + + for (let i = 0; i < data.length; i++) { + let extensionRunningInfo = data[i]; + console.log("extensionRunningInfo.extension: " + JSON.stringify(extensionRunningInfo.extension)); + console.log("extensionRunningInfo.pid: " + JSON.stringify(extensionRunningInfo.pid)); + console.log("extensionRunningInfo.uid: " + JSON.stringify(extensionRunningInfo.uid)); + console.log("extensionRunningInfo.processName: " + JSON.stringify(extensionRunningInfo.processName)); + console.log("extensionRunningInfo.startTime: " + JSON.stringify(extensionRunningInfo.startTime)); + console.log("extensionRunningInfo.clientPackage: " + JSON.stringify(extensionRunningInfo.clientPackage)); + console.log("extensionRunningInfo.type: " + JSON.stringify(extensionRunningInfo.type)); + } + }); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index bc9cb28c60e10b88b377cece605e51730cbea3cd..d888ccdc51bef996937e9d2e6ef891980ffe457c 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -1,8 +1,8 @@ # FormExtensionContext -The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for Form Extension abilities. +The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for FormExtensionAbilities. -You can use the APIs of this module to start Form Extension abilities. +You can use the APIs of this module to start FormExtensionAbilities. > **NOTE** > @@ -11,21 +11,24 @@ You can use the APIs of this module to start Form Extension abilities. ## Usage -Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtension** instance. +Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtensionAbility** instance. ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; + export default class MyFormExtensionAbility extends FormExtensionAbility { - onAddForm() { - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } -} + onAddForm(want) { + let formContext = this.context; // Obtain a FormExtensionContext instance. + // ... + let dataObj1 = { + temperature: "11c", + "time": "11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +}; ``` ## startAbility @@ -48,23 +51,29 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Example** ```ts -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want, (error, data) => { - if (error) { - console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); - } else { - console.log(`FormExtensionContext startAbility success`); - } -}) +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onFormEvent(formId, message) { + // Call startAbility() when the message event is triggered. + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "EntryAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want, (error, data) => { + if (error) { + console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); + } else { + console.log('FormExtensionContext startAbility success'); + } + }); + } +}; ``` ## startAbility @@ -87,24 +96,30 @@ Starts an ability. This API uses a promise to return the result. | Type | Description | | ------------ | ---------------------------------- | -| Promise<void< | Promise that returns no value.| +| Promise<void> | Promise that returns no value.| **Example** ```ts -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want).then(() => { - console.info("StartAbility Success"); -}).catch((error) => { - console.info("StartAbility failed"); -}); +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onFormEvent(formId, message) { + // Call startAbility() when the message event is triggered. + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "EntryAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want).then(() => { + console.info("StartAbility Success"); + }).catch((error) => { + console.info("StartAbility failed"); + }); + } +}; ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md index e56a2a43e4603f1b2f8e0e2a9dfbaf303e938f7b..7ccae03fa363d0850338d07f1318a377f10fc293 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md @@ -1,14 +1,14 @@ -# MissionCallbacks +# MissionCallback -The **MissionCallbacks** module defines the callbacks that can be registered as a mission status listener. +The **MissionCallback** module defines the callbacks invoked after synchronization starts. These callbacks can be used as input parameters in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -| Name | Template | Readable | Writable | Description | -| --------------------- | -------- | ---- | ---- | ------------------ | -| notifyMissionsChanged | function | Yes | No | Callback used to notify the mission change event and return the device ID. | -| notifySnapshot | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID.| -| notifyNetDisconnect | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.| +| Name | Template | Readable| Writable| Description | +| ---------------------------------------------------- | -------- | ---- | ---- | ---------------------------------- | +| notifyMissionsChanged(deviceId: string) | function | Yes | No | Callback used to notify the mission change event and return the device ID. | +| notifySnapshot(deviceId: string, mission: number) | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID. | +| notifyNetDisconnect(deviceId: string, state: number) | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.| **Example** ```ts @@ -21,12 +21,12 @@ let missionCallback = { notifyMissionsChanged: function (deviceId) { console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); }, - notifySnapshot: function (mission, deviceId) { - console.log("notifySnapshot mission: " + JSON.stringify(mission)); + notifySnapshot: function (deviceId, mission) { console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + console.log("notifySnapshot mission: " + JSON.stringify(mission)); }, - notifyNetDisconnect: function (mission, state) { - console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); + notifyNetDisconnect: function (deviceId, state) { + console.log("notifyNetDisconnect deviceId: " + JSON.stringify(deviceId)); console.log("notifyNetDisconnect state: " + JSON.stringify(state)); } }; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md index 028e5dafadb2c6b5c63486f82e08acb2e1f601c5..9157fc697346087895870a5bbd6e4a0368d6bde7 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md @@ -1,6 +1,6 @@ # MissionDeviceInfo -The **MissionDeviceInfo** module defines the parameters required for registering a listener. +The **MissionDeviceInfo** module defines the parameters required for registering a listener. It can be used as an input parameter in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md index 5240d4229fb1222c91bcbddac116b26e23e69dd9..afefb70c5a3e0b0059e4712992c3f736516bc2f7 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -1,34 +1,45 @@ # MissionInfo -The **MissionInfo** module defines the mission information of an ability. +The **MissionInfo** module defines detailed information about a mission. The information can be obtained through [getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| missionId | number | Yes| Yes| Mission ID.| -| runningState | number | Yes| Yes| Running state of the mission.| -| lockedState | boolean | Yes| Yes| Locked state of the mission.| -| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| -| want | [Want](js-apis-application-want.md) | Yes| Yes| Want information of the mission.| -| label | string | Yes| Yes| Label of the mission.| -| iconPath | string | Yes| Yes| Path of the mission icon.| -| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| +| missionId | number | Yes| Yes| Mission ID.| +| runningState | number | Yes| Yes| Running state of the mission.| +| lockedState | boolean | Yes| Yes| Locked state of the mission.| +| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| +| want | [Want](js-apis-application-want.md) | Yes| Yes| Want information of the mission.| +| label | string | Yes| Yes| Label of the mission.| +| iconPath | string | Yes| Yes| Path of the mission icon.| +| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| **Example** ```ts -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.app.ability.missionManager' -missionManager.getMissionInfo("12345", 1, (error, data) => { - console.info('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); - console.info('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); - console.info('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); - console.info('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); - console.info('getMissionInfo want is:' + JSON.stringify(data.want)); - console.info('getMissionInfo label is:' + JSON.stringify(data.label)); - console.info('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); - console.info('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); -}); +try { + missionManager.getMissionInfo("", 1, (error, data) => { + if (error.code) { + // Process service logic errors. + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + + console.log('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); + console.log('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); + console.log('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); + console.log('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); + console.log('getMissionInfo want is:' + JSON.stringify(data.want)); + console.log('getMissionInfo label is:' + JSON.stringify(data.label)); + console.log('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); + console.log('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md index 5dc8a425524082102b4a554e7b911a1e7a490e8b..9e2e2aa23a6589c0eb80075f8de60f65261e6903 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md @@ -1,6 +1,6 @@ # MissionParameter -The **MissionParameter** module defines the parameters required for mission synchronization. +The **MissionParameter** module defines the parameters required for mission synchronization. It can be used an input parameter in [startSyncRemoteMissions](js-apis-distributedMissionManager.md#distributedmissionmanagerstartsyncremotemissions). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md index bac1c9f6c38951f0ba4f5ab25a7e07d7a9441dcd..a97f3b32b71f90078cb03f32fa46262f5cf6b770 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -1,6 +1,6 @@ # MissionSnapshot -The **MissionSnapshot** module provides the mission snapshot information of an ability. +The **MissionSnapshot** module defines the snapshot of a mission. The snapshot can be obtained through [getMissionSnapShot](js-apis-app-ability-missionManager.md#missionmanagergetmissionsnapshot). > **NOTE** > @@ -11,7 +11,7 @@ The **MissionSnapshot** module provides the mission snapshot information of an a | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| ability | ElementName | Yes| Yes| Information that matches an ability.| +| ability | ElementName | Yes| Yes| Ability information of the mission.| | snapshot | [image.PixelMap](js-apis-image.md) | Yes| Yes| Snapshot of the mission.| ## How to Use @@ -20,19 +20,33 @@ The mission snapshot information can be obtained by using **getMissionSnapShot** **Example** ```ts -import ElementName from '@ohos.bundle'; -import image from '@ohos.multimedia.image'; -import missionManager from '@ohos.application.missionManager'; - -missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) -}) + import ElementName from '@ohos.bundle'; + import image from '@ohos.multimedia.image'; + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.getMissionSnapShot("", id, (err, snapshot) => { + if (err.code) { + console.log("getMissionInfos failed, err.code:" + JSON.stringify(err.code) + + "err.message:" + JSON.stringify(err.message)); + return; + } + + // Carry out normal service processing. + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processData.md b/en/application-dev/reference/apis/js-apis-inner-application-processData.md index 75d7312c7144f725e0d47e6aed6e3bc594ce3989..c6e91944c5ed16800f3a2a7785de5a5e60dc623a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -1,6 +1,6 @@ # ProcessData -The **ProcessData** module defines process data. +The **ProcessData** module defines process data. If a lifecycle change listener is registered by calling [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8), the **onProcessCreated** callback in [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) is invoked when the lifecycle of an application or ability changes. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -10,9 +10,10 @@ The **ProcessData** module defines process data. | ----------------------- | ---------| ---- | ---- | ------------------------- | | pid8+ | number | Yes | No | Process ID. | | bundleName8+ | string | Yes | No | Bundle name of the application. | -| uid8+ | number | Yes | No | User ID. | -| isContinuousTask9+ | boolean | Yes | No | Whether the process is a continuous task. | -| isKeepAlive9+ | boolean | Yes | No | Whether the process remains active. | +| uid8+ | number | Yes | No | UID of the application. | +| isContinuousTask9+ | boolean | Yes | No | Whether the task is a continuous task. The value **true** means that the task is a continuous task, and **false** means the opposite. | +| isKeepAlive9+ | boolean | Yes | No | Whether the process is a resident task. The value **true** means that the process is a resident, and **false** means the opposite. | +| state9+ | number | Yes | No | Application state. The value can be **0** (newly created), **2** (foreground), **4** (background), or **5** (terminated). | **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index 8534ed198099f17a00769d2627349752a38aef62..0652791f728de12c144459146287ecbbb680480e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -1,6 +1,6 @@ # ProcessRunningInfo -The **ProcessRunningInfo** module provides process running information. +The **ProcessRunningInfo** module defines the running information of a process. > **NOTE** > - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-inner-application-processRunningInformation.md) instead. @@ -19,12 +19,13 @@ The **ProcessRunningInfo** module provides process running information. ## Usage -The process running information is obtained through [getProcessRunningInfos](js-apis-application-appManager.md##appManager.getProcessRunningInfos(deprecated)). +The process running information is obtained by using [getProcessRunningInfos](js-apis-application-appManager.md#appmanagergetprocessrunninginfosdeprecated) in **appManager**. **Example** ```ts import appManager from '@ohos.application.appManager'; -app.getProcessRunningInfos().then((data) => { + +appManager.getProcessRunningInfos().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md index bae1a6f2761c1f8de4873875d0578819a43ddea2..a376446b2af90c8cc13f6eee80a10a5399dae041 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md @@ -1,6 +1,6 @@ # ProcessRunningInformation -The **ProcessRunningInformation** module provides process running information. +The **ProcessRunningInformation** module defines the running information of a process. > **NOTE** > @@ -8,12 +8,13 @@ The **ProcessRunningInformation** module provides process running information. ## How to Use -The process running information is obtained through [appManager](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9). +The process running information is obtained through [getProcessRunningInformation](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9) in **appManager**. ```ts import appManager from '@ohos.application.appManager'; -appManager.getProcessRunningInformation((error,data) => { - console.log("getProcessRunningInformation error: " + error.code + " data: " + JSON.stringify(data)); + +appManager.getProcessRunningInformation((error, data) => { + console.log("error: " + error.code + " data: " + JSON.stringify(data)); }); ``` @@ -21,9 +22,9 @@ appManager.getProcessRunningInformation((error,data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| bundleNames | Array<string> | Yes| No| Names of all running bundles in the process.| +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| bundleNames | Array<string> | Yes| No| Names of all running bundles in the process.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index bfe660ebd6d4f0fb64a0380a3fee7b2470e9a3b3..ae6beb1357d9d25dfcd06cbcd1d65df660fa44bb 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -1,6 +1,6 @@ # ServiceExtensionContext -The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for Service Extension abilities. +The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for ServiceExtensionAbilities. You can use the APIs of this module to start, terminate, connect, and disconnect abilities. @@ -17,9 +17,9 @@ Before using the **ServiceExtensionContext** module, you must define a child cla import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; let context = undefined; - class MainAbility extends ServiceExtensionAbility { + class EntryAbility extends ServiceExtensionAbility { onCreate() { - context = this.context; + context = this.context; // Obtain a ServiceExtensionContext instance. } } ``` @@ -36,10 +36,10 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | callback | AsyncCallback<void> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -103,16 +103,16 @@ Starts an ability. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -214,8 +214,8 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0 @@ -245,6 +245,11 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -287,8 +292,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -316,6 +321,11 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -359,8 +369,8 @@ Starts an ability with the account ID and start options specified. This API uses ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -392,6 +402,11 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Starts an ability with the account ID specified. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -406,9 +421,9 @@ Starts an ability with the account ID specified. This API uses a promise to retu **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -440,8 +455,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -470,7 +485,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -505,8 +520,8 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -531,7 +546,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a new ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -545,9 +560,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -571,8 +586,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -597,9 +612,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +Starts a new ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -637,8 +652,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -664,9 +679,9 @@ Starts a new Service Extension ability with the account ID specified. This API u startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +Starts a new ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -681,9 +696,9 @@ Starts a new Service Extension ability with the account ID specified. This API u **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -708,8 +723,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -735,7 +750,7 @@ Starts a new Service Extension ability with the account ID specified. This API u stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -767,8 +782,8 @@ Stops a Service Extension ability in the same application. This API uses an asyn ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -793,7 +808,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -807,9 +822,9 @@ Stops a Service Extension ability in the same application. This API uses a promi **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -830,8 +845,8 @@ Stops a Service Extension ability in the same application. This API uses a promi ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -856,9 +871,9 @@ Stops a Service Extension ability in the same application. This API uses a promi stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -892,8 +907,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -919,9 +934,9 @@ Stops a Service Extension ability in the same application with the account ID sp stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -936,9 +951,9 @@ Stops a Service Extension ability in the same application with the account ID sp **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -960,8 +975,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -995,9 +1010,9 @@ Terminates this ability. This API uses an asynchronous callback to return the re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -1037,9 +1052,9 @@ Terminates this ability. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -1069,7 +1084,7 @@ Terminates this ability. This API uses a promise to return the result. connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; -Connects this ability to a Service ability. +Connects this ability to a ServiceAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1077,16 +1092,16 @@ Connects this ability to a Service ability. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| **Return value** - | Type| Description| - | -------- | -------- | - | number | A number, based on which the connection will be interrupted.| +| Type| Description| +| -------- | -------- | +| number | A number, based on which the connection will be interrupted.| **Error codes** @@ -1165,8 +1180,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1189,7 +1204,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback<void>): void; -Disconnects this ability from the Service ability. This API uses an asynchronous callback to return the result. +Disconnects this ability from the ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1197,10 +1212,10 @@ Disconnects this ability from the Service ability. This API uses an asynchronous **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | connection | number | Yes| Number returned after **connectAbility** is called.| - | callback | AsyncCallback<void> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Number returned after **connectAbility** is called.| +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -1241,7 +1256,7 @@ Disconnects this ability from the Service ability. This API uses an asynchronous disconnectServiceExtensionAbility(connection: number): Promise<void>; -Disconnects this ability from the Service ability. This API uses a promise to return the result. +Disconnects this ability from the ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1249,15 +1264,15 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | connection | number | Yes| Number returned after **connectAbility** is called.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Number returned after **connectAbility** is called.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -1300,6 +1315,11 @@ startAbilityByCall(want: Want): Promise<Caller>; Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -1341,7 +1361,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }; @@ -1372,7 +1392,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "", parameters: { "ohos.aafwk.param.callAbilityToForeground": true diff --git a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 23c4e8d48a1b3755c829c1a9e775a1eb9bdba908..51b10659d38d55686ced548c624798d77391f102 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -25,7 +25,7 @@ let cmd = "cmd"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { - console.info("executeShellCommand callback, failed: ", err); - console.info("executeShellCommand callback, success: ", data); + console.info("executeShellCommand callback, result: ", err); + console.info("executeShellCommand callback, data: ", data); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 394f484144b3cf2f5fdf071ea22e2a38fe652739..f8528cc1bf6c8b4468c5c475934fe1c91c70490a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -1,8 +1,6 @@ # UIAbilityContext -The **UIAbilityContext** module, inherited from **Context**, implements the context for abilities. - -This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box. +**UIAbilityContext**, inherited from [Context](js-apis-inner-application-context.md), provides the context environment for [UIAbility](js-apis-app-ability-uiAbility.md). **UIAbilityContext** provides UIAbility-related configuration and APIs for operating UIAbilities and ServiceExtensionAbilities. For example, you can use the APIs to start a UIAbility, terminate a UIAbility to which the UIAbilityContext belongs, and start, terminate, connect to, or disconnect from a ServiceExtensionAbility. > **NOTE** > @@ -15,16 +13,24 @@ This module provides APIs for accessing ability-specific resources. You can use | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| Ability information.| -| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the current HAP.| -| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration information.| +| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| UIAbility information.| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| HAP information.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| UIAbility configuration, such as the language and color mode.| + +> **NOTE** +> - In the sample code provided in this topic, **this.context** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** capabilities on pages, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). -## AbilityContext.startAbility +## UIAbilityContext.startAbility startAbility(want: Want, callback: AsyncCallback<void>): void; Starts an ability. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -71,7 +77,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. if (error.code) { // Process service logic errors. console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -79,18 +85,22 @@ Starts an ability. This API uses an asynchronous callback to return the result. }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` - -## AbilityContext.startAbility +## UIAbilityContext.startAbility startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void; Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -103,7 +113,7 @@ Starts an ability with the start options specified. This API uses an asynchronou **Error codes** -| ID| Error Message +| ID| Error Message| | ------- | -------------------------------- | | 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | @@ -130,7 +140,7 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var options = { @@ -142,7 +152,7 @@ Starts an ability with the start options specified. This API uses an asynchronou if (error.code) { // Process service logic errors. console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -150,17 +160,22 @@ Starts an ability with the start options specified. This API uses an asynchronou }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbility +## UIAbilityContext.startAbility startAbility(want: Want, options?: StartOptions): Promise<void>; Starts an ability. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -208,33 +223,37 @@ Starts an ability. This API uses a promise to return the result. abilityName: "MyAbility" }; var options = { - windowMode: 0, + windowMode: 0, }; try { this.context.startAbility(want, options) - .then((data) => { + .then(() => { // Carry out normal service processing. console.log('startAbility succeed'); }) .catch((error) => { // Process service logic errors. console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` - -## AbilityContext.startAbilityForResult +## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -274,7 +293,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; @@ -283,25 +302,29 @@ Starts an ability. This API uses an asynchronous callback to return the result w if (error.code) { // Process service logic errors. console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + - result.resultCode) + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode) }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResult +## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -342,7 +365,7 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var options = { @@ -354,26 +377,30 @@ Starts an ability with the start options specified. This API uses an asynchronou if (error.code) { // Process service logic errors. console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + - result.resultCode) + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode) }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResult +## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -Starts an ability. This API uses a promise to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -419,11 +446,11 @@ Starts an ability. This API uses a promise to return the result when the ability ```ts var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + bundleName: "com.example.myapplication", + abilityName: "MainAbility" }; var options = { - windowMode: 0, + windowMode: 0, }; try { @@ -435,22 +462,27 @@ Starts an ability. This API uses a promise to return the result when the ability .catch((error) => { // Process service logic errors. console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResultWithAccount +## UIAbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -461,8 +493,8 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| **Error codes** @@ -494,7 +526,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -504,28 +536,33 @@ Starts an ability. This API uses an asynchronous callback to return the result w if (error.code) { // Process service logic errors. console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) + result.resultCode + ' result.want = ' + JSON.stringify(result.want)) }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResultWithAccount +## UIAbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +Starts an ability with the start options and account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -536,9 +573,9 @@ Starts an ability with the start options specified. This API uses an asynchronou | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback invoked when the ability is terminated.| **Error codes** @@ -570,7 +607,7 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -579,32 +616,36 @@ Starts an ability with the start options specified. This API uses an asynchronou }; try { - this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => { + this.context.startAbilityForResultWithAccount(want, accountId, options, (error) => { if (error.code) { // Process service logic errors. console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) + console.log("startAbilityForResultWithAccount succeed") }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResultWithAccount +## UIAbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed. +Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -615,14 +656,14 @@ Starts an ability with the start options specified. This API uses a promise to r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<AbilityResult> | Promise used to return the result.| +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the ability result when the ability is terminated.| **Error codes** @@ -654,7 +695,7 @@ Starts an ability with the start options specified. This API uses a promise to r ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -667,24 +708,24 @@ Starts an ability with the start options specified. This API uses a promise to r .then((result) => { // Carry out normal service processing. console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) + result.resultCode) }) .catch((error) => { // Process service logic errors. console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbility +## UIAbilityContext.startServiceExtensionAbility startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -694,7 +735,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -719,8 +760,8 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { @@ -728,7 +769,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t if (error.code) { // Process service logic errors. console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -736,16 +777,16 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbility +## UIAbilityContext.startServiceExtensionAbility startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -755,7 +796,7 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| **Error codes** @@ -779,35 +820,35 @@ Starts a new Service Extension ability. This API uses a promise to return the re ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { this.context.startServiceExtensionAbility(want) - .then((data) => { + .then(() => { // Carry out normal service processing. console.log('startServiceExtensionAbility succeed'); }) .catch((error) => { // Process service logic errors. console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbilityWithAccount +## UIAbilityContext.startServiceExtensionAbilityWithAccount startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -817,8 +858,8 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -840,8 +881,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -850,7 +891,7 @@ Starts a new Service Extension ability with the account ID specified. This API u if (error.code) { // Process service logic errors. console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -858,18 +899,18 @@ Starts a new Service Extension ability with the account ID specified. This API u }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbilityWithAccount +## UIAbilityContext.startServiceExtensionAbilityWithAccount startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +Starts a ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -880,7 +921,7 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| **Error codes** @@ -905,8 +946,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -919,19 +960,19 @@ Starts a new Service Extension ability with the account ID specified. This API u .catch((error) => { // Process service logic errors. console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbility +## UIAbilityContext.stopServiceExtensionAbility stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -941,7 +982,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -963,8 +1004,8 @@ Stops a Service Extension ability in the same application. This API uses an asyn ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { @@ -972,7 +1013,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn if (error.code) { // Process service logic errors. console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -980,16 +1021,16 @@ Stops a Service Extension ability in the same application. This API uses an asyn }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbility +## UIAbilityContext.stopServiceExtensionAbility stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -999,7 +1040,7 @@ Stops a Service Extension ability in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| **Error codes** @@ -1020,8 +1061,8 @@ Stops a Service Extension ability in the same application. This API uses a promi ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { @@ -1033,22 +1074,22 @@ Stops a Service Extension ability in the same application. This API uses a promi .catch((error) => { // Process service logic errors. console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbilityWithAccount +## UIAbilityContext.stopServiceExtensionAbilityWithAccount stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1058,8 +1099,8 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1082,8 +1123,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -1092,7 +1133,7 @@ Stops a Service Extension ability in the same application with the account ID sp if (error.code) { // Process service logic errors. console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1100,18 +1141,18 @@ Stops a Service Extension ability in the same application with the account ID sp }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbilityWithAccount +## UIAbilityContext.stopServiceExtensionAbilityWithAccount stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1121,8 +1162,8 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| **Error codes** @@ -1144,8 +1185,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -1158,16 +1199,16 @@ Stops a Service Extension ability in the same application with the account ID sp .catch((error) => { // Process service logic errors. console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.terminateSelf +## UIAbilityContext.terminateSelf terminateSelf(callback: AsyncCallback<void>): void; @@ -1195,20 +1236,26 @@ Terminates this ability. This API uses an asynchronous callback to return the re **Example** ```ts - this.context.terminateSelf((error) => { - if (error.code) { - // Process service logic errors. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('terminateSelf succeed'); - }); + try { + this.context.terminateSelf((error) => { + if (error.code) { + // Process service logic errors. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('terminateSelf succeed'); + }); + } catch (error) { + // Capture the synchronization parameter error. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } ``` -## AbilityContext.terminateSelf +## UIAbilityContext.terminateSelf terminateSelf(): Promise<void>; @@ -1236,22 +1283,30 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```ts - this.context.terminateSelf().then((data) => { - // Carry out normal service processing. - console.log('terminateSelf succeed'); - }).catch((error) => { - // Process service logic errors. + try { + this.context.terminateSelf() + .then(() => { + // Carry out normal service processing. + console.log('terminateSelf succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (error) { + // Capture the synchronization parameter error. console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); + ' error.message: ' + JSON.stringify(error.message)); + } ``` -## AbilityContext.terminateSelfWithResult +## UIAbilityContext.terminateSelfWithResult terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1277,8 +1332,8 @@ Terminates this ability. This API uses an asynchronous callback to return the ab ```ts var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" + bundleName: "com.example.myapplication", + abilityName: "MainAbility" } var resultCode = 100; // AbilityResult information returned to the caller. @@ -1292,25 +1347,25 @@ Terminates this ability. This API uses an asynchronous callback to return the ab if (error.code) { // Process service logic errors. console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. console.log('terminateSelfWithResult succeed'); }); } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + // Process input parameter errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.terminateSelfWithResult +## UIAbilityContext.terminateSelfWithResult terminateSelfWithResult(parameter: AbilityResult): Promise<void>; -Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1342,8 +1397,8 @@ Terminates this ability. This API uses a promise to return the ability result in ```ts var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" + bundleName: "com.example.myapplication", + abilityName: "MainAbility" } var resultCode = 100; // AbilityResult information returned to the caller. @@ -1361,20 +1416,20 @@ Terminates this ability. This API uses a promise to return the ability result in .catch((error) => { // Process service logic errors. console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.connectServiceExtensionAbility +## UIAbilityContext.connectServiceExtensionAbility connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability. +Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1384,8 +1439,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No| Parameters for the connection.| +| want | [Want](js-apis-application-want.md) | Yes| Want information for connecting to the ServiceExtensionAbility.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.| **Return value** @@ -1410,13 +1465,19 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var options = { - onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, - onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } + onConnect(elementName, remote) { + console.log('----------- onConnect -----------') + }, + onDisconnect(elementName) { + console.log('----------- onDisconnect -----------') + }, + onFailed(code) { + console.log('----------- onFailed -----------') + } } var connection = null; @@ -1425,18 +1486,18 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.connectServiceExtensionAbilityWithAccount +## UIAbilityContext.connectServiceExtensionAbilityWithAccount connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. +Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template, with the account ID specified. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1447,8 +1508,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No| Parameters for the connection.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.| **Return value** @@ -1474,14 +1535,20 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; var options = { - onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, - onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } + onConnect(elementName, remote) { + console.log('----------- onConnect -----------') + }, + onDisconnect(elementName) { + console.log('----------- onDisconnect -----------') + }, + onFailed(code) { + console.log('----------- onFailed -----------') + } } var connection = null; @@ -1490,15 +1557,15 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.disconnectServiceExtensionAbility +## UIAbilityContext.disconnectServiceExtensionAbility disconnectServiceExtensionAbility(connection: number): Promise\; -Disconnects a connection. This API uses a promise to return the result. +Disconnects from a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1508,7 +1575,7 @@ Disconnects a connection. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Result code of the ability connection.| +| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.| **Return value** @@ -1551,11 +1618,11 @@ Disconnects a connection. This API uses a promise to return the result. } ``` -## AbilityContext.disconnectServiceExtensionAbility +## UIAbilityContext.disconnectServiceExtensionAbility disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; -Disconnects a connection. This API uses an asynchronous callback to return the result. +Disconnects from a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1565,7 +1632,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Result code of the ability connection.| +| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1590,7 +1657,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r if (error.code) { // Process service logic errors. console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1599,16 +1666,21 @@ Disconnects a connection. This API uses an asynchronous callback to return the r } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityByCall +## UIAbilityContext.startAbilityByCall startAbilityByCall(want: Want): Promise<Caller>; Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -1632,10 +1704,10 @@ Starts an ability in the foreground or background and obtains the caller object // Start an ability in the background by not passing parameters. var wantBackground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "" + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "" }; try { @@ -1645,14 +1717,14 @@ Starts an ability in the foreground or background and obtains the caller object caller = obj; console.log('startAbilityByCall succeed'); }).catch((error) => { - // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); + // Process service logic errors. + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1663,13 +1735,13 @@ Starts an ability in the foreground or background and obtains the caller object // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. var wantForeground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "", - parameters: { - "ohos.aafwk.param.callAbilityToForeground": true - } + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "", + parameters: { + "ohos.aafwk.param.callAbilityToForeground": true + } }; try { @@ -1679,24 +1751,29 @@ Starts an ability in the foreground or background and obtains the caller object caller = obj; console.log('startAbilityByCall succeed'); }).catch((error) => { - // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); + // Process service logic errors. + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityWithAccount +## UIAbilityContext.startAbilityWithAccount startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1707,7 +1784,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1740,7 +1817,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -1750,7 +1827,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c if (error.code) { // Process service logic errors. console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1759,18 +1836,23 @@ Starts an ability with the account ID specified. This API uses an asynchronous c } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityWithAccount +## UIAbilityContext.startAbilityWithAccount startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1781,8 +1863,8 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1815,7 +1897,7 @@ Starts an ability with the account ID and start options specified. This API uses ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -1828,7 +1910,7 @@ Starts an ability with the account ID and start options specified. This API uses if (error.code) { // Process service logic errors. console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1836,19 +1918,24 @@ Starts an ability with the account ID and start options specified. This API uses }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityWithAccount +## UIAbilityContext.startAbilityWithAccount startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; Starts an ability with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1859,7 +1946,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| **Error codes** @@ -1892,7 +1979,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -1909,75 +1996,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu .catch((error) => { // Process service logic errors. console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; - -Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Yes| Callback used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); - }); - - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; - -Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Promise used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - - ``` - - -## AbilityContext.setMissionLabel +## UIAbilityContext.setMissionLabel setMissionLabel(label: string, callback:AsyncCallback<void>): void; @@ -1995,13 +2023,12 @@ Sets a label for this ability in the mission. This API uses an asynchronous call **Example** ```ts - this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); + this.context.setMissionLabel("test", (result) => { + console.log('setMissionLabel:' + JSON.stringify(result)); }); ``` - -## AbilityContext.setMissionLabel +## UIAbilityContext.setMissionLabel setMissionLabel(label: string): Promise<void>; @@ -2025,12 +2052,12 @@ Sets a label for this ability in the mission. This API uses a promise to return ```ts this.context.setMissionLabel("test").then(() => { - console.log('success'); + console.log('success'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('failed:' + JSON.stringify(error)); }); ``` -## AbilityContext.setMissionIcon +## UIAbilityContext.setMissionIcon setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; @@ -2050,29 +2077,29 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call **Example** ```ts - import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { - size: { - height: 100, - width: 100 - } - }; - image.createPixelMap(color, initializationOptions) - .then((data) => { - imagePixelMap = data; - }) - .catch((err) => { - console.log('--------- createPixelMap fail, err: ---------', err) - }); - this.context.setMissionIcon(imagePixelMap, (err) => { - console.log('---------- setMissionIcon fail, err: -----------', err); + import image from '@ohos.multimedia.image'; + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap, (err) => { + console.log('---------- setMissionIcon fail, err: -----------', err); + }) ``` -## AbilityContext.setMissionIcon +## UIAbilityContext.setMissionIcon setMissionIcon(icon: image.PixelMap): Promise\; @@ -2097,31 +2124,30 @@ Sets an icon for this ability in the mission. This API uses a promise to return **Example** ```ts - import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { - size: { - height: 100, - width: 100 - } - }; - image.createPixelMap(color, initializationOptions) - .then((data) => { - imagePixelMap = data; - }) - .catch((err) => { - console.log('--------- createPixelMap fail, err: ---------', err) - }); - this.context.setMissionIcon(imagePixelMap) - .then(() => { - console.log('-------------- setMissionIcon success -------------'); - }) - .catch((err) => { - console.log('-------------- setMissionIcon fail, err: -------------', err); - }); + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; + }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap) + .then(() => { + console.log('-------------- setMissionIcon success -------------'); + }) + .catch((err) => { + console.log('-------------- setMissionIcon fail, err: -------------', err); + }); ``` -## AbilityContext.restoreWindowStage +## UIAbilityContext.restoreWindowStage restoreWindowStage(localStorage: LocalStorage) : void; @@ -2138,11 +2164,11 @@ Restores the window stage data for this ability. **Example** ```ts - var storage = new LocalStorage(); - this.context.restoreWindowStage(storage); + var storage = new LocalStorage(); + this.context.restoreWindowStage(storage); ``` -## AbilityContext.isTerminating +## UIAbilityContext.isTerminating isTerminating(): boolean; diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md index 6d93123f0ca73a7089b640f2f1cb98cc3df4308c..8facc43fc842570c3eb0ea95a141bdaa77dcf252 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -1,6 +1,6 @@ # WantAgentInfo -The **WantAgentInfo** module defines the information required for triggering the WantAgent. +The **WantAgentInfo** module defines the information required for triggering a **WantAgent** object. The information can be used as an input parameter in [getWantAgent](js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to obtain a specified **WantAgent** object. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -9,38 +9,5 @@ The **WantAgentInfo** module defines the information required for triggering the | wants | Array\ | Yes | Array of all **Want** objects. | | operationType | wantAgent.OperationType | Yes | Operation type. | | requestCode | number | Yes | Request code defined by the user.| -| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-wantAgent.md#WantAgentFlags)> | No | Array of flags for using the **WantAgent** object. | +| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object. | | extraInfo | {[key: string]: any} | No | Extra information. | - -**Example** -```ts -import wantAgent from '@ohos.wantAgent'; - -let wantAgentInfo = { - wants: [ - { - deviceId: "", - bundleName: "com.example.apicoverhaptest", - abilityName: "com.example.apicoverhaptest.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true.true,false}", - parameters: { - myKey0: 2222 - } - } - ], - operationType: wantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], - extraInfo:{ - "key": "value" - } -} -wantAgent.getWantAgent(wantAgentInfo).then((data) =>{ - console.info("getWantAgent data: " + JSON.stringify(data)); -}).catch((err) => { - console.error("getWantAgent err: " + JSON.stringify(err)); -}) -``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index 7f0868a36b356797f8e4a39c31e13a7c1396d239..b33db13faa840a1660a42e612ef5a4d523241877 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -1,4 +1,4 @@ -# InputMethodExtensionContext +# @ohos.inputmethodextensioncontext (InputMethodExtensionContext) The **InputMethodExtensionContext** module, inherited from **ExtensionContext**, provides context for **InputMethodExtension** abilities. @@ -20,7 +20,7 @@ Before using the **InputMethodExtensionContext** module, you must define a child ```js import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; -class MainAbility extends InputMethodExtensionAbility { +class EntryAbility extends InputMethodExtensionAbility { onCreate() { let context = this.context; } diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index 0c3651fc6add2e830f9a8e3eeb5ccabddb122e2e..3dc9a22442c07759d3b594297f7828cb7d5cc95b 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -1,4 +1,4 @@ -# @ohos.bundle.installer +# @ohos.bundle.installer (installer) The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 2034cae2ba7d64c6f593f937a4c944e39e5ac04c..d4f3449adae43eed9b19236aec0d0308feed89e8 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,20 +1,20 @@ # @ohos.intl (Internationalization) -The **intl** module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. +The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. +The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities. -The [i18n](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - This module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n interfaces defined in ECMA 402. For details about the enhanced i18n capabilities, see [i18n](js-apis-i18n.md). ## Modules to Import -``` +```js import Intl from '@ohos.intl'; ``` - +Importing an incorrect bundle can lead to unexpected API behavior. ## Locale @@ -23,16 +23,16 @@ import Intl from '@ohos.intl'; **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | language | string | Yes | No | Language associated with the locale, for example, **zh**. | | script | string | Yes | No | Script type of the language, for example, **Hans**. | | region | string | Yes | No | Region associated with the locale, for example, **CN**. | | baseName | string | Yes | No | Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**. | | caseFirst | string | Yes | No | Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| -| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| | collation | string | Yes | No | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| +| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, or **h24**.| | numberingSystem | string | Yes | No | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | No | Whether to apply special collation rules for numeric characters. | @@ -41,13 +41,16 @@ import Intl from '@ohos.intl'; constructor() -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var locale = new Intl.Locale(); + ```js + // The default constructor uses the current system locale to create a Locale object. + let locale = new Intl.Locale() + // Return the current system locale. + let localeID = locale.toString() ``` @@ -55,20 +58,22 @@ Creates a Locale object. constructor(locale: string, options?: LocaleOptions) -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------- | ---- | ---------------------------- | -| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| | options9+ | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | **Example** - ``` - var locale = new Intl.Locale("zh-CN"); + ```js + // Create a Locale object named zh-CN. + let locale = new Intl.Locale("zh-CN") + let localeID = locale.toString() // localeID = "zh-CN" ``` @@ -76,20 +81,21 @@ Creates a Locale object. toString(): string -Converts locale information to a string. +Obtains the string representation of a **Locale** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ------ | ----------- | -| string | String containing locale information.| +| string | String representation of the **Locale** object.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.toString(); + ```js + // Create a Locale object named en-GB. + let locale = new Intl.Locale("en-GB"); + let localeID = locale.toString(); // localeID = "en-GB" ``` @@ -101,16 +107,25 @@ Maximizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the maximized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.maximize(); + ```js + // Create a Locale object named zh. + let locale = new Intl.Locale("zh"); + // Complete the script and region of the Locale object. + let maximizedLocale = locale.maximize(); + let localeID = maximizedLocale.toString(); // localeID = "zh-Hans-CN" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Complete the script of the Locale object. + maximizedLocale = locale.maximize(); + localeID = maximizedLocale.toString(); // localeID = "en-Latn-US" ``` @@ -122,16 +137,25 @@ Minimizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the minimized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.minimize(); + ```js + // Create a Locale object named zh-Hans-CN. + let locale = new Intl.Locale("zh-Hans-CN"); + // Remove the script and region of the Locale object. + let minimizedLocale = locale.minimize(); + let localeID = minimizedLocale.toString(); // localeID = "zh" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Remove the region of the Locale object. + minimizedLocale = locale.minimize(); + localeID = minimizedLocale.toString(); // localeID = "en" ``` @@ -141,11 +165,11 @@ Represents the locale options. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | -| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**,**search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| +| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | Yes | Whether to use the 12-hour clock. | | caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| @@ -163,8 +187,9 @@ Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var datefmt= new Intl.DateTimeFormat(); + ```js + // Use the current system locale to create a DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(); ``` @@ -178,20 +203,22 @@ Creates a **DateTimeOptions** object for the specified locale. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | **Example** - ``` - var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use locale zh-CN to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + let datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); ``` **Example** - ``` - var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use the locale list ["ban", "zh"] to create a DateTimeFormat object. Because ban is an invalid locale ID, locale zh is used to create the DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); ``` @@ -209,17 +236,22 @@ Formats the specified date and time. | ---- | ---- | ---- | ------- | | date | Date | Yes | Date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ------------ | | string | A string containing the formatted date and time.| **Example** - ``` - var date = new Date(2021, 11, 17, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.format(date); + ```js + let date = new Date(2021, 11, 17, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDate = datefmt.format(date); // formattedDate "17/12/2021" + + // Use locale en-GB to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + formattedDate = datefmt.format(date); // formattedDate "Friday, 17 December 2021 at 03:24:00" ``` @@ -238,18 +270,19 @@ Formats the specified date range. | startDate | Date | Yes | Start date and time to be formatted.| | endDate | Date | Yes | End date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | -------------- | | string | A string containing the formatted date and time range.| **Example** - ``` - var startDate = new Date(2021, 11, 17, 3, 24, 0); - var endDate = new Date(2021, 11, 18, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.formatRange(startDate, endDate); + ```js + let startDate = new Date(2021, 11, 17, 3, 24, 0); + let endDate = new Date(2021, 11, 18, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDateRange = datefmt.formatRange(startDate, endDate); // formattedDateRange = "17/12/2021-18/12/2021" ``` @@ -261,16 +294,19 @@ Obtains the formatting options for **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------------------- | +| Type | Description | +| ------------------------------------ | ----------------------------- | | [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| **Example** - ``` - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.resolvedOptions(); + ```js + let datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + // Obtain the options of the DateTimeFormat object. + let options = datefmt.resolvedOptions(); + let dateStyle = options.dateStyle; // dateStyle = "full" + let timeStyle = options.timeStyle; // timeStyle = "medium" ``` @@ -280,12 +316,12 @@ Provides the options for the **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | dateStyle | string | Yes | Yes | Date display format. The value can be **long**, **short**, **medium**, or **full**.| | timeStyle | string | Yes | Yes | Time display format. The value can be **long**, **short**, **medium**, or **full**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | timeZone | string | Yes | Yes | Time zone represented by a valid IANA time zone ID. | | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | hour12 | boolean | Yes | Yes | Whether to use the 12-hour clock. | @@ -315,8 +351,9 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var numfmt = new Intl.NumberFormat(); + ```js + // Use the current system locale to create a NumberFormat object. + let numfmt = new Intl.NumberFormat(); ``` @@ -328,15 +365,17 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | **Example** - ``` - var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); + ```js + // Use locale en-GB to create a NumberFormat object. Set style to decimal and notation to scientific. + let numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); ``` @@ -354,7 +393,7 @@ Formats a number. | ------ | ------ | ---- | ---- | | number | number | Yes | Number to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | @@ -362,9 +401,10 @@ Formats a number. **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.format(1223); + ```js + // Use locale list ["en-GB", "zh"] to create a NumberFormat object. Because en-GB is a valid locale ID, it is used to create the NumberFormat object. + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + let formattedNumber = numfmt.format(1223); // formattedNumber = 1.223E3 ``` @@ -376,27 +416,30 @@ Obtains the options of the **NumberFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ------------------------------- | --------------------------- | +| Type | Description | +| -------------------------------- | --------------------------- | | [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.resolvedOptions(); + ```js + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + // Obtain the options of the NumberFormat object. + let options = numfmt.resolvedOptions(); + let style = options.style; // style = decimal + let notation = options.notation // notation = scientific ``` ## NumberOptions6+ -Provides the device capability. +Defines the device capability. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | currency | string | Yes | Yes | Currency unit, for example, **EUR**, **CNY**, or **USD**. | @@ -426,13 +469,14 @@ Provides the device capability. constructor() -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var collator = new Intl.Collator(); + ```js + // Use the system locale to create a Collator object. + let collator = new Intl.Collator(); ``` @@ -440,20 +484,21 @@ Creates a Collator object. constructor(locale: string | Array<string>, options?: CollatorOptions) -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | **Example** - ``` - var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); + ```js + // Use locale zh-CN to create a Collator object. Set localeMatcher to lookup and usage to sort. + let collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); ``` @@ -472,16 +517,18 @@ Compares two strings based on the sorting policy of the **Collator** object. | first | string | Yes | First string to compare. | | second | string | Yes | Second string to compare.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| **Example** - ``` - var collator = new Intl.Collator("zh-Hans"); - collator.compare("first", "second"); + ```js + // Use locale en-GB to create a Collator object. + let collator = new Intl.Collator("en-GB"); + // Compare the sequence of the first and second strings. + let compareResult = collator.compare("first", "second"); // compareResult = -1 ``` @@ -493,17 +540,19 @@ Returns properties reflecting the locale and collation options of a **Collator** **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------- | +| Type | Description | +| ------------------------------------ | ----------------- | | [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| **Example** - - ``` - var collator = new Intl.Collator("zh-Hans"); - var options = collator.resolvedOptions(); + ```js + let collator = new Intl.Collator("zh-Hans", { usage: 'sort', ignorePunctuation: true }); + // Obtain the options of the Collator object. + let options = collator.resolvedOptions(); + let usage = options.usage; // usage = "sort" + let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true ``` @@ -513,11 +562,11 @@ Represents the properties of a **Collator** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ----------------- | ------- | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | usage | string | Yes | Yes | Whether the comparison is for sorting or for searching. The value can be **sort** or **search**. | -| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| +| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **letiant**.| | ignorePunctuation | boolean | Yes | Yes | Whether punctuation is ignored. The value can be **true** or **false**. | | collation | string | Yes | Yes | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| | numeric | boolean | Yes | Yes | Whether numeric collation is used. The value can be **true** or **false**. | @@ -531,13 +580,14 @@ Represents the properties of a **Collator** object. constructor() -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var pluralRules = new Intl.PluralRules(); + ```js + // Use the system locale to create a PluralRules object. + let pluralRules = new Intl.PluralRules(); ``` @@ -545,19 +595,21 @@ Create a **PluralRules** object. constructor(locale: string | Array<string>, options?: PluralRulesOptions) -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | **Example** - ``` - var pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); + ```js + // Use locale zh-CN to create a PluralRules object. Set localeMatcher to lookup and type to cardinal. + let pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); ``` @@ -575,16 +627,23 @@ Obtains a string that represents the singular-plural type of the specified numbe | ---- | ------ | ---- | ------------ | | n | number | Yes | Number for which the singular-plural type is to be obtained.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| **Example** - ``` - var pluralRules = new Intl.PluralRules("zh-Hans"); - pluralRules.select(1); + ```js + // Use locale zh-Hans to create a PluralRules object. + let zhPluralRules = new Intl.PluralRules("zh-Hans"); + // Determine the singular-plural type corresponding to number 1 in locale zh-Hans. + let plural = zhPluralRules.select(1); // plural = other + + // Use locale en-US to create a PluralRules object. + let enPluralRules = new Intl.PluralRules("en-US"); + // Determine the singular-plural type corresponding to number 1 in locale en-US. + plural = enPluralRules.select(1); // plural = one ``` @@ -594,7 +653,7 @@ Represents the properties of a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | type | string | Yes | Yes | Sorting type. The value can be **cardinal** or **ordinal**. | @@ -617,8 +676,9 @@ Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat(); + ```js + // Use the system locale to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat(); ``` @@ -632,14 +692,15 @@ Creates a **RelativeTimeFormat** object. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | **Example** - ``` - var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. Set localeMatcher to lookup, numeric to always, and style to long. + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); ``` @@ -658,16 +719,18 @@ Formats the value and unit based on the specified locale and formatting options. | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | | string | Relative time after formatting.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); - relativetimefmt.format(3, "quarter") + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); + // Obtain the localized representation (in unit of quarter) of number 3 in locale zh-CN. + let formatResult = relativetimefmt.format(3, "quarter"); // formatResult = "3 quarters later" ``` @@ -675,7 +738,7 @@ Formats the value and unit based on the specified locale and formatting options. formatToParts(value: number, unit: string): Array<object> -Returns an array of RelativeTimeFormat objects in parts for locale-aware formatting. +Obtains an array of RelativeTimeFormat objects in parts for locale-aware formatting. **System capability**: SystemCapability.Global.I18n @@ -686,16 +749,17 @@ Returns an array of RelativeTimeFormat objects in parts for locale-aware formatt | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------------------- | --------------------------- | | Array<object> | An array of **RelativeTimeFormat** objects in parts.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); - var parts = relativetimefmt.format(10, "seconds"); + ```js + // Use locale en to create a RelativeTimeFormat object. Set numeric to auto. + let relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); + let parts = relativetimefmt.formatToParts(10, "seconds"); // parts = [ {type: "literal", value: "in"}, {type: "integer", value: 10, unit: "second"}, {type: "literal", value: "seconds"} ] ``` @@ -707,16 +771,19 @@ Obtains the formatting options for **RelativeTimeFormat** objects. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ---------------------------------------- | --------------------------------- | | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** - ``` - var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); - relativetimefmt.resolvedOptions(); + ```js + // Use locale en-GB to create a RelativeTimeFormat object. + let relativetimefmt= new Intl.RelativeTimeFormat("en-GB", { style: "short" }); + // Obtain the options of the RelativeTimeFormat object. + let options = relativetimefmt.resolvedOptions(); + let style = options.style; // style = "short" ``` @@ -726,20 +793,20 @@ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | | style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| -## RelativeTimeFormatResolvedOptions8+ +## RelativeTimeFormatResolvedOptions8+ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------ | ---- | ---- | ---------------------------------------- | | locale | string | Yes | Yes | A string containing locale information, including the language, optional script, and region. | | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index 1e966a2b659551a35649c3c087330e7d3059e182..89893c1c97d183c69765535141b2012fae9e080a 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -1,12 +1,13 @@ # @ohos.util.LightWeightMap (Nonlinear Container LightWeightMap) > **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. **LightWeightMap** stores key-value (KV) pairs. Each key must be unique and have only one value. -**LightWeightMap** is based on generics and uses a lightweight structure. Keys in the map are searched using hash values, which are stored in an array. +**LightWeightMap** is based on generics and uses a lightweight structure. Its default initial capacity is 8, and it has the capacity doubled in each expansion. + +The keys in such a set are searched using hash values, which are stored in an array. Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs, **LightWeightMap** occupies less memory. @@ -44,7 +45,7 @@ A constructor used to create a **LightWeightMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -73,7 +74,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -109,7 +110,7 @@ Checks whether this container contains all elements of the specified **LightWeig **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -149,7 +150,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -159,10 +160,8 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); -let result = lightWeightMap.hasKey; -lightWeightMap.hasKey("squirrel"); lightWeightMap.set("squirrel", 123); -let result1 = lightWeightMap.hasKey("squirrel"); +let result = lightWeightMap.hasKey("squirrel"); ``` @@ -188,7 +187,7 @@ Checks whether this container contains the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -214,7 +213,7 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -256,7 +255,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -294,7 +293,7 @@ Obtains the index of the first occurrence of an element with the specified key i **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -332,7 +331,7 @@ Obtains the index of the first occurrence of an element with the specified value **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -370,12 +369,12 @@ Obtains the key of an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getKeyAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -403,7 +402,7 @@ Adds all elements in a **LightWeightMap** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -416,7 +415,7 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); -lightWeightMap.setAll(map); +map.setAll(lightWeightMap); // Add all elements in lightWeightMap to the map. ``` @@ -442,7 +441,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -478,7 +477,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -516,7 +515,7 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -555,12 +554,12 @@ Sets a value for an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -594,12 +593,12 @@ Obtains the value of an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -621,7 +620,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -653,7 +652,7 @@ Obtains an iterator that contains all the keys in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -690,7 +689,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -735,7 +734,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -769,7 +768,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -800,13 +799,13 @@ Concatenates the elements in this container into a string and returns the string **Return value** -| Type| Description| -| -------- | -------- | -| String | String obtained.| + | Type| Description| + | -------- | -------- | + | String | String obtained.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -818,7 +817,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); -let iter = lightWeightMap.toString(); +let result = lightWeightMap.toString(); ``` ### [Symbol.iterator] @@ -837,7 +836,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index 0953c12b1a012870147f5be3481de8cd28f9edd6..25c7950dc4968bc3f9f33ad6b277ecdc68a6ea09 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -1,7 +1,6 @@ # @ohos.util.LightWeightSet (Nonlinear Container LightWeightSet) > **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. **LightWeightSet** stores a set of values, each of which must be unique. @@ -44,7 +43,7 @@ A constructor used to create a **LightWeightSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -73,7 +72,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -108,7 +107,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -138,7 +137,7 @@ Adds all elements in a **LightWeightSet** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -178,7 +177,7 @@ Checks whether this container contains all elements of the specified **LightWeig **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -218,7 +217,7 @@ Checks whether this container has the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -246,7 +245,7 @@ Checks whether this container contains objects of the same type as the specified | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| obj | Object | Yes| Object to be used for comparison.| +| obj | Object | Yes| **LightWeightSet** instance to be used for comparison.| **Return value** @@ -256,7 +255,7 @@ Checks whether this container contains objects of the same type as the specified **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -289,12 +288,12 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The increaseCapacityTo method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of minimumCapacity is out of range. | **Example** @@ -326,7 +325,7 @@ Obtains the position index of the element with the specified key in this contain **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -364,7 +363,7 @@ Removes an element of the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -402,7 +401,7 @@ Removes the element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -440,7 +439,7 @@ Obtains the value of the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -466,7 +465,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -496,14 +495,6 @@ Obtains a string that contains all elements in this container. | -------- | -------- | | String | String obtained.| -**Error codes** - -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). - -| ID| Error Message| -| -------- | -------- | -| 10200011 | The toString method cannot be bound. | - **Example** ```ts @@ -530,7 +521,7 @@ Obtains an array that contains all objects in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -562,7 +553,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -607,7 +598,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -641,7 +632,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -678,7 +669,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 1eda96e1205a256960c8a03f28ee60080850d22c..0e745d749c0967cd515a91356750f7de0703ace7 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -1,14 +1,13 @@ # @ohos.util.LinkedList (Linear Container LinkedList) > **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. **LinkedList** is implemented based on the doubly linked list. Each node of the doubly linked list has references pointing to the previous element and the next element. When querying an element, the system traverses the list from the beginning or end. **LinkedList** offers efficient insertion and removal operations but supports low query efficiency. **LinkedList** allows null elements. Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList** is a doubly linked list that supports insertion and removal at both ends. -**LinkedList** is less efficient in data access than **[ArrayList](js-apis-arraylist.md)**. +**LinkedList** is more efficient in data insertion than **[ArrayList](js-apis-arraylist.md)**, but less efficient in data access. **Recommended use case**: Use **LinkedList** for frequent insertion and removal operations. @@ -42,7 +41,7 @@ A constructor used to create a **LinkedList** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -78,7 +77,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -113,7 +112,7 @@ Adds an element at the top of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -149,12 +148,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -187,7 +186,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -224,7 +223,7 @@ Obtains an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -266,7 +265,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -308,7 +307,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -350,12 +349,12 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -385,7 +384,7 @@ Removes the first element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -420,7 +419,7 @@ Removes the last element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -461,7 +460,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -500,7 +499,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -540,7 +539,7 @@ Removes the last occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -574,7 +573,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -617,7 +616,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -646,7 +645,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -686,12 +685,12 @@ Replaces an element at the specified position in this container with a given ele **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -720,7 +719,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -752,7 +751,7 @@ Obtains the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -785,7 +784,7 @@ Obtains the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -818,7 +817,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 2c657bc20289e50af9edda35a739f8fd8c3b0896..bd1272f3a7a48a47f30ba689ff9df972932727d6 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -1,7 +1,6 @@ # @ohos.util.List (Linear Container List) > **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. **List** is implemented based on the singly linked list. Each node has a reference pointing to the next element. When querying an element, the system traverses the list from the beginning. **List** offers efficient insertion and removal operations but supports low query efficiency. **List** allows null elements. @@ -16,7 +15,7 @@ This topic uses the following to identify the use of generics: ## Modules to Import ```ts -import List from '@ohos.util.List'; +import List from '@ohos.util.List'; ``` @@ -26,7 +25,7 @@ import List from '@ohos.util.List'; **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | length | number | Yes| No| Number of elements in a list (called container later).| @@ -41,7 +40,7 @@ A constructor used to create a **List** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -76,7 +75,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -112,12 +111,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -150,7 +149,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -187,7 +186,7 @@ Obtains the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -229,7 +228,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -271,7 +270,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -314,7 +313,7 @@ Compares whether a specified object is equal to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -359,12 +358,12 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -400,7 +399,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -443,7 +442,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -478,7 +477,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -491,7 +490,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -533,7 +532,7 @@ comparator **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -547,8 +546,8 @@ list.add(2); list.add(4); list.add(5); list.add(4); -list.sort((a: number, b: number) => a - b); -list.sort((a: number, b: number) => b - a); +list.sort((a: number, b: number) => a - b); // The elements are sorted in ascending order. +list.sort((a: number, b: number) => b - a); // The elements are sorted in descending order. ``` ### getSubList @@ -574,12 +573,12 @@ Obtains elements within a range in this container, including the element at the **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getSubList method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -604,7 +603,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -644,12 +643,12 @@ Replaces an element at the specified position in this container with a given ele **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -678,7 +677,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -711,7 +710,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -744,7 +743,7 @@ Obtains the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -777,7 +776,7 @@ Obtains the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -810,7 +809,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 94034c60a39513e8bafa13724c7665f9c1620202..6d395fd5f21b8b041f7930ae96002dc430fd650b 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,7 +1,6 @@ -# Media +# @ohos.multimedia.media (Media) > **NOTE** -> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. @@ -1917,12 +1916,12 @@ Sets video recording parameters. This API uses an asynchronous callback to retur For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 201 | Permission denied. Return by callback. | -| 401 | Parameter error. Return by callback. | -| 5400102 | Operate not permit. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operation not allowed. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -1987,12 +1986,12 @@ Sets video recording parameters. This API uses a promise to return the result. For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 201 | Permission denied. Return by promise. | -| 401 | Parameter error. Return by promise. | -| 5400102 | Operate not permit. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operation not allowed. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2051,11 +2050,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2096,11 +2095,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2137,11 +2136,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2178,11 +2177,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2217,11 +2216,11 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2258,11 +2257,11 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2295,11 +2294,11 @@ Resumes video recording. This API uses an asynchronous callback to return the re For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2334,11 +2333,11 @@ Resumes video recording. This API uses a promise to return the result. For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2373,11 +2372,11 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2414,11 +2413,11 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2527,7 +2526,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | --------------------------------- | -| 5400103 | IO error. Return by callback. | +| 5400103 | I/O error. Return by callback. | | 5400105 | Service died. Return by callback. | **Example** @@ -2567,7 +2566,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | -------------------------------- | -| 5400103 | IO error. Return by promise. | +| 5400103 | I/O error. Return by promise. | | 5400105 | Service died. Return by promise. | **Example** @@ -2602,7 +2601,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | --------------------------------- | -| 5400103 | IO error. Return by callback. | +| 5400103 | I/O error. Return by callback. | | 5400105 | Service died. Return by callback. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index df70808165f275b456e591af48145d1e635ebfcd..8298770c17f71299078a9bc1e541abef94cd6d0b 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -202,7 +202,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| | callback | Callback<void> | Yes | Void callback. | **Example** @@ -224,7 +224,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| | callback | Callback<void> | No | Void callback. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 91ef73c07db34721d0cc0f964bb992ce37669ae3..704b9084ff4f3ebecf2720f6c40ebeb98f5dc775 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -242,7 +242,7 @@ For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode ## tag.getMifareClassic9+ -getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. @@ -258,7 +258,7 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use | **Type**| **Description** | | ----------------- | ------------------------| -| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| +| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) | **MifareClassicTag** object obtained.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md new file mode 100644 index 0000000000000000000000000000000000000000..03e049e9a1bb1076f770bd2d89dc25455c453ee6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -0,0 +1,40 @@ +# PermissionRequestResult + +The **PermissionRequestResult** module defines the result of a permission request. The result is returned when [requestPermissionsFromUser](js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called to request permissions. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Attributes + +**System capability**: SystemCapability.Security.AccessToken + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| No| Permissions requested.| +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite.| + +## Usage + +The permission request result is obtained through an **atManager** instance. + +**Example** +```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }).catch((err) => { + console.info("data:" + JSON.stringify(err)); + }) +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index dfc05166987a87d07bc1499fbcb980b45f08f2e8..8ccc7d7fb4bc1a5f876b8da75c181f8547e32f51 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -1,7 +1,6 @@ # @ohos.util.PlainArray (Nonlinear Container PlainArray) > **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. **PlainArray** stores key-value (KV) pairs. Each key must be unique, be of the number type, and have only one value. @@ -21,6 +20,8 @@ This topic uses the following to identify the use of generics: import PlainArray from '@ohos.util.PlainArray'; ``` + + ## PlainArray ### Attributes @@ -42,7 +43,7 @@ A constructor used to create a **PlainArray** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -71,7 +72,7 @@ Checks whether this container is empty. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -107,7 +108,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -145,7 +146,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -183,7 +184,7 @@ Obtains the index of the first occurrence of an element with the specified key i **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -221,7 +222,7 @@ Obtains the index of the first occurrence of an element with the specified value **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -259,7 +260,7 @@ Obtains the key of the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -284,24 +285,24 @@ Obtains the value of an element at the specified position in this container. **Parameters** -| Name| Type | Mandatory| Description| -| -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the target element.| + | Name| Type | Mandatory| Description| + | -------- | -------- | -------- | -------- | + | index | number | Yes| Position index of the target element.| **Return value** -| Type| Description| -| -------- | -------- | -| T | Returns the value of the element if obtained; returns **undefined** otherwise.| + | Type| Description| + | -------- | -------- | + | T | Returns the value of the element if obtained; returns **undefined** otherwise.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -328,7 +329,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -361,7 +362,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -397,7 +398,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -435,7 +436,7 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -474,12 +475,12 @@ Removes elements in a specified range from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeRangeFrom method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -508,12 +509,12 @@ Sets a value for an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -541,7 +542,7 @@ Obtains a string that contains all elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -567,7 +568,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -607,7 +608,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -641,7 +642,7 @@ Obtains an iterator object that contains key-value pairs, where the key is of th **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 2435d0a39731803e7c8ba730f6547a125cfc8438..fc74447111636244fb54e604dba5c458a6e6e061 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -121,9 +121,13 @@ Checks the visible status of the mouse pointer. This API uses a promise to retur **Example** ```js -pointer.isPointerVisible().then((visible) => { - console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); -}); +try { + pointer.isPointerVisible().then((visible) => { + console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); + }); +} catch (error) { + console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` ## pointer.setPointerSpeed9+ diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index 4d7ffb05e886f6b908a771b091f83983452bcfed..c7da8609952d245b53e82aead09f57f97eeeedf1 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -1,4 +1,4 @@ -# @ohos.privacyManager (Privacy Management) +# @ohos.privacyManager (Privacy Management) The **privacyManager** module provides APIs for privacy management, such as management of permission usage records. @@ -42,11 +42,14 @@ The permission usage record includes the application identity (token ID) of the **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -89,11 +92,14 @@ The permission usage record includes the application identity (token ID) of the **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -139,11 +145,14 @@ Obtains historical permission usage records. This API uses a promise to return t **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. the value of flag in request is invalid. | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -191,11 +200,14 @@ Obtains historical permission usage records. This API uses an asynchronous callb **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. the value of flag in request is invalid. | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -251,12 +263,15 @@ Starts to use a permission and flushes the permission usage record. This API is **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -296,12 +311,15 @@ Starts to use a permission and flushes the permission usage record. This API is **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -324,7 +342,7 @@ try { ## privacyManager.stopUsingPermission -stopUsingPermission(tokenID: number, permissionName: string): Promise<void> +stopUsingPermission(tokenID: number, permissionName: Permissions): Promise<void> Stops using a permission. This API is called by a system application and uses a promise to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. This API uses a promise to return the result. @@ -348,12 +366,15 @@ Stops using a permission. This API is called by a system application and uses a **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -393,12 +414,15 @@ Stops using a permission. This API is called by a system application and uses a **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -434,26 +458,29 @@ Subscribes to the permission usage status changes of the specified permissions. | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | No | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | +| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback invoked to return a change in the permission usage.| **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100004 | The interface is not used together. | -| 12100005 | The number of listeners exceeds the limit. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100004 | The interface is called repeatedly with the same input. | +| 12100005 | The registration time has exceeded the limitation. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList = []; try { - atManager.on('activeStateChange', permissionNameList, (data) => { + privacyManager.on('activeStateChange', permissionNameList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); }); } catch(err) { @@ -476,23 +503,26 @@ Unsubscribes from the permission usage status changes of the specified permissio | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | No | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| +| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback for the permission usage change event.| **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The permissionName in list is all invalid or the list size is larger than 1024. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList = []; try { privacyManager.off('activeStateChange', permissionNameList); }catch(err) { @@ -589,7 +619,7 @@ Enumerates the permission usage statuses. **System capability**: SystemCapability.Security.AccessToken -| Name | Default Value| Description | +| Name | Value | Description | | ------------------------- | ------ | ---------------- | | PERM_INACTIVE | 0 | The permission is not used. | | PERM_ACTIVE_IN_FOREGROUND | 1 | The permission is being used by an application running in the foreground.| diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index 57ce3f7b301c42167b6af3830e39949afd76f719..e4adf559e862ddc954b7e75c3253fb8aa95b6b2a 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -1,7 +1,6 @@ # @ohos.util.Queue (Linear Container Queue) > **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. **Queue** follows the principle of First In First Out (FIFO). It supports insertion of elements at the end and removal from the front of the queue. **Queue** is implemented based on the queue data structure. @@ -41,7 +40,7 @@ A constructor used to create a **Queue** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -76,7 +75,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -110,7 +109,7 @@ Removes the first element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -144,7 +143,7 @@ Obtains the first element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -187,7 +186,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -222,7 +221,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index a861858ce8f2fd6979fe21860b62443ad3d2ee15..29b20c42950323df2346d817922f178d71d11a80 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,4 +1,4 @@ -# @ohos.reminderAgent +# @ohos.reminderAgent (reminderAgent) The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 7b8db156f8b609f2bc62d751a71623abc990c65f..ab3d0f116871392e6cdbf0c004b9c418c5660e16 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,4 +1,4 @@ -# @ohos.reminderAgentManager +# @ohos.reminderAgentManager (reminderAgentManager) The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. 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 03645ac62b8ec51c616fbfd6e923aef203a52ad6..d5daa5d41e299d368b7d38af4428856bf343c516 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -236,7 +236,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | --------- | ---------------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -256,7 +256,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; @@ -268,13 +268,13 @@ function callback(error, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -310,7 +310,7 @@ Requests a continuous task from the system. This API uses a promise to return th | --------- | ---------------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** @@ -335,17 +335,17 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -401,7 +401,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; function callback(error, data) { @@ -412,7 +412,7 @@ function callback(error, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context, callback); @@ -462,10 +462,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 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 b423c712999053c8a00d0b8503525cd03ce1cdf8..1e243a9881594c4acf692110cfe2a2e7a363b945 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -219,8 +219,8 @@ Queries the application usage duration statistics based on the specified start t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<[BundleStatsMap](#bundlestatsmap)> | Yes | Callback used to return the application usage duration statistics.| **Error codes** @@ -274,8 +274,8 @@ Queries the application usage duration statistics based on the specified start t | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -333,8 +333,8 @@ Queries the application usage duration statistics in the specified time frame at | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | | byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried. | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleStatsInfo](#bundlestatsinfo)>> | Yes | Callback used to return the application usage duration statistics.| **Error codes** @@ -387,8 +387,8 @@ Queries the application usage duration statistics in the specified time frame at | Name | Type | Mandatory | Description | | ---------- | ----------------------------- | ---- | ----- | | byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried.| -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -443,8 +443,8 @@ Queries events of all applications based on the specified start time and end tim | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleEvents](#bundleevents)>> | Yes | Callback used to return the events obtained.| **Error codes** @@ -496,8 +496,8 @@ Queries events of all applications based on the specified start time and end tim | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -548,8 +548,8 @@ Queries events of this application based on the specified start time and end tim | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleEvents](#bundleevents)>> | Yes | Callback used to return the events obtained.| **Error codes** @@ -597,8 +597,8 @@ Queries events of this application based on the specified start time and end tim | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1276,8 +1276,8 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1329,8 +1329,8 @@ queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback<Arr | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[DeviceEventStats](#deviceeventstats)>> | Yes | Callback used to return the result. | **Error codes** @@ -1379,8 +1379,8 @@ Queries the number of notifications from all applications based on the specified | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1432,8 +1432,8 @@ Queries the number of notifications from all applications based on the specified | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[DeviceEventStats](#deviceeventstats)>> | Yes | Callback used to return the result. | **Error codes** @@ -1476,7 +1476,7 @@ Provides the information about the FA usage. | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ----------------------------- | | deviceId | string | No | ID of the device to which the FA belongs. | -| bundleName | string | Yes | Name of the application bundle to which the FA belongs. | +| bundleName | string | Yes | Name of the bundle to which the FA belongs. | | moduleName | string | Yes | Name of the module to which the FA belongs. | | abilityName | string | No | **MainAbility** name of the FA. | | appLabelId | number | No | Application label ID of the FA. | diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 77638dbfe38acf986f1b632349253c9ceb9496ed..70f20b743d5ee09f2c79877ab626d76fdaeb0d95 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,4 +1,4 @@ -# @ohos.resourceschedule.workScheduler +# @ohos.resourceschedule.workScheduler (workScheduler) The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index e9022ac7d23c3f213487da532d92a369c17a5c48..22f25f8f0185b954270c2169fc657f0676244623 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -1,6 +1,6 @@ # @ohos.screen (Screen) -The **screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. +The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 6fdc718f8df4868cb7e7f9c12f2346b36032b953..69845e5552e2c21cb49852513e837c7976dcb8b3 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -1,8 +1,9 @@ -# Sensor +# @ohos.sensor (Sensor) The **Sensor** module provides APIs for obtaining the sensor list and subscribing to sensor data. It also provides some common sensor algorithms. > **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. @@ -3495,9 +3496,9 @@ Describes the acceleration sensor data. It extends from [Response](#response). | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ------------------------------------ | -| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| +| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s². | ## LinearAccelerometerResponse @@ -3509,9 +3510,9 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | -| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| +| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s². | ## AccelerometerUncalibratedResponse @@ -3523,12 +3524,12 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( | Name | Type | Readable| Writable| Description | | ----- | ------ | ---- | ---- | ------------------------------------------------ | -| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | -| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | -| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | -| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | -| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| -| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | +| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s². | +| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s². | +| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s². | +| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s². | ## GravityResponse @@ -3540,9 +3541,9 @@ Describes the gravity sensor data. It extends from [Response](#response). | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | -| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| +| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s². | ## OrientationResponse diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index d7c5dcb66c511aa8ade7ad6e4fa94041162f2380..ff8551cad86f3f4c448e08d267548657305c5c9d 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -1,7 +1,6 @@ # @ohos.util.Stack (Linear Container Stack) > **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. **Stack** is implemented based on the array data structure. It follows the principle Last Out First In (LOFI) and supports data insertion and removal at one end. @@ -40,7 +39,7 @@ A constructor used to create a **Stack** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -75,7 +74,7 @@ Adds an element at the top of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -109,7 +108,7 @@ Removes the top element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -143,7 +142,7 @@ Obtains the top element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -182,7 +181,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -225,7 +224,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -260,7 +259,7 @@ Checks whether this container is empty (contains no elements). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -293,7 +292,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md index fafd6ee8d27ded9366e6fec85b21274316f63f8b..b48e4a8f6233b11ffdef0361280dba6322c9f959 100644 --- a/en/application-dev/reference/apis/js-apis-system-app.md +++ b/en/application-dev/reference/apis/js-apis-system-app.md @@ -1,4 +1,4 @@ -# @system.app +# @system.app (Application Context) > **NOTE** > - The APIs of this module are no longer maintained since API version 7. You are advised to use the new APIs. diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md index fd4fba8512b1cdecae82339ef31a4b293f022aef..f1ada5f0f2e7df99e3aa9889889d66eece5b2b3f 100644 --- a/en/application-dev/reference/apis/js-apis-system-location.md +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -1,6 +1,7 @@ # Geographic Location > **NOTE** +> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.geolocation`](js-apis-geolocation.md). > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. 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 1bf121889896276a676f177300f341da5fb327fe..a0b69a4dba4644451020ec49368117bcb1e98f91 100644 --- a/en/application-dev/reference/apis/js-apis-system-network.md +++ b/en/application-dev/reference/apis/js-apis-system-network.md @@ -1,8 +1,8 @@ -# Network State +# @system.network (Network State) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. +> **NOTE** > +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-system-request.md b/en/application-dev/reference/apis/js-apis-system-request.md index a2b939bf7d0983a25202fe11b7c5dd4ddd9d3665..82ba741d0964faa44066b5d43568b4fa25316f87 100644 --- a/en/application-dev/reference/apis/js-apis-system-request.md +++ b/en/application-dev/reference/apis/js-apis-system-request.md @@ -1,10 +1,10 @@ -# @system.request +# @system.request (Upload and Download) The **system.request** module provides applications with basic upload and download capabilities. > **NOTE** -> - The APIs of this module are deprecated since API version 9. You are advised to use [`@ohos.request`](js-apis-request.md) instead. > +> - The APIs of this module are deprecated since API version 9. You are advised to use [`@ohos.request`](js-apis-request.md) instead. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. 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 7df5f6675bb53168935ada36ca1d0675e49da978..30bfc60e3339b8102fbe6f4a6c5fc1202015da11 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -1,4 +1,4 @@ -# Sensor +# @system.sensor (Sensor) The **Sensor** module provides APIs for querying the sensor list, subscribing to or unsubscribing from sensor data, and executing control commands. @@ -21,9 +21,9 @@ import sensor from '@system.sensor'; ## Error Codes -| Error Code | Description | -| ---------- | ---------------------------------------- | -| 900 | The current device does not support the corresponding sensor. | +| Error Code | Description | +| ---- | -------------- | +| 900 | The current device does not support the corresponding sensor.| ## sensor.subscribeAccelerometer @@ -37,19 +37,19 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the acceleration sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the acceleration sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | --------------------------- | -| x | number | Acceleration on the x-axis. | -| y | number | Acceleration on the y-axis. | -| z | number | Acceleration on the z-axis. | +| Name | Type | Description | +| ---- | ------ | ------- | +| x | number | Acceleration on the x-axis.| +| y | number | Acceleration on the y-axis.| +| z | number | Acceleration on the z-axis.| **Example** @@ -68,7 +68,6 @@ sensor.subscribeAccelerometer({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeAccelerometer @@ -97,16 +96,16 @@ Subscribes to data changes of the compass sensor. If this API is called multiple **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the compass sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | --------------- | +| success | Function | Yes | Called when the compass sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------------------------------ | -| direction | number | Direction of the device, in degrees. | +| Name | Type | Description | +| --------- | ------ | ---------- | +| direction | number | Direction of the device, in degrees.| **Example** @@ -122,7 +121,6 @@ sensor.subscribeCompass({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeCompass @@ -149,16 +147,16 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the proximity sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ----------------- | +| success | Function | Yes | Called when the proximity sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | ---------------------------------------- | -| distance | number | Distance between a visible object and the device screen. | +| Name | Type | Description | +| -------- | ------ | --------------------- | +| distance | number | Distance between a visible object and the device screen.| **Example** @@ -174,7 +172,6 @@ sensor.subscribeProximity({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeProximity @@ -201,16 +198,16 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the ambient light sensor data changes | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | --------------- | +| success | Function | Yes | Called when the ambient light sensor data changes| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------------------ | -| intensity | number | Light intensity, in lux. | +| Name | Type | Description | +| --------- | ------ | ------------ | +| intensity | number | Light intensity, in lux.| **Example** @@ -226,7 +223,6 @@ sensor.subscribeLight({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeLight @@ -255,16 +251,16 @@ Subscribes to data changes of the step counter sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the step counter sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ---------------- | +| success | Function | Yes | Called when the step counter sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------ | ---------------------------------------- | -| steps | number | Number of counted steps after the sensor is restarted.
| +| Name | Type | Description | +| ----- | ------ | --------------------- | +| steps | number | Number of counted steps after the sensor is restarted.
| **Example** @@ -280,7 +276,6 @@ sensor.subscribeStepCounter({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeStepCounter @@ -310,16 +305,16 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the barometer sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ---------------- | +| success | Function | Yes | Called when the barometer sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | -------------------- | -| pressure | number | Pressure, in pascal. | +| Name | Type | Description | +| -------- | ------ | ----------- | +| pressure | number | Pressure, in pascal.| **Example** @@ -335,7 +330,6 @@ sensor.subscribeBarometer({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. @@ -366,16 +360,16 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ------------------------- | +| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ----------- | -| heartRate | number | Heart rate. | +| Name | Type | Description | +| --------- | ------ | ---- | +| heartRate | number | Heart rate.| **Example** @@ -391,7 +385,6 @@ sensor.subscribeHeartRate({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. @@ -421,16 +414,16 @@ Subscribes to changes of the wearing state of a wearable device. If this API is **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | -------------------------------------- | -| success | Function | Yes | Called when the wearing state changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ------------- | +| success | Function | Yes | Called when the wearing state changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------------------------------------ | -| value | boolean | Whether the wearable device is worn. | +| Name | Type | Description | +| ----- | ------- | ------ | +| value | boolean | Whether the wearable device is worn.| **Example** @@ -446,7 +439,6 @@ sensor.subscribeOnBodyState({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeOnBodyState @@ -473,17 +465,17 @@ Obtains the wearing state of a wearable device. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | -------------------------------------- | -| success | Function | No | Callback upon success. | -| fail | Function | No | Callback upon failure. | -| complete | Function | No | Called when the execution is complete. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ------------ | +| success | Function | No | Callback upon success.| +| fail | Function | No | Callback upon failure.| +| complete | Function | No | Called when the execution is complete.| Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------------------------------------ | -| value | boolean | Whether the wearable device is worn. | +| Name | Type | Description | +| ----- | ------- | ------ | +| value | boolean | Whether the wearable device is worn.| **Example** @@ -510,18 +502,18 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the device orientation sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the device orientation sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | +| Name | Type | Description | | ----- | ------ | ---------------------------------------- | -| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth. | -| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth. | -| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth. | +| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth.| +| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth.| +| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth.| **Example** @@ -540,7 +532,6 @@ sensor.subscribeDeviceOrientation({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeDeviceOrientation6+ @@ -571,19 +562,19 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the gyroscope sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the gyroscope sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | ---------------------------------------- | -| x | number | Rotation angular velocity of the X axis. | -| y | number | Rotation angular velocity of the Y axis. | -| z | number | Rotation angular velocity of the Z axis. | +| Name | Type | Description | +| ---- | ------ | --------- | +| x | number | Rotation angular velocity of the X axis.| +| y | number | Rotation angular velocity of the Y axis.| +| z | number | Rotation angular velocity of the Z axis.| **Example** @@ -602,7 +593,6 @@ sensor.subscribeGyroscope({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeGyroscope6+ diff --git a/en/application-dev/reference/apis/js-apis-system-vibrate.md b/en/application-dev/reference/apis/js-apis-system-vibrate.md index 86f474bce1a013f32bb351bfc6a0a44b658cbba5..90dc19e2ffb0c8817f7cc2096dc792d252f8996f 100644 --- a/en/application-dev/reference/apis/js-apis-system-vibrate.md +++ b/en/application-dev/reference/apis/js-apis-system-vibrate.md @@ -1,6 +1,7 @@ -# Vibrator +# @system.vibrator (Vibrator) -The **Vibrate** module provides APIs for controlling LED lights and vibrators. You can use the APIs to query the LED light list, turn on and off the LED light, query the vibrator list, query the vibrator effect, and trigger and turn off the vibrator. + +The **Vibrator** module provides APIs for controlling LED lights and vibrators. You can use the APIs to query the LED light list, turn on and off the LED light, query the vibrator list, query the vibrator effect, and trigger and turn off the vibrator. Misc devices refer to LED lights and vibrators on devices. LED lights are mainly used for indication (for example, indicating the charging state) and blinking (such as tri-colored lights). Vibrators are mainly used in scenarios such as the alarm clock, power-on/off, and incoming call vibration. diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index 573732b5474552added2d9918986e2add3982b01..eb874f0abd94f72f56f0e1e13a23883e1ae14ce8 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -1,7 +1,6 @@ # @ohos.util.TreeMap (Nonlinear Container TreeMap) > **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. **TreeMap** stores key-value (KV) pairs. Each key must be unique and have only one value. @@ -49,7 +48,7 @@ A constructor used to create a **TreeMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -78,7 +77,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -114,7 +113,7 @@ Checks whether this container has the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -152,7 +151,7 @@ Checks whether this container has the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -190,7 +189,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -222,7 +221,7 @@ Obtains the first key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -254,7 +253,7 @@ Obtains the last key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -282,11 +281,11 @@ Adds all elements in a **TreeMap** instance to this container. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| map | TreeMap | Yes| **TreeMap** instance whose elements are to be added to the current container.| +| map | TreeMap | Yes| **TreeMap** object to be added to the container.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -299,7 +298,11 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let map = new TreeMap(); -treeMap.setAll(map); +map.set("demo", 12); +map.setAll(treeMap); // Add all elements in the treeMap to the map. +map.forEach((value, key) => { + console.log("test" + value, key); // Print result: 12 demo, 356 sparrow, and 123 squirrel +}) ``` @@ -326,7 +329,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -362,7 +365,7 @@ Removes the element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -400,7 +403,7 @@ Obtains the key that is placed in front of the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -439,7 +442,7 @@ Obtains the key that is placed next to the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -478,7 +481,7 @@ Replaces an element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -503,7 +506,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -535,7 +538,7 @@ Obtains an iterator that contains all the keys in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -572,7 +575,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -617,7 +620,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -651,7 +654,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -688,7 +691,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index bc6f1272452fd35d0458b6232f7c03a1bd19ce9b..4aaaac1861ceffdfda3d7adc53b16181c42cc9c3 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -1,7 +1,6 @@ # @ohos.util.TreeSet (Nonlinear Container TreeSet) > **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. **TreeSet** is implemented based on **[TreeMap](js-apis-treemap.md)**. In **TreeSet**, only **value** objects are processed. **TreeSet** can be used to store values, each of which must be unique. @@ -46,7 +45,7 @@ A constructor used to create a **TreeSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -75,7 +74,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -111,7 +110,7 @@ Checks whether this container has the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -143,7 +142,7 @@ Obtains the value of the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -175,7 +174,7 @@ Obtains the value of the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -213,7 +212,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -249,7 +248,7 @@ Removes the element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -287,7 +286,7 @@ Obtains the value that is placed in front of the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -326,7 +325,7 @@ Obtains the value that is placed next to the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -359,7 +358,7 @@ Removes the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -391,7 +390,7 @@ Removes the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -417,7 +416,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -449,7 +448,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -494,7 +493,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -528,7 +527,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -566,7 +565,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index 6bad7dde783939b10243f10824e98ef991235499..00bf51656958f8ca58b926cb54ad9fd1d82a8e53 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -29,6 +29,70 @@ import uri from '@ohos.uri' | authority | string | Yes| No| Authority part in the URI.| | ssp | string | Yes| No| Scheme-specific part in the URI.| +### Naming Rules + +Naming format: + +A standard URI consists of the following parts: +[scheme:]scheme-specific-part[#fragment] +- Scheme: scheme component, which is mandatory. Example values: **http**, **https**, **ftp**, **datashare**, and **dataability**. +- scheme-specific-part: specific part of the URI decoding scheme. The value consists of [//][authority][path][?query]. Set this parameter as required. + - authority: decoding authority component of the URI. The value consists of [userinfo@]host[:port]. Set this parameter as required. + - userinfo: user information. Set this parameter as required. + - host: host name of the server. This parameter is mandatory when authority exists. + - port: port number of the server. Set this parameter as required. + - path: path information. Set this parameter as required. + - query: query component. Set this parameter as required. +- fragment: fragment component. Set this parameter as required. + +**Example URIs** + +```js +const result1 = new uri.URI("ftp://ftp.aaa.bbb.ccc/dddd/eee.txt"); +console.log(result1.host) // ftp.aaa.bbb.ccc +console.log(result1.fragment) // null +console.log(result1.path) // /dddd/eee.txt +console.log(result1.scheme) // ftp +console.log(result1.userInfo) // null +console.log(result1.port) // -1 +console.log(result1.query) // null + +const result2 = new uri.URI("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#fragment"); +console.log(result2.host) // spinaltap.micro.umn.edu +console.log(result2.fragment) // fragment +console.log(result2.path) // /dddd/eee.txt +console.log(result2.scheme) // ftp +console.log(result2.userInfo) // null +console.log(result2.port) //-1 +console.log(result2.query) // null + +const result3 = new uri.URI("datashare:///com.samples.datasharetest.DataShare/DB00/TBL00"); +console.log(result3.host) // null +console.log(result3.fragment) // null +console.log(result3.path) // /com.samples.datasharetest.DataShare/DB00/TBL00 +console.log(result3.scheme) // datashare +console.log(result3.userInfo) // null +console.log(result3.port) // -1 +console.log(result3.query) // null + +const result4 = new uri.URI("https://username:password@host:8080/directory/file?foo=1&bar=2#fragment"); +console.log(result4.host) // host +console.log(result4.fragment) // fragment +console.log(result4.path) // /directory/file +console.log(result4.scheme) // https +console.log(result4.userInfo) // username:password +console.log(result4.port) // 8080 +console.log(result4.query) // foo=1&bar=2 + +const result5 = new uri.URI("dataability:///com.example.DataAbility"); +console.log(result5.host) // null +console.log(result5.fragment) // null +console.log(result5.path) // /com.example.DataAbility: +console.log(result5.scheme) // dataability +console.log(result5.userInfo) // null +console.log(result5.port) // -1 +console.log(result5.query) // null +``` ### constructor @@ -44,6 +108,14 @@ A constructor used to create a URI instance. | -------- | -------- | -------- | -------- | | uri | string | Yes| Input object.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200002 | Invalid uri string. | + **Example** ```js @@ -79,14 +151,14 @@ result.toString() ### equals(deprecated) -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. - equals(other: URI): boolean Checks whether this URI is the same as another URI object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -105,7 +177,7 @@ Checks whether this URI is the same as another URI object. ```js const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); uriInstance.equals(uriInstance1); ``` ### equalsTo9+ @@ -132,7 +204,7 @@ Checks whether this URI is the same as another URI object. ```js const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); uriInstance.equalsTo(uriInstance1); ``` @@ -148,7 +220,7 @@ Checks whether this URI is an absolute URI (whether the scheme component is defi | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the URI is an absolute URI; returns **false** otherwise.| +| boolean | If the URI is an absolute URI, **true** is returned. Otherwise, **false** is returned.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 442c62ee76cf48b60361ee939c0f116bf98fb1fa..8a972e121d32b041e1ff7f8319c4e26261afb2f5 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -11,7 +11,6 @@ import Url from '@ohos.url' ``` ## URLParams9+ - ### constructor9+ constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) @@ -32,7 +31,7 @@ A constructor used to create a **URLParams** instance. let objectParams = new Url.URLParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); let objectParams1 = new Url.URLParams({"fod" : '1' , "bard" : '2'}); let objectParams2 = new Url.URLParams('?fod=1&bard=2'); -let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.mozilla.org/?fod=1&bard=2'); let params = new Url.URLParams(urlObject.search); ``` @@ -55,7 +54,7 @@ Appends a key-value pair into the query string. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.append('fod', '3'); ``` @@ -78,9 +77,9 @@ Deletes key-value pairs of the specified key. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsobject = new Url.URLParams(urlObject.search.slice(1)); -paramsobject.delete('fod'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.delete('fod'); ``` @@ -88,7 +87,7 @@ paramsobject.delete('fod'); getAll(name: string): string[] -Obtains all the key-value pairs based on the specified key. +Obtains all the key-value pairs based on the specified name. **System capability**: SystemCapability.Utils.Lang @@ -102,12 +101,12 @@ Obtains all the key-value pairs based on the specified key. | Type| Description| | -------- | -------- | -| string[] | All key-value pairs matching the specified key.| +| string[] | Key-value pairs obtained.| **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let params = new Url.URLParams(urlObject.search.slice(1)); params.append('fod', '3'); // Add a second value for the fod parameter. console.log(params.getAll('fod').toString()) // Output ["1","3"]. @@ -132,7 +131,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ```js let searchParamsObject = new Url.URLParams("keyName1=valueName1&keyName2=valueName2"); -for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs +for (var pair of searchParamsObject.entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } ``` @@ -164,9 +163,9 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal **Example** ```js -const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -myURLObject.searchParams.forEach((value, name, searchParams) => { - console.log(name, value, myURLObject.searchParams === searchParams); +const myURLObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); +myURLObject.params.forEach((value, name, searchParams) => { + console.log(name, value, myURLObject.params === searchParams); }); ``` @@ -224,7 +223,7 @@ Checks whether a key has a value. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.has('bard') === true; ``` @@ -248,7 +247,7 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.set('baz', '3'); // Add a third parameter. ``` @@ -360,7 +359,7 @@ Obtains search parameters that are serialized as a string and, if necessary, per **Example** ```js -let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let url = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let params = new Url.URLParams(url.search.slice(1)); params.append('fod', '3'); console.log(params.toString()); @@ -384,20 +383,20 @@ console.log(params.toString()); | port | string | Yes| Yes| Port in a URL.| | protocol | string | Yes| Yes| Protocol in a URL.| | search | string | Yes| Yes| Serialized query string in a URL.| -| searchParams | URLSearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| -| URLParams | URLParams | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| +| searchParams(deprecated) | [URLSearchParams](#urlsearchparamsdeprecated) | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.
- **NOTE**: This attribute is supported since API version 7 and is deprecated since API version 9. You are advised to use params9+ instead.| +| params9+ | [URLParams](#urlparams9) | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| | username | string | Yes| Yes| Username in a URL.| ### constructor(deprecated) -constructor(url: string, base?: string | URL) - -Creates a URL. - > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. +constructor(url: string, base?: string | URL) + +Creates a URL. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -410,13 +409,13 @@ Creates a URL. **Example** ```js -let mm = 'http://username:password@host:8080'; -let a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; -let b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; -new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -let c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; +let mm = 'https://username:password@host:8080'; +let a = new Url.URL("/", mm); // Output 'https://username:password@host:8080/'; +let b = new Url.URL(mm); // Output 'https://username:password@host:8080/'; +new Url.URL('path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +let c = new Url.URL('/path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', c); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', a); // Output 'https://username:password@host:8080/path/path1'; new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL @@ -424,8 +423,16 @@ new Url.URL('https://www.example.com', ); // Output https://www.example.com/ new Url.URL('https://www.example.com', b); // Output https://www.example.com/ ``` -### parseURL9+ +### constructor9+ + +constructor() + +A no-argument constructor used to create a URL. It returns a **URL** object after **parseURL** is called. It is not used independently. + +**System capability**: SystemCapability.Utils.Lang +### parseURL9+ + static parseURL(url : string, base?: string | URL): URL Parses a URL. @@ -447,11 +454,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | -------- | -------- | | 10200002 | Invalid url string. | + **Example** ```js -let mm = 'http://username:password@host:8080'; -Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; +let mm = 'https://username:password@host:8080'; +let url = Url.URL.parseURL(mm); +url.toString(); // Output 'https://username:password@host:8080/'; ``` ### tostring @@ -471,11 +480,10 @@ Converts the parsed URL into a string. **Example** ```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toString(); ``` - ### toJSON toJSON(): string @@ -492,7 +500,7 @@ Converts the parsed URL into a JSON string. **Example** ```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toJSON(); ``` @@ -634,7 +642,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ```js let searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2"); -for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs +for (var pair of searchParamsObject.entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } ``` @@ -657,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 to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| **Table 1** callbackFn parameter description @@ -902,126 +910,4 @@ let params = new Url.URLSearchParams(url.search.slice(1)); params.append('fod', '3'); console.log(params.toString()); ``` - -## URL - -### Attributes - -**System capability**: SystemCapability.Utils.Lang - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.| -| host | string | Yes| Yes| Host information in a URL.| -| hostname | string | Yes| Yes| Hostname (without the port) in a URL.| -| href | string | Yes| Yes| String that contains the whole URL.| -| origin | string | Yes| No| Read-only string that contains the Unicode serialization of the origin of the represented URL.| -| password | string | Yes| Yes| Password in a URL.| -| pathname | string | Yes| Yes| Path in a URL.| -| port | string | Yes| Yes| Port in a URL.| -| protocol | string | Yes| Yes| Protocol in a URL.| -| search | string | Yes| Yes| Serialized query string in a URL.| -| searchParams | URLSearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| -| URLParams | URLParams | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| -| username | string | Yes| Yes| Username in a URL.| - -### constructor(deprecated) - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. - -constructor(url: string, base?: string | URL) - -Creates a URL. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| 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| - -**Example** - -```js -let mm = 'https://username:password@host:8080'; -let a = new Url.URL("/", mm); // Output 'https://username:password@host:8080/'; -let b = new Url.URL(mm); // Output 'https://username:password@host:8080/'; -new Url.URL('path/path1', b); // Output 'https://username:password@host:8080/path/path1'; -let c = new Url.URL('/path/path1', b); // Output 'https://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', c); // Output 'https://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', a); // Output 'https://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 -new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL -new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL -new Url.URL('https://www.example.com', ); // Output https://www.example.com/ -new Url.URL('https://www.example.com', b); // Output https://www.example.com/ -``` - -### parseURL9+ - -static parseURL(url : string, base?: string | URL): URL - -Parses a URL. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| 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| - -**Example** - -```js -let mm = 'https://username:password@host:8080'; -Url.URL.parseURL(mm); // Output 'https://username:password@host:8080/'; -``` - -### tostring - -toString(): string - -Converts the parsed URL into a string. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Website address in a serialized string.| - -**Example** - -```js -const url = new Url.URL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toString(); -``` - - -### toJSON - -toJSON(): string - -Converts the parsed URL into a JSON string. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Website address in a serialized string.| - -**Example** -```js -const url = new Url.URL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toJSON(); -``` diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md index 81fac3a36bb2dd34577e10596236cf8135a5fde1..7005776c804fa21fe899f82d29253c2436b4f5ea 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -1,4 +1,4 @@ -# @ohos.userIAM.faceAuth (Facial Authentication) +# @ohos.userIAM.faceAuth (Facial Authentication) The **userIAM.faceAuth** module provides APIs for face enrollment. @@ -34,17 +34,17 @@ A constructor used to create a **FaceAuthManager** object. **Example** - ```js - import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; - let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); - ``` +let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); +``` ### setSurfaceId setSurfaceId(surfaceId: string): void; -Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. +Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. This API must be used with [AddCredential](./js-apis-osAccount.md#addcredential8). **System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth @@ -56,17 +56,28 @@ Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#ge | -------------- | ---------------------------------- | ---- | -------------------------- | | surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| +For details about the following error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 12700001 | The operation is failed. | + **Example** - ```js - import faceAuth from '@ohos.userIAM.faceAuth'; - - let surfaceId = "123456"; - let manager = new faceAuth.FaceAuthManager(); - try { - manager.setSurfaceId(surfaceId); - console.info("Set the surface ID successfully"); - } catch (e) { - console.error("Failed to set the surface ID, error = " + e); - } - ``` +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + +// The surfaceId is obtained from the XComponent control. The surfaceId here is only an example. +let surfaceId = "123456"; +let manager = new userIAM_faceAuth.FaceAuthManager(); +try { + manager.setSurfaceId(surfaceId); + console.info("Set the surface ID successfully"); +} catch (e) { + console.error("Failed to set the surface ID, error = " + e); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index 64e92b13dadd306eab3ee030611a5e2d6ce0bd40..29044d135b43286a8b3df624584750022f6576b8 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -1,4 +1,4 @@ -# @ohos.userIAM.userAuth (User Authentication) +# @ohos.userIAM.userAuth (User Authentication) The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login. @@ -12,268 +12,115 @@ The **userIAM.userAuth** module provides user authentication capabilities in ide import userIAM_userAuth from '@ohos.userIAM.userAuth'; ``` -## Sample Code - -```js -// API version 9 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; - -export default { - getVersion() { - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - }, - - start() { - console.info("start auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - console.log("authV9 result " + result.result); - console.log("authV9 token " + result.token); - console.log("authV9 remainAttempts " + result.remainAttempts); - console.log("authV9 lockoutDuration " + result.lockoutDuration); - } - }); - // If tips are needed - auth.on("tip", { - callback : (result : userIAM_userAuth.TipInfo) => { - switch (result.tip) { - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: - // Do something; - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: - // Do something; - // ... - default: - // Do others. - } - } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - }, +## AuthResultInfo9+ - getAvailableStatus() { - console.info("start check auth support"); - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - }, +Defines the authentication result. - cancel() { - console.info("start cancel auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +**System capability**: SystemCapability.UserIAM.UserAuth.Core - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| result | number | Yes | Authentication result. | +| token | Uint8Array | No | Token that has passed the user identity authentication.| +| remainAttempts | number | No | Number of remaining authentication times allowed.| +| lockoutDuration | number | No | Time for which the authentication operation is frozen.| -```js -// API version 8 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; -let auth = new userIAM_userAuth.UserAuth(); +## TipInfo9+ -export default { - getVersion() { - console.info("start get version"); - let version = auth.getVersion(); - console.info("auth version = " + version); - }, - - startAuth() { - console.info("start auth"); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - }, - - checkAuthSupport() { - console.info("start check auth support"); - let checkCode = this.auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - }, - - cancelAuth() { - console.info("start cancel auth"); - // Obtain contextId using auth(). - let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - console.info("auth onResult result = " + result); - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - console.info("auth onAcquireInfo module = " + module); - } - }); - let cancelCode = this.auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - } -} -``` +Defines the authentication tip information. -```js -// API version 6 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; +**System capability**: SystemCapability.UserIAM.UserAuth.Core -export default { - startAuth() { - console.info("start auth"); - let auth = userIAM_userAuth.getAuthenticator(); - auth.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - // Add the logic to be executed when the authentication is successful. - }).catch((code)=>{ - console.error("auth fail, code = " + code); - // Add the logic to be executed when the authentication fails. - }); - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| module | number | Yes | ID of the module that sends the tip information. | +| tip | number | Yes | Tip to be given during the authentication process. | ## EventInfo9+ -Defines the event information used in authentication. +Enumerates the authentication event information types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Type | Description | +| Value | Description | | --------- | ----------------------- | -| [AuthResultInfo](#authresultinfo9) | Authentication result information. | +| [AuthResultInfo](#authresultinfo9) | Authentication result. | | [TipInfo](#tipinfo9) | Authentication tip information. | +## AuthEventKey9+ + +Defines the keyword of the authentication event type. It is used as a parameter of [on](#on9). + +| Value | Description | +| ---------- | ----------------------- | +| "result" | If the first parameter of [on](#on9) is **result**, the [callback](#callback9) returns the authentication result.| +| "tip" | If the first parameter of [on](#on9) is **tip**, the [callback](#callback9) returns the authentication tip information.| + ## AuthEvent9+ -Provides callbacks to return authentication events. +Provides an asynchronous callback to return the authentication event information. ### callback9+ -callback: (result : EventInfo) => void +callback(result : EventInfo) : void -Called to return the authentication result or authentication tips. +Called to return the authentication result or authentication tip information. **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | -------------------------------------------------------- | -| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------ | +| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +// Obtain the authentication result through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` - -## AuthResultInfo9+ - -Defines the authentication result information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| result | number | Yes | Authentication result. | -| token | Uint8Array | No | Token that has passed the user identity authentication.| -| remainAttempts | number | No | Number of remaining authentication times allowed.| -| lockoutDuration | number | No | Time for which the authentication operation is frozen.| - -## TipInfo9+ - -Defines the authentication tip information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| module | number | No | Authentication module. | -| tip | number | No | Tip to be given during the authentication process. | - -## AuthEventKey9+ - -Defines the keyword of an authentication event. - -| Value | Description | -| ---------- | ----------------------- | -| "result" | Indicates authentication result.| -| "tip" | If **AuthEventKey** is **result**, the callback returns the authentication tip information.| + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +// Obtain the authentication tip information through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("tip", { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // Do something; + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // Do something. + default: + // Do others. + } + } + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ## AuthInstance9+ @@ -281,9 +128,12 @@ Implements user authentication. ### on9+ -on(name : AuthEventKey, callback : AuthEvent) : void +on : (name : AuthEventKey, callback : AuthEvent) => void -Enables authentication event listening. +Subscribes to the user authentication events of the specified type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to subscribe to events. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -291,151 +141,210 @@ Enables authentication event listening. | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event to listen for. | -| callback | AuthEvent | Yes | Callback invoked to return the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Authentication event type. If the value is **result**, the callback returns the authentication result. If the value is **tip**, the callback returns the authentication tip information.| +| callback | [AuthEvent](#authevent9) | Yes | Callback invoked to return the authentication result or tip information.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - // If tips are needed - auth.on("tip", { + }); + // Subscribe to authentication tip information. + auth.on("tip", { callback : (result : userIAM_userAuth.TipInfo) => { switch (result.tip) { case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: // Do something; case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: // Do something; - // ... default: // Do others. } } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ### off9+ -off(name : AuthEventKey) : void +off : (name : AuthEventKey) => void -Disables authentication event listening. +Unsubscribes from the user authentication events of the specific type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to unsubscribe from events. **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Type of the authentication event to unsubscribe from. If the value is **result**, the authentication result is unsubscribed from. If the value is **tip**, the authentication tip information is unsubscribed from.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let auth; +try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); +} catch (error) { + console.log("get auth instance failed" + error); +} - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +try { + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - console.log("turn on authentication event listening success"); - } catch (error) { - console.log("turn off authentication event listening failed " + error); - // do error - } - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.off("result"); - console.info("turn off authentication event listening success"); - } catch (error) { - console.info("turn off authentication event listening failed, error = " + error); - } - ``` + }); + console.log("subscribe authentication event success"); +} catch (error) { + console.log("subscribe authentication event failed " + error); +} +// Unsubscribe from the authentication result. +try { + auth.off("result"); + console.info("cancel subscribe authentication event success"); +} catch (error) { + console.info("cancel subscribe authentication event failed, error = " + error); +} +``` ### start9+ -start() : void +start : () => void Starts authentication. +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500001 | Authentication failed. | +| 12500002 | General operation error. | +| 12500003 | The operation is canceled. | +| 12500004 | The operation is time-out. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500007 | The authentication task is busy. | +| 12500009 | The authenticator is locked. | +| 12500010 | The type of credential has not been enrolled. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.start(); + console.info("authV9 start auth success"); +} catch (error) { + console.info("authV9 start auth failed, error = " + error); +} +``` ### cancel9+ -cancel(): void +cancel : () => void -Cancels the authentication. +Cancels this authentication. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. The [AuthInstance](#authinstance9) instance must be the one being authenticated. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.cancel(); + console.info("cancel auth success"); +} catch (error) { + console.info("cancel auth failed, error = " + error); +} +``` ## userIAM_userAuth.getAuthInstance9+ @@ -444,7 +353,7 @@ getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel Obtains an **AuthInstance** instance for user authentication. > **NOTE**
-> Each **AuthInstance** can be used to initiate an authentication only once. +> An **AuthInstance** instance can be used for an authentication only once. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -460,23 +369,35 @@ Obtains an **AuthInstance** instance for user authentication. | Type | Description | | ----------------------------------------- | ------------ | -| [AuthInstance](#authinstance9) | **Authenticator** object obtained.| +| [AuthInstance](#authinstance9) | **Authenticator** instance obtained.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - console.info("get auth instance success"); - } catch (error) { - console.info("get auth instance success failed, error = " + error); - } - ``` +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.info("get auth instance success"); +} catch (error) { + console.info("get auth instance success failed, error = " + error); +} +``` ## userIAM_userAuth.getVersion9+ @@ -494,24 +415,33 @@ Obtains the version of this authenticator. | ------ | ---------------------- | | number | Authenticator version obtained.| +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - ``` +try { + let version = userIAM_userAuth.getVersion(); + console.info("auth version = " + version); +} catch (error) { + console.info("get version failed, error = " + error); +} +``` ## userIAM_userAuth.getAvailableStatus9+ getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void -Checks whether the authentication capability of the specified trust level is available. +Checks whether the specified authentication capability is supported. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -522,54 +452,65 @@ Checks whether the authentication capability of the specified trust level is ava | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500010 | The type of credential has not been enrolled. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - ``` +try { + userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + console.info("current auth trust level is supported"); +} catch (error) { + console.info("current auth trust level is not supported, error = " + error); +} +``` - ## ResultCodeV99+ +## UserAuthResultCode9+ -Enumerates the operation results. +Enumerates the authentication result codes. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------- | ------ | -------------------- | -| SUCCESS | 12500000 | The operation is successful. | -| FAIL | 12500001 | The operation failed. | -| GENERAL_ERROR | 12500002 | A common operation error occurred. | -| CANCELED | 12500003 | The operation is canceled. | -| TIMEOUT | 12500004 | The operation timed out. | +| SUCCESS | 12500000 | The authentication is successful. | +| FAIL | 12500001 | The authentication failed. | +| GENERAL_ERROR | 12500002 | A general operation error occurred. | +| CANCELED | 12500003 | The authentication is canceled. | +| TIMEOUT | 12500004 | The authentication timed out. | | TYPE_NOT_SUPPORT | 12500005 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 12500006 | The authentication trust level is not supported. | | BUSY | 12500007 | Indicates the busy state. | -| INVALID_PARAMETERS | 12500008 | Invalid parameters are detected. | | LOCKED | 12500009 | The authentication executor is locked. | | NOT_ENROLLED | 12500010 | The user has not entered the authentication information.| ## UserAuth8+ -Provides methods to manage an **Authenticator** object. +Provides APIs to manage an **Authenticator** object. ### constructor(deprecated) constructor() -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). +A constructor used to create an authenticator instance. -A constructor used to create an **authenticator** object. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -577,25 +518,24 @@ A constructor used to create an **authenticator** object. | Type | Description | | ---------------------- | -------------------- | -| [UserAuth](#userauth8) | **Authenticator** object obtained.| +| [UserAuth](#userauth8) | **Authenticator** instance obtained.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - ``` +let auth = new userIAM_userAuth.UserAuth(); +``` ### getVersion(deprecated) getVersion() : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). +Obtains the version of this authenticator. -Obtains the authentication executor version. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -609,23 +549,22 @@ Obtains the authentication executor version. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - let version = auth.getVersion(); - console.info("auth version = " + version); - ``` +let auth = new userIAM_userAuth.UserAuth(); +let version = auth.getVersion(); +console.info("auth version = " + version); +``` ### getAvailableStatus(deprecated) getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). +Checks whether the specified authentication capability is supported. -Obtains the available status of the specified authentication trust level. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -636,40 +575,37 @@ Obtains the available status of the specified authentication trust level. | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Available status obtained. For details, see [ResultCode](#resultcodedeprecated).| +| number | Query result. If the authentication capability is supported, **SUCCESS** is returned. Otherwise, a [ResultCode](#resultcodedeprecated) is returned.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); +if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("check auth support success"); +} else { + console.error("check auth support fail, code = " + checkCode); +} +``` ### auth(deprecated) auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9). - Performs user authentication. This API uses a 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 [start](#start9). + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -680,8 +616,8 @@ Performs user authentication. This API uses a callback to return the result. | -------------- | ---------------------------------------- | ---- | ------------------------ | | challenge | Uint8Array | Yes | Challenge value, which can be null. | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | -| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | +| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | **Return value** @@ -691,36 +627,35 @@ Performs user authentication. This API uses a callback to return the result. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### cancelAuth(deprecated) cancelAuth(contextID : Uint8Array) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). +Cancels an authentication based on the context ID. -Cancels an authentication. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -730,100 +665,86 @@ Cancels an authentication. | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | Yes | Context ID, which is obtained by using [auth](#authdeprecated).| +| contextID | Uint8Array | Yes | Context ID, which is obtained by [auth](#authdeprecated).| **Return value** | Type | Description | | ------ | ------------------------ | -| number | Whether the authentication is canceled.| +| number | Returns **SUCCESS** if the cancellation is successful. Returns a [ResultCode](#resultcodedeprecated) otherwise.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - // contextId can be obtained using auth(). In this example, it is defined here. - let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); - let auth = new userIAM_userAuth.UserAuth(); - let cancelCode = auth.cancelAuth(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +// contextId can be obtained by auth(). In this example, it is defined here. +let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); +let auth = new userIAM_userAuth.UserAuth(); +let cancelCode = auth.cancelAuth(contextId); +if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("cancel auth success"); +} else { + console.error("cancel auth fail"); +} +``` ## IUserAuthCallback(deprecated) -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). +Provides callbacks to return the authentication result. -Defines the object of the result returned by the callback during authentication. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). ### onResult(deprecated) onResult: (result : number, extraInfo : AuthResult) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to return the authentication result. -Obtains the authentication result. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | ------------------------------------------------------------ | -| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated). | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------------------------ | +| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated).| | extraInfo | [AuthResult](#authresultdeprecated) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| - **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### onAcquireInfo(deprecated) onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to acquire authentication tip information. This API is optional. -Obtains the tip code information during authentication. This function is optional. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -831,89 +752,74 @@ Obtains the tip code information during authentication. This function is optiona | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------ | -| module | number | Yes | Type of the authentication executor. | -| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| +| module | number | Yes | ID of the module that sends the tip information. | +| acquire | number | Yes | Authentication tip information.| | extraInfo | any | Yes | Reserved field. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; -## AuthResult(deprecated) +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } +}); +``` -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). +## AuthResult(deprecated) Represents the authentication result object. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). + **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| token | Uint8Array | No | Identity authentication token. | +| ------------ | ---------- | ---- | -------------------| +| token | Uint8Array | No | Authentication token information.| | remainTimes | number | No | Number of remaining authentication operations.| | freezingTime | number | No | Time for which the authentication operation is frozen.| ## ResultCode(deprecated) -> **NOTE**
-> This object is deprecated since API version 9. You are advised to use [ResultCodeV9](#resultcodev99). +Enumerates the authentication result codes. -Enumerates the operation results. +> **NOTE**
+> This object is deprecated since API version 9. You are advised to use [UserAuthResultCode](#userauthresultcode9). **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------- | ------ | -------------------- | | SUCCESS | 0 | The operation is successful. | -| FAIL | 1 | The operation failed. | -| GENERAL_ERROR | 2 | A common operation error occurred. | -| CANCELED | 3 | The operation is canceled. | -| TIMEOUT | 4 | The operation timed out. | +| FAIL | 1 | The authentication failed. | +| GENERAL_ERROR | 2 | A general operation error occurred. | +| CANCELED | 3 | The authentication is canceled. | +| TIMEOUT | 4 | The authentication timed out. | | TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | | BUSY | 7 | Indicates the busy state. | +| INVALID_PARAMETERS | 8 | Invalid parameters are detected. | | LOCKED | 9 | The authentication executor is locked. | | NOT_ENROLLED | 10 | The user has not entered the authentication information.| - ## FaceTips8+ Enumerates the tip codes used during the facial authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------------- | ------ | ------------------------------------ | | FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. | | FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. | @@ -934,7 +840,7 @@ Enumerates the tip codes used during the fingerprint authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------------------------- | ------ | -------------------------------------------------- | | FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | | FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| @@ -950,7 +856,7 @@ Enumerates the identity authentication types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------- | ------ | ---------- | | FACE | 2 | Facial authentication.| | FINGERPRINT | 4 | Fingerprint authentication.| @@ -961,7 +867,7 @@ Enumerates the trust levels of the authentication result. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name| Default Value| Description | +| Name| Value | Description | | ---- | ------ | ------------------------- | | ATL1 | 10000 | Trust level 1.| | ATL2 | 20000 | Trust level 2.| @@ -972,18 +878,18 @@ Enumerates the trust levels of the authentication result. getAuthenticator(): Authenticator +Obtains an **Authenticator** instance for user authentication. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [constructor](#constructordeprecated). -Obtains an **Authenticator** object for user authentication. - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** | Type | Description | | ----------------------------------------- | ------------ | -| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| +| [Authenticator](#authenticatordeprecated) | **Authenticator** instance obtained.| **Example** ```js @@ -992,61 +898,61 @@ Obtains an **Authenticator** object for user authentication. ## Authenticator(deprecated) +Defines the **Authenticator** object. + > **NOTE**
> This object is deprecated since API version 8. You are advised to use [UserAuth](#userauth8). -Provides methods to manage an **Authenticator** object. - - ### execute(deprecated) execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void +Performs user authentication. This API uses asynchronous callback to return the result. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses asynchronous callback to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------- | | type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| -| callback | AsyncCallback<number> | No | Callback used to return the result. | +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | - Parameters returned in callback +Parameters returned in callback | Type | Description | | ------ | ------------------------------------------------------------ | | number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ - if (code === userIAM_userAuth.ResultCode.SUCCESS) { - console.info("auth success"); - return; - } - console.error("auth fail, code = " + code); - }); - ``` + +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ + if (code === userIAM_userAuth.ResultCode.SUCCESS) { + console.info("auth success"); + return; + } + console.error("auth fail, code = " + code); +}); +``` ### execute(deprecated) -execute(type:AuthType, level:SecureLevel): Promise<number> +execute(type : AuthType, level : SecureLevel): Promise<number> + +Performs user authentication. This API uses a promise to return the result. > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses a promise to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -1066,25 +972,25 @@ Performs user authentication. This API uses a promise to return the result. **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - }).catch((error)=>{ - console.error("auth fail, code = " + error); - }); - ``` +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2").then((code)=>{ + console.info("auth success"); +}).catch((error)=>{ + console.error("auth fail, code = " + error); +}); +``` ## AuthenticationResult(deprecated) +Enumerates the authentication results. + > **NOTE**
> This object is discarded since API version 8. You are advised to use [ResultCode](#resultcodedeprecated). -Enumerates the authentication results. - **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------------ | ------ | -------------------------- | | NO_SUPPORT | -1 | The device does not support the current authentication mode.| | SUCCESS | 0 | The authentication is successful. | diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 09e3c245326f4bc9008e20535edfa4f0a2c3d2d0..f4193680d4d0732a38ab9564bbd67428c7a3497a 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -1,4 +1,4 @@ -# @ohos.util (Utilities) +# @ohos.util (util) The **util** module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. @@ -41,38 +41,6 @@ let res = util.format("%s", "hello world!"); console.log(res); ``` -## util.printf(deprecated) - -printf(format: string, ...args: Object[]): string - -Formats the specified values and inserts them into the string by replacing the wildcard in the string. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| format | string | Yes| String.| -| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | String containing the formatted values.| - -**Example** - - ```js - let res = util.printf("%s", "hello world!"); - console.log(res); - ``` - ## util.errnoToString9+ errnoToString(errno: number): string @@ -96,43 +64,11 @@ Obtains detailed information about a system error code. **Example** ```js -let errnum = 10; // 10 is a system error code. +let errnum = -1; // -1 is a system error code. let result = util.errnoToString(errnum); console.log("result = " + result); ``` -## util.getErrorString(deprecated) - -getErrorString(errno: number): string - -Obtains detailed information about a system error code. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| errno | number | Yes| Error code generated.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Detailed information about the error code.| - -**Example** - - ```js - let errnum = 10; // 10 is a system error code. - let result = util.getErrorString(errnum); - console.log("result = " + result); - ``` - ## util.callbackWrapper callbackWrapper(original: Function): (err: Object, value: Object )=>void @@ -203,30 +139,6 @@ Processes an asynchronous function and returns a promise. }) ``` -## util.promiseWrapper(deprecated) - -promiseWrapper(original: (err: Object, value: Object) => void): Object - -Processes an asynchronous function and returns a promise. - -> **NOTE** -> -> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| original | Function | Yes| Asynchronous function.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| - ## util.randomUUID9+ randomUUID(entropyCache?: boolean): string @@ -314,6 +226,96 @@ Parses a UUID from a string, as described in RFC 4122 version 4. // 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156 ``` +## util.printf(deprecated) + +printf(format: string, ...args: Object[]): string + +Formats the specified values and inserts them into the string by replacing the wildcard in the string. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| format | string | Yes| String.| +| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | String containing the formatted values.| + +**Example** + + ```js + let res = util.printf("%s", "hello world!"); + console.log(res); + ``` + + +## util.getErrorString(deprecated) + +getErrorString(errno: number): string + +Obtains detailed information about a system error code. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| errno | number | Yes| Error code generated.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Detailed information about the error code.| + +**Example** + + ```js + let errnum = -1; // -1 is a system error code. + let result = util.getErrorString(errnum); + console.log("result = " + result); + ``` + +## util.promiseWrapper(deprecated) + +promiseWrapper(original: (err: Object, value: Object) => void): Object + +Processes an asynchronous function and returns a promise. + +> **NOTE** +> +> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| original | Function | Yes| Asynchronous function.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| + + ## TextDecoder ### Attributes @@ -336,7 +338,7 @@ A constructor used to create a **TextDecoder** object. ### create9+ -create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean },): TextDecoder; +create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean }): TextDecoder; Creates a **TextDecoder** object. It provides the same function as the deprecated argument constructor. @@ -363,41 +365,9 @@ let textDecoder = new util.TextDecoder() textDecoder.create('utf-8', { ignoreBOM : true }); ``` -### constructor(deprecated) - -constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },) - -A constructor used to create a **TextDecoder** object. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| encoding | string | No| Encoding format.| -| options | Object | No| Encoding-related options, which include **fatal** and **ignoreBOM**.| - - **Table 1** options - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| fatal | boolean | No| Whether to display fatal errors.| -| ignoreBOM | boolean | No| Whether to ignore the BOM.| - -**Example** - - ```js - let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); - ``` - -### decode +### decodeWithStream9+ -decode(input: Uint8Array, options?: { stream?: false }): string +decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string Decodes the input content. @@ -414,7 +384,7 @@ Decodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| stream | boolean | No| Whether to allow data blocks in subsequent **decode()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| +| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| **Return value** @@ -434,17 +404,52 @@ Decodes the input content. result[4] = 0x62; result[5] = 0x63; console.log("input num:"); - let retStr = textDecoder.decode( result , {stream: false}); + let retStr = textDecoder.decodeWithStream( result , {stream: false}); console.log("retStr = " + retStr); ``` +### constructor(deprecated) -### decodeWithStream9+ +constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean }) -decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string +A constructor used to create a **TextDecoder** object. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [create9+](#create9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| encoding | string | No| Encoding format.| +| options | Object | No| Encoding-related options, which include **fatal** and **ignoreBOM**.| + + **Table 1** options + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fatal | boolean | No| Whether to display fatal errors.| +| ignoreBOM | boolean | No| Whether to ignore the BOM.| + +**Example** + + ```js + let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); + ``` + +### decode(deprecated) + +decode(input: Uint8Array, options?: { stream?: false }): string Decodes the input content. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [decodeWithStream9+](#decodewithstream9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -458,7 +463,7 @@ Decodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| +| stream | boolean | No| Whether to allow data blocks in subsequent **decode()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| **Return value** @@ -478,11 +483,10 @@ Decodes the input content. result[4] = 0x62; result[5] = 0x63; console.log("input num:"); - let retStr = textDecoder.decodeWithStream( result , {stream: false}); + let retStr = textDecoder.decode( result , {stream: false}); console.log("retStr = " + retStr); ``` - ## TextEncoder ### Attributes @@ -493,7 +497,6 @@ Decodes the input content. | -------- | -------- | -------- | -------- | -------- | | encoding | string | Yes| No| Encoding format. The default format is **utf-8**.| - ### constructor constructor() @@ -508,65 +511,53 @@ A constructor used to create a **TextEncoder** object. let textEncoder = new util.TextEncoder(); ``` -### encodeInto9+ +### constructor9+ -encodeInto(input?: string): Uint8Array +constructor(encoding?: string) -Encodes the input content. +A constructor used to create a **TextEncoder** object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| input | string | No | String to encode.| - -**Return value** - -| Type | Description | -| ---------- | ------------------ | -| Uint8Array | Encoded text.| +| Name| Type| Mandatory| Description| +| ----- | ---- | ---- | ---- | +| encoding | string | No| Encoding format.| **Example** ```js -let textEncoder = new util.TextEncoder(); -let buffer = new ArrayBuffer(20); -let result = new Uint8Array(buffer); -result = textEncoder.encodeInto("\uD800¥¥"); + let textEncoder = new util.TextEncoder("utf-8"); ``` -### encode(deprecated) +### encodeInto9+ -encode(input?: string): Uint8Array +encodeInto(input?: string): Uint8Array Encodes the input content. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. - **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| input | string | No| String to encode.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| input | string | No | String to encode.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------- | ------------------ | | Uint8Array | Encoded text.| **Example** + ```js - let textEncoder = new util.TextEncoder(); - let buffer = new ArrayBuffer(20); - let result = new Uint8Array(buffer); - result = textEncoder.encode("\uD800¥¥"); +let textEncoder = new util.TextEncoder(); +let buffer = new ArrayBuffer(20); +let result = new Uint8Array(buffer); +result = textEncoder.encodeInto("\uD800¥¥"); ``` ### encodeIntoUint8Array9+ @@ -597,7 +588,7 @@ let that = new util.TextEncoder() let buffer = new ArrayBuffer(4) let dest = new Uint8Array(buffer) let result = new Object() -result = that.encodeInto('abcd', dest) +result = that.encodeIntoUint8Array('abcd', dest) ``` ### encodeInto(deprecated) @@ -634,6 +625,38 @@ Stores the UTF-8 encoded text. result = that.encodeInto('abcd', dest) ``` +### encode(deprecated) + +encode(input?: string): Uint8Array + +Encodes the input content. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| input | string | No| String to encode.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Uint8Array | Encoded text.| + +**Example** + ```js + let textEncoder = new util.TextEncoder(); + let buffer = new ArrayBuffer(20); + let result = new Uint8Array(buffer); + result = textEncoder.encode("\uD800¥¥"); + ``` + ## RationalNumber8+ ### constructor9+ @@ -671,31 +694,6 @@ Parses a rational number. Previously, this processing is an internal action of t let rationalNumber = util.RationalNumber.parseRationalNumber(1,2) ``` -### constructor(deprecated) - -constructor(numerator: number,denominator: number) - -A constructor used to create a **RationalNumber** object. - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| numerator | number | Yes| Numerator, which is an integer.| -| denominator | number | Yes| Denominator, which is an integer.| - -**Example** - -```js -let rationalNumber = new util.RationalNumber(1,2); -``` - ### createRationalFromString8+ static createRationalFromString​(rationalString: string): RationalNumber​ @@ -751,38 +749,6 @@ let rational = util.RationalNumber.createRationalFromString("3/4"); let result = rationalNumber.compare(rational); ``` -### compareTo(deprecated) - -compareTo​(another: RationalNumber): number​ - -Compares this **RationalNumber** object with a given object. - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| - -**Example** - -```js -let rationalNumber = new util.RationalNumber(1,2); -let rational = util.RationalNumber.createRationalFromString("3/4"); -let result = rationalNumber.compareTo(rational); -``` - ### valueOf8+ valueOf(): number @@ -860,38 +826,6 @@ let rationalNumber = new util.RationalNumber(1,2); let result = util.RationalNumber.getCommonFactor(4,6); ``` -### getCommonDivisor(deprecated) - -static getCommonDivisor​(number1: number,number2: number): number - -Obtains the greatest common divisor of two specified integers. - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| number1 | number | Yes| The first integer used to get the greatest common divisor.| -| number2 | number | Yes| The second integer used to get the greatest common divisor.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Greatest common divisor obtained.| - -**Example** - -```js -let rationalNumber = new util.RationalNumber(1,2); -let result = util.RationalNumber.getCommonDivisor(4,6); -``` - ### getNumerator8+ getNumerator​(): number @@ -1018,6 +952,94 @@ let rationalNumber = new util.RationalNumber(1,2); let result = rationalNumber.toString(); ``` +### constructor(deprecated) + +constructor(numerator: number,denominator: number) + +A constructor used to create a **RationalNumber** object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| numerator | number | Yes| Numerator, which is an integer.| +| denominator | number | Yes| Denominator, which is an integer.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +``` + +### compareTo(deprecated) + +compareTo​(another: RationalNumber): number​ + +Compares this **RationalNumber** object with a given object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.compareTo(rational); +``` + +### getCommonDivisor(deprecated) + +static getCommonDivisor​(number1: number,number2: number): number + +Obtains the greatest common divisor of two specified integers. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| number1 | number | Yes| The first integer used to get the greatest common divisor.| +| number2 | number | Yes| The second integer used to get the greatest common divisor.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Greatest common divisor obtained.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = util.RationalNumber.getCommonDivisor(4,6); +``` ## LRUCache9+ @@ -1464,7 +1486,7 @@ lru.afterRemoval(false,10,30,null); ### contains9+ -contains(key: object): boolean +contains(key: K): boolean Checks whether this cache contains the specified key. @@ -1474,7 +1496,7 @@ Checks whether this cache contains the specified key. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| key | object | Yes | Key to check.| +| key | K | Yes | Key to check.| **Return value** @@ -1564,1026 +1586,1014 @@ pro.put(2,10); let result = pro[Symbol.iterator](); ``` -## LruBuffer(deprecated) - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. +## ScopeComparable8+ -### Attributes +The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Total number of values in this buffer.| +### compareTo8+ -**Example** +compareTo(other: ScopeComparable): boolean; - ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(1,8); - let result = pro.length; - ``` +Compares two values and returns a Boolean value. -### constructor(deprecated) +**System capability**: SystemCapability.Utils.Lang -constructor(capacity?: number) +**Parameters** -A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| other | [ScopeComparable](#scopecomparable8) | Yes | The other value to be compared with the current value.| -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +**Return value** -**System capability**: SystemCapability.Utils.Lang +| Type| Description | +| ---- | ------------------ | +| boolean | If the current value is greater than or equal to the input value, **true** is returned. Otherwise, **false** is returned.| -**Parameters** +**Example** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| capacity | number | No| Capacity of the **LruBuffer** to create.| +Create a class to implement the **compareTo** method. The **Temperature** class is used as an example in the following sample code. -**Example** +```js +class Temperature{ + constructor(value){ + // If TS is used for development, add the following code: + // private readonly _temp: Temperature; + this._temp = value; + } + compareTo(value){ + return this._temp >= value.getTemp(); + } + getTemp(){ + return this._temp; + } + toString(){ + return this._temp.toString(); + } +} +``` - ```js - let lrubuffer= new util.LruBuffer(); - ``` +## ScopeType8+ -### updateCapacity(deprecated) +Defines the type of values in a **Scope** object. -updateCapacity(newCapacity: number): void +**System capability**: SystemCapability.Utils.Lang -Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +| Type| Description| +| -------- | -------- | +| number | The value type is a number.| +| [ScopeComparable](#scopecomparable8) | The value type is ScopeComparable.| -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. +## ScopeHelper9+ + +### constructor9+ + +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +A constructor used to create a **ScopeHelper** object with the specified upper and lower limits. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| newCapacity | number | Yes| New capacity of the **LruBuffer**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit of the **Scope** object.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit of the **Scope** object.| **Example** ```js - let pro = new util.LruBuffer(); - let result = pro.updateCapacity(100); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); ``` -### toString(deprecated) -toString(): string +### toString9+ -Obtains the string representation of this **LruBuffer** object. +toString(): string -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +Obtains a string representation that contains this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| string | String representation of this **LruBuffer** object.| +| Type | Description | +| ------ | -------------------------------------- | +| string | String representation containing the **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - pro.remove(20); - let result = pro.toString(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.toString(); ``` -### getCapacity(deprecated) -getCapacity(): number +### intersect9+ -Obtains the capacity of this buffer. +intersect(range: ScopeHelper): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. +Obtains the intersection of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Capacity of this buffer.| +| Type | Description | +| ------------------------------ | ------------------------------ | +| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - let result = pro.getCapacity(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +range.intersect(rangeFir); ``` -### clear(deprecated) -clear(): void +### intersect9+ -Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. +Obtains the intersection of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| + +**Return value** + +| Type | Description | +| ---------------------------- | ---------------------------------------- | +| [ScopeHelper](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| + **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.length; - pro.clear(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.intersect(tempMiDF, tempMidS); ``` -### getCreateCount(deprecated) -getCreateCount(): number +### getUpper9+ -Obtains the number of return values for **createDefault()**. +getUpper(): ScopeType -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. +Obtains the upper limit of this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of return values for **createDefault()**.| +| Type | Description | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(1,8); - let result = pro.getCreateCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getUpper(); ``` -### getMissCount(deprecated) -getMissCount(): number +### getLower9+ -Obtains the number of times that the queried values are mismatched. +getLower(): ScopeType -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. +Obtains the lower limit of this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of times that the queried values are mismatched.| +| Type | Description | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMissCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getLower(); ``` -### getRemovalCount(deprecated) -getRemovalCount(): number +### expand9+ -Obtains the number of removals from this buffer. +expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. +Obtains the union set of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of removals from the buffer.| +| Type | Description | +| ---------------------------- | ------------------------------------ | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.updateCapacity(2); - pro.put(50,22); - let result = pro.getRemovalCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF, tempMidS); ``` -### getMatchCount(deprecated) -getMatchCount(): number +### expand9+ -Obtains the number of times that the queried values are matched. +expand(range: ScopeHelper): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. +Obtains the union set of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of times that the queried values are matched.| +| Type | Description | +| ---------------------------- | ---------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMatchCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +let result = range.expand(rangeFir); ``` -### getPutCount(deprecated) -getPutCount(): number +### expand9+ -Obtains the number of additions to this buffer. +expand(value: ScopeType): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. +Obtains the union set of this **Scope** and the given value. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of additions to the buffer.| +| Type | Description | +| ---------------------------- | -------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given value.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.getPutCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF); ``` -### isEmpty(deprecated) -isEmpty(): boolean +### contains9+ -Checks whether this buffer is empty. +contains(value: ScopeType): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. +Checks whether a value is within this **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the buffer does not contain any value.| +| Type | Description | +| ------- | --------------------------------------------------- | +| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.isEmpty(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +range.contains(tempMiDF); ``` -### get(deprecated) -get(key: K): V | undefined +### contains9+ -Obtains the value of the specified key. +contains(range: ScopeHelper): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. +Checks whether a range is within this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key based on which the value is queried.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** -| Type| Description| -| -------- | -------- | -| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| +| Type | Description | +| ------- | ----------------------------------------------------- | +| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.get(2); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempLess = new Temperature(20); +let tempMore = new Temperature(45); +let rangeSec = new util.ScopeHelper(tempLess, tempMore); +let result = range.contains(rangeSec); ``` -### put(deprecated) -put(key: K,value: V): V +### clamp9+ -Adds a key-value pair to this buffer. +clamp(value: ScopeType): ScopeType -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. +Limits a value to this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the key-value pair to add.| -| value | V | Yes| Value of the key-value pair to add.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | -------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| **Return value** -| Type| Description| -| -------- | -------- | -| V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | +| Type | Description | +| ------------------------ | ------------------------------------------------------------ | +| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - let result = pro.put(2,10); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.clamp(tempMiDF); ``` -### values(deprecated) +## Base64Helper9+ -values(): V[] +### constructor9+ -Obtains all values in this buffer, listed from the most to the least recently accessed. +constructor() -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. +A constructor used to create a **Base64Helper** instance. **System capability**: SystemCapability.Utils.Lang +**Example** + + ```js +let base64 = new util.Base64Helper(); + ``` + +### encodeSync9+ + +encodeSync(src: Uint8Array): Uint8Array + +Encodes the input content. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | Yes | Uint8Array to encode.| + **Return value** -| Type| Description| -| -------- | -------- | -| V [] | All values in the buffer, listed from the most to the least recently accessed.| +| Type | Description | +| ---------- | ----------------------------- | +| Uint8Array | Uint8Array encoded.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(2,"anhu"); - pro.put("afaf","grfb"); - let result = pro.values(); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeSync(array); ``` -### keys(deprecated) -keys(): K[] +### encodeToStringSync9+ -Obtains all keys in this buffer, listed from the most to the least recently accessed. +encodeToStringSync(src: Uint8Array): string -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. +Encodes the input content. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | Yes | Uint8Array to encode.| + **Return value** -| Type| Description| -| -------- | -------- | -| K [] | All keys in the buffer, listed from the most to the least recently accessed.| +| Type | Description | +| ------ | -------------------- | +| string | String encoded from the Uint8Array.| **Example** - ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.keys(); + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeToStringSync(array); ``` -### remove(deprecated) -remove(key: K): V | undefined +### decodeSync9+ -Removes the specified key and its value from this buffer. +decodeSync(src: Uint8Array | string): Uint8Array -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. +Decodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key to remove.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ----------------------------- | +| src | Uint8Array \| string | Yes | Uint8Array or string to decode.| **Return value** -| Type| Description| -| -------- | -------- | -| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| +| Type | Description | +| ---------- | ----------------------------- | +| Uint8Array | Uint8Array decoded.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.remove(20); +let that = new util.Base64Helper(); +let buff = 'czEz'; +let result = that.decodeSync(buff); ``` -### afterRemoval(deprecated) -afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void +### encode9+ -Performs subsequent operations after a value is removed. +encode(src: Uint8Array): Promise<Uint8Array> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. +Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| -| key | K | Yes| Key removed.| -| value | V | Yes| Value removed.| -| newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| + +**Return value** + +| Type | Description | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** ```js - let arr = []; - class ChildLruBuffer extends util.LruBuffer - { - constructor() - { - super(); - } - afterRemoval(isEvict, key, value, newValue) - { - if (isEvict === false) - { - arr = [key, value, newValue]; - } - } - } - let lru = new ChildLruBuffer(); - lru.afterRemoval(false,10,30,null); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let rarray = new Uint8Array([99,122,69,122]); +that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) ``` -### contains(deprecated) - -contains(key: K): boolean -Checks whether this buffer contains the specified key. +### encodeToString9+ +encodeToString(src: Uint8Array): Promise<string> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key to check.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| +| Type | Description | +| --------------------- | ------------------------ | +| Promise<string> | String obtained after asynchronous encoding.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.contains(20); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +that.encodeToString(array).then(val=>{ + console.log(val) +}) ``` -### createDefault(deprecated) -createDefault(key: K): V +### decode9+ -Creates a value if the value of the specified key is not available. +decode(src: Uint8Array | string): Promise<Uint8Array> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. +Decodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key of which the value is missing.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | --------------------------------- | +| src | Uint8Array \| string | Yes | Uint8Array or string to decode asynchronously.| **Return value** -| Type| Description| -| -------- | -------- | -| V | Value of the key.| +| Type | Description | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** ```js - let pro = new util.LruBuffer(); - let result = pro.createDefault(50); +let that = new util.Base64Helper(); +let array = new Uint8Array([99,122,69,122]); +let rarray = new Uint8Array([115,49,51]); +that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) ``` -### entries(deprecated) +## types8+ -entries(): IterableIterator<[K,V]> +### constructor8+ -Obtains a new iterator object that contains all key-value pairs in this object. +constructor() -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. +A constructor used to create a **Types** object. **System capability**: SystemCapability.Utils.Lang -**Return value** - -| Type| Description| -| -------- | -------- | -| [K, V] | Iterable array.| - **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.entries(); + let type = new util.types(); ``` -### [Symbol.iterator](deprecated) -[Symbol.iterator]\(): IterableIterator<[K, V]> +### isAnyArrayBuffer8+ -Obtains a two-dimensional array in key-value pairs. +isAnyArrayBuffer(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. +Checks whether the input value is of the **ArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [K, V] | Two-dimensional array in key-value pairs.| +| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro[Symbol.iterator](); + let that = new util.types(); + let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); ``` -### ScopeType8+ - -Defines the type of values in a **Scope** object. The value type can be **ScopeComparable** or **number**. - -The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. - -```js -interface ScopeComparable{ - compareTo(other: ScopeComparable): boolean; -} -type ScopeType = ScopeComparable | number; -``` - - -Create a class to implement the **compareTo** method. In the subsequent sample code, **Temperature** is used as an example of the [ScopeType](#scopetype8) object. - - -Example -```js -class Temperature{ - constructor(value){ - // If TS is used for development, add the following code: - // private readonly _temp: Temperature; - this._temp = value; - } - compareTo(value){ - return this._temp >= value.getTemp(); - } - getTemp(){ - return this._temp; - } - toString(){ - return this._temp.toString(); - } -} -``` -## ScopeHelper9+ +### isArrayBufferView8+ -### constructor9+ +isArrayBufferView(value: Object): boolean -constructor(lowerObj: ScopeType, upperObj: ScopeType) +Checks whether the input value is of the **ArrayBufferView** type. -A constructor used to create a **ScopeHelper** object with the specified upper and lower limits. +**ArrayBufferView** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit of the **Scope** object.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit of the **Scope** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); + let that = new util.types(); + let result = that.isArrayBufferView(new Int8Array([])); ``` -### toString9+ +### isArgumentsObject8+ -toString(): string +isArgumentsObject(value: Object): boolean -Obtains a string representation that contains this **Scope**. +Checks whether the input value is of the **arguments** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------ | -------------------------------------- | -| string | String representation containing the **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.toString(); + let that = new util.types(); + function foo() { + var result = that.isArgumentsObject(arguments); + } + let f = foo(); ``` -### intersect9+ +### isArrayBuffer8+ -intersect(range: ScopeHelper): ScopeHelper +isArrayBuffer(value: Object): boolean -Obtains the intersection of this **Scope** and the given **Scope**. +Checks whether the input value is of the **ArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------- | ---- | ------------------ | -| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------------ | ------------------------------ | -| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); -range.intersect(rangeFir ); + let that = new util.types(); + let result = that.isArrayBuffer(new ArrayBuffer(0)); ``` -### intersect9+ +### isAsyncFunction8+ -intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper +isAsyncFunction(value: Object): boolean -Obtains the intersection of this **Scope** and the given lower and upper limits. +Checks whether the input value is an asynchronous function. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------------------- | -| [ScopeHelper](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.intersect(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isAsyncFunction(async function foo() {}); ``` -### getUpper9+ +### isBooleanObject8+ -getUpper(): ScopeType +isBooleanObject(value: Object): boolean -Obtains the upper limit of this **Scope**. +Checks whether the input value is of the **Boolean** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------------------------ | ---------------------- | -| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.getUpper(); + let that = new util.types(); + let result = that.isBooleanObject(new Boolean(true)); ``` -### getLower9+ +### isBoxedPrimitive8+ -getLower(): ScopeType +isBoxedPrimitive(value: Object): boolean -Obtains the lower limit of this **Scope**. +Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------------------------ | ---------------------- | -| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.getLower(); + let that = new util.types(); + let result = that.isBoxedPrimitive(new Boolean(false)); ``` -### expand9+ +### isDataView8+ -expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper +isDataView(value: Object): boolean -Obtains the union set of this **Scope** and the given lower and upper limits. +Checks whether the input value is of the **DataView** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------------------ | -| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.expand(tempMiDF, tempMidS); + let that = new util.types(); + const ab = new ArrayBuffer(20); + let result = that.isDataView(new DataView(ab)); ``` -### expand9+ +### isDate8+ -expand(range: ScopeHelper): ScopeHelper +isDate(value: Object): boolean -Obtains the union set of this **Scope** and the given **Scope**. +Checks whether the input value is of the **Date** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------- | ---- | ------------------ | -| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------------- | -| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); -let result = range.expand(rangeFir); + let that = new util.types(); + let result = that.isDate(new Date()); ``` -### expand9+ +### isExternal8+ -expand(value: ScopeType): ScopeHelper +isExternal(value: Object): boolean -Obtains the union set of this **Scope** and the given value. +Checks whether the input value is of the **native external** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | ---------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | -------------------------------- | -| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given value.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.expand(tempMiDF); + let that = new util.types(); + let result = that.isExternal(true); ``` -### contains9+ +### isFloat32Array8+ -contains(value: ScopeType): boolean +isFloat32Array(value: Object): boolean -Checks whether a value is within this **Scope**. +Checks whether the input value is of the **Float32Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | ---------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------- | --------------------------------------------------- | -| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -range.contains(tempMiDF); + let that = new util.types(); + let result = that.isFloat32Array(new Float32Array()); ``` -### contains9+ +### isFloat64Array8+ -contains(range: ScopeHelper): boolean +isFloat64Array(value: Object): boolean -Checks whether a range is within this **Scope**. +Checks whether the input value is of the **Float64Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------- | ---- | ------------------ | -| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------- | ----------------------------------------------------- | -| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let tempLess = new Temperature(20); -let tempMore = new Temperature(45); -let rangeSec = new util.ScopeHelper(tempLess, tempMore); -let result = range.contains(rangeSec); + let that = new util.types(); + let result = that.isFloat64Array(new Float64Array()); ``` -### clamp9+ +### isGeneratorFunction8+ -clamp(value: ScopeType): ScopeType +isGeneratorFunction(value: Object): boolean -Limits a value to this **Scope**. +Checks whether the input value is a generator function. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | -------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------ | ------------------------------------------------------------ | -| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.clamp(tempMiDF); + let that = new util.types(); + let result = that.isGeneratorFunction(function* foo() {}); ``` -## Scope(deprecated) - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. - -### constructor(deprecated) - -constructor(lowerObj: ScopeType, upperObj: ScopeType) -A constructor used to create a **Scope** object with the specified upper and lower limits. +### isGeneratorObject8+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +isGeneratorObject(value: Object): boolean +Checks whether the input value is a generator object. **System capability**: SystemCapability.Utils.Lang @@ -2591,52 +2601,57 @@ A constructor used to create a **Scope** object with the specified upper and low | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit of the **Scope** object.| +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); + let that = new util.types(); + function* foo() {} + const generator = foo(); + let result = that.isGeneratorObject(generator); ``` -### toString(deprecated) -toString(): string +### isInt8Array8+ -Obtains a string representation that contains this **Scope**. +isInt8Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +Checks whether the input value is of the **Int8Array** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| string | String representation containing the **Scope**.| +| boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.toString(); + let that = new util.types(); + let result = that.isInt8Array(new Int8Array([])); ``` -### intersect(deprecated) -intersect(range: Scope): Scope +### isInt16Array8+ -Obtains the intersection of this **Scope** and the given **Scope**. +isInt16Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +Checks whether the input value is of the **Int16Array** type. **System capability**: SystemCapability.Utils.Lang @@ -2644,35 +2659,27 @@ Obtains the intersection of this **Scope** and the given **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given **Scope**.| +| boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let rangeFir = new util.Scope(tempMiDF, tempMidS); - range.intersect(rangeFir ); + let that = new util.types(); + let result = that.isInt16Array(new Int16Array([])); ``` -### intersect(deprecated) -intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope +### isInt32Array8+ -Obtains the intersection of this **Scope** and the given lower and upper limits. +isInt32Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +Checks whether the input value is of the **Int32Array** type. **System capability**: SystemCapability.Utils.Lang @@ -2680,89 +2687,85 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| +| boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let result = range.intersect(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isInt32Array(new Int32Array([])); ``` -### getUpper(deprecated) -getUpper(): ScopeType +### isMap8+ -Obtains the upper limit of this **Scope**. +isMap(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. +Checks whether the input value is of the **Map** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| +| boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.getUpper(); + let that = new util.types(); + let result = that.isMap(new Map()); ``` -### getLower(deprecated) -getLower(): ScopeType +### isMapIterator8+ -Obtains the lower limit of this **Scope**. +isMapIterator(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. +Checks whether the input value is of the **MapIterator** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| +| boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.getLower(); + let that = new util.types(); + const map = new Map(); + let result = that.isMapIterator(map.keys()); ``` -### expand(deprecated) -expand(lowerObj: ScopeType,upperObj: ScopeType): Scope +### isNativeError8+ -Obtains the union set of this **Scope** and the given lower and upper limits. +isNativeError(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +Checks whether the input value is of the **Error** type. **System capability**: SystemCapability.Utils.Lang @@ -2770,35 +2773,27 @@ Obtains the union set of this **Scope** and the given lower and upper limits. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given lower and upper limits.| +| boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let result = range.expand(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isNativeError(new TypeError()); ``` -### expand(deprecated) -expand(range: Scope): Scope +### isNumberObject8+ -Obtains the union set of this **Scope** and the given **Scope**. +isNumberObject(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +Checks whether the input value is a number object. **System capability**: SystemCapability.Utils.Lang @@ -2806,35 +2801,27 @@ Obtains the union set of this **Scope** and the given **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| +| boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let rangeFir = new util.Scope(tempMiDF, tempMidS); - let result = range.expand(rangeFir); + let that = new util.types(); + let result = that.isNumberObject(new Number(0)); ``` -### expand(deprecated) -expand(value: ScopeType): Scope +### isPromise8+ -Obtains the union set of this **Scope** and the given value. +isPromise(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +Checks whether the input value is a promise. **System capability**: SystemCapability.Utils.Lang @@ -2842,33 +2829,27 @@ Obtains the union set of this **Scope** and the given value. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| +| boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - let result = range.expand(tempMiDF); + let that = new util.types(); + let result = that.isPromise(Promise.resolve(1)); ``` -### contains(deprecated) -contains(value: ScopeType): boolean +### isProxy8+ -Checks whether a value is within this **Scope**. +isProxy(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +Checks whether the input value is a proxy. **System capability**: SystemCapability.Utils.Lang @@ -2876,33 +2857,29 @@ Checks whether a value is within this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| +| boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - range.contains(tempMiDF); + let that = new util.types(); + const target = {}; + const proxy = new Proxy(target, {}); + let result = that.isProxy(proxy); ``` -### contains(deprecated) - -contains(range: Scope): boolean -Checks whether a range is within this **Scope**. +### isRegExp8+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +isRegExp(value: Object): boolean + +Checks whether the input value is of the **RegExp** type. **System capability**: SystemCapability.Utils.Lang @@ -2910,36 +2887,27 @@ Checks whether a range is within this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| +| boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let tempLess = new Temperature(20); - let tempMore = new Temperature(45); - let rangeSec = new util.Scope(tempLess, tempMore); - let result = range.contains(rangeSec); + let that = new util.types(); + let result = that.isRegExp(new RegExp('abc')); ``` -### clamp(deprecated) - -clamp(value: ScopeType): ScopeType +### isSet8+ -Limits a value to this **Scope**. +isSet(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. +Checks whether the input value is of the **Set** type. **System capability**: SystemCapability.Utils.Lang @@ -2947,259 +2915,255 @@ Limits a value to this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| +| boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - let result = range.clamp(tempMiDF); + let that = new util.types(); + let result = that.isSet(new Set()); ``` -## Base64Helper9+ -### constructor9+ +### isSetIterator8+ -constructor() +isSetIterator(value: Object): boolean -A constructor used to create a **Base64Helper** instance. +Checks whether the input value is of the **SetIterator** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| + **Example** ```js -let base64 = new util.Base64Helper(); + let that = new util.types(); + const set = new Set(); + let result = that.isSetIterator(set.keys()); ``` -### encodeSync9+ -encodeSync(src: Uint8Array): Uint8Array +### isStringObject8+ -Encodes the input content. +isStringObject(value: Object): boolean + +Checks whether the input value is a string object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------------- | -| src | Uint8Array | Yes | Uint8Array to encode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------- | ----------------------------- | -| Uint8Array | Uint8Array encoded.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeSync(array); + let that = new util.types(); + let result = that.isStringObject(new String('foo')); ``` -### encodeToStringSync9+ +### isSymbolObjec8+ -encodeToStringSync(src: Uint8Array): string +isSymbolObject(value: Object): boolean -Encodes the input content. +Checks whether the input value is a symbol object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------------- | -| src | Uint8Array | Yes | Uint8Array to encode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------ | -------------------- | -| string | String encoded from the Uint8Array.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeToStringSync(array); + let that = new util.types(); + const symbols = Symbol('foo'); + let result = that.isSymbolObject(Object(symbols)); ``` -### decodeSync9+ +### isTypedArray8+ -decodeSync(src: Uint8Array | string): Uint8Array +isTypedArray(value: Object): boolean -Decodes the input content. +Checks whether the input value is of the **TypedArray** type. + +**TypedArray** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint16Array**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ----------------------------- | -| src | Uint8Array \| string | Yes | Uint8Array or string to decode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------- | ----------------------------- | -| Uint8Array | Uint8Array decoded.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let buff = 'czEz'; -let result = that.decodeSync(buff); + let that = new util.types(); + let result = that.isTypedArray(new Float64Array([])); ``` -### encode9+ +### isUint8Array8+ -encode(src: Uint8Array): Promise<Uint8Array> +isUint8Array(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is of the **Uint8Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ----------------------- | -| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------- | --------------------------------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let rarray = new Uint8Array([99,122,69,122]); -that.encode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } -}) + let that = new util.types(); + let result = that.isUint8Array(new Uint8Array([])); ``` -### encodeToString9+ +### isUint8ClampedArray8+ -encodeToString(src: Uint8Array): Promise<string> +isUint8ClampedArray(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is of the **Uint8ClampedArray** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ----------------------- | -| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| --------------------- | ------------------------ | -| Promise<string> | String obtained after asynchronous encoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -that.encodeToString(array).then(val=>{ - console.log(val) -}) + let that = new util.types(); + let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); ``` -### decode9+ +### isUint16Array8+ -decode(src: Uint8Array | string): Promise<Uint8Array> +isUint16Array(value: Object): boolean -Decodes the input content asynchronously. +Checks whether the input value is of the **Uint16Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | --------------------------------- | -| src | Uint8Array \| string | Yes | Uint8Array or string to decode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------- | --------------------------------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([99,122,69,122]); -let rarray = new Uint8Array([115,49,51]); -that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } -}) + let that = new util.types(); + let result = that.isUint16Array(new Uint16Array([])); ``` -## Base64(deprecated) +### isUint32Array8+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. +isUint32Array(value: Object): boolean -### constructor(deprecated) +Checks whether the input value is of the **Uint32Array** type. -constructor() +**System capability**: SystemCapability.Utils.Lang -A constructor used to create a **Base64** object. +**Parameters** -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| -**System capability**: SystemCapability.Utils.Lang +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| **Example** ```js - let base64 = new util.Base64(); + let that = new util.types(); + let result = that.isUint32Array(new Uint32Array([])); ``` -### encodeSync(deprecated) -encodeSync(src: Uint8Array): Uint8Array +### isWeakMap8+ -Encodes the input content. +isWeakMap(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. +Checks whether the input value is of the **WeakMap** type. **System capability**: SystemCapability.Utils.Lang @@ -3207,31 +3171,27 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Uint8Array | Uint8Array encoded.| +| boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let result = that.encodeSync(array); + let that = new util.types(); + let result = that.isWeakMap(new WeakMap()); ``` -### encodeToStringSync(deprecated) -encodeToStringSync(src: Uint8Array): string +### isWeakSet8+ -Encodes the input content. +isWeakSet(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. +Checks whether the input value is of the **WeakSet** type. **System capability**: SystemCapability.Utils.Lang @@ -3239,31 +3199,27 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| string | String encoded from the Uint8Array.| +| boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let result = that.encodeToStringSync(array); + let that = new util.types(); + let result = that.isWeakSet(new WeakSet()); ``` -### decodeSync(deprecated) -decodeSync(src: Uint8Array | string): Uint8Array +### isBigInt64Array8+ -Decodes the input content. +isBigInt64Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. +Checks whether the input value is of the **BigInt64Array** type. **System capability**: SystemCapability.Utils.Lang @@ -3271,31 +3227,27 @@ Decodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array \| string | Yes| Uint8Array or string to decode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Uint8Array | Uint8Array decoded.| +| boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let buff = 'czEz'; - let result = that.decodeSync(buff); + let that = new util.types(); + let result = that.isBigInt64Array(new BigInt64Array([])); ``` -### encode(deprecated) -encode(src: Uint8Array): Promise<Uint8Array> +### isBigUint64Array8+ -Encodes the input content asynchronously. +isBigUint64Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. +Checks whether the input value is of the **BigUint64Array** type. **System capability**: SystemCapability.Utils.Lang @@ -3303,36 +3255,27 @@ Encodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| +| boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let rarray = new Uint8Array([99,122,69,122]); - that.encode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } - }) + let that = new util.types(); + let result = that.isBigUint64Array(new BigUint64Array([])); ``` -### encodeToString(deprecated) -encodeToString(src: Uint8Array): Promise<string> +### isModuleNamespaceObject8+ -Encodes the input content asynchronously. +isModuleNamespaceObject(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. +Checks whether the input value is a module namespace object. **System capability**: SystemCapability.Utils.Lang @@ -3340,34 +3283,28 @@ Encodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<string> | String obtained after asynchronous encoding.| +| boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - that.encodeToString(array).then(val=>{ - console.log(val) - }) + import url from '@ohos.url' + let that = new util.types(); + let result = that.isModuleNamespaceObject(url); ``` -### decode(deprecated) - -decode(src: Uint8Array | string): Promise<Uint8Array> +### isSharedArrayBuffer8+ -Decodes the input content asynchronously. +isSharedArrayBuffer(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. +Checks whether the input value is of the **SharedArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang @@ -3375,50 +3312,53 @@ Decodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| +| boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([99,122,69,122]); - let rarray = new Uint8Array([115,49,51]); - that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } - }) + let that = new util.types(); + let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); ``` -## types8+ - - -### constructor8+ +## LruBuffer(deprecated) -constructor() +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. -A constructor used to create a **Types** object. +### Attributes **System capability**: SystemCapability.Utils.Lang +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Total number of values in this buffer.| + **Example** ```js - let type = new util.types(); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(1,8); + let result = pro.length; ``` +### constructor(deprecated) -### isAnyArrayBuffer8+ +constructor(capacity?: number) -isAnyArrayBuffer(value: Object): boolean +A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. -Checks whether the input value is of the **ArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3426,29 +3366,23 @@ Checks whether the input value is of the **ArrayBuffer** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| +| capacity | number | No| Capacity of the **LruBuffer** to create.| **Example** ```js - let that = new util.types(); - let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); + let lrubuffer= new util.LruBuffer(); ``` +### updateCapacity(deprecated) -### isArrayBufferView8+ - -isArrayBufferView(value: Object): boolean +updateCapacity(newCapacity: number): void -Checks whether the input value is of the **ArrayBufferView** type. +Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. -**ArrayBufferView** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3456,255 +3390,257 @@ Checks whether the input value is of the **ArrayBufferView** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| +| newCapacity | number | Yes| New capacity of the **LruBuffer**.| **Example** ```js - let that = new util.types(); - let result = that.isArrayBufferView(new Int8Array([])); + let pro = new util.LruBuffer(); + let result = pro.updateCapacity(100); ``` +### toString(deprecated) -### isArgumentsObject8+ +toString(): string -isArgumentsObject(value: Object): boolean +Obtains the string representation of this **LruBuffer** object. -Checks whether the input value is of the **arguments** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| +| string | String representation of this **LruBuffer** object.| **Example** ```js - let that = new util.types(); - function foo() { - var result = that.isArgumentsObject(arguments); - } - let f = foo(); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + pro.remove(20); + let result = pro.toString(); ``` +### getCapacity(deprecated) -### isArrayBuffer8+ +getCapacity(): number -isArrayBuffer(value: Object): boolean +Obtains the capacity of this buffer. -Checks whether the input value is of the **ArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| +| number | Capacity of this buffer.| **Example** - ```js - let that = new util.types(); - let result = that.isArrayBuffer(new ArrayBuffer(0)); + let pro = new util.LruBuffer(); + let result = pro.getCapacity(); ``` +### clear(deprecated) -### isAsyncFunction8+ +clear(): void -isAsyncFunction(value: Object): boolean +Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. -Checks whether the input value is an asynchronous function. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** +**Example** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.length; + pro.clear(); + ``` + +### getCreateCount(deprecated) + +getCreateCount(): number + +Obtains the number of return values for **createDefault()**. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| +| number | Number of return values for **createDefault()**.| **Example** ```js - let that = new util.types(); - let result = that.isAsyncFunction(async function foo() {}); + let pro = new util.LruBuffer(); + pro.put(1,8); + let result = pro.getCreateCount(); ``` +### getMissCount(deprecated) -### isBooleanObject8+ +getMissCount(): number -isBooleanObject(value: Object): boolean +Obtains the number of times that the queried values are mismatched. -Checks whether the input value is of the **Boolean** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| +| number | Number of times that the queried values are mismatched.| **Example** ```js - let that = new util.types(); - let result = that.isBooleanObject(new Boolean(true)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMissCount(); ``` +### getRemovalCount(deprecated) -### isBoxedPrimitive8+ +getRemovalCount(): number -isBoxedPrimitive(value: Object): boolean +Obtains the number of removals from this buffer. -Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| +| number | Number of removals from the buffer.| **Example** ```js - let that = new util.types(); - let result = that.isBoxedPrimitive(new Boolean(false)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.updateCapacity(2); + pro.put(50,22); + let result = pro.getRemovalCount(); ``` +### getMatchCount(deprecated) -### isDataView8+ +getMatchCount(): number -isDataView(value: Object): boolean +Obtains the number of times that the queried values are matched. -Checks whether the input value is of the **DataView** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| +| number | Number of times that the queried values are matched.| **Example** ```js - let that = new util.types(); - const ab = new ArrayBuffer(20); - let result = that.isDataView(new DataView(ab)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMatchCount(); ``` +### getPutCount(deprecated) -### isDate8+ +getPutCount(): number -isDate(value: Object): boolean +Obtains the number of additions to this buffer. -Checks whether the input value is of the **Date** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| +| number | Number of additions to the buffer.| **Example** ```js - let that = new util.types(); - let result = that.isDate(new Date()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.getPutCount(); ``` +### isEmpty(deprecated) -### isExternal8+ +isEmpty(): boolean -isExternal(value: Object): boolean +Checks whether this buffer is empty. -Checks whether the input value is of the **native external** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| +| boolean | Returns **true** if the buffer does not contain any value.| **Example** ```js - let that = new util.types(); - let result = that.isExternal(true); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.isEmpty(); ``` +### get(deprecated) -### isFloat32Array8+ +get(key: K): V | undefined -isFloat32Array(value: Object): boolean +Obtains the value of the specified key. -Checks whether the input value is of the **Float32Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3712,27 +3648,31 @@ Checks whether the input value is of the **Float32Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key based on which the value is queried.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| +| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isFloat32Array(new Float32Array()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.get(2); ``` +### put(deprecated) -### isFloat64Array8+ +put(key: K,value: V): V -isFloat64Array(value: Object): boolean +Adds a key-value pair to this buffer. -Checks whether the input value is of the **Float64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3740,85 +3680,84 @@ Checks whether the input value is of the **Float64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key of the key-value pair to add.| +| value | V | Yes| Value of the key-value pair to add.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| +| V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | **Example** ```js - let that = new util.types(); - let result = that.isFloat64Array(new Float64Array()); + let pro = new util.LruBuffer(); + let result = pro.put(2,10); ``` +### values(deprecated) -### isGeneratorFunction8+ +values(): V[] -isGeneratorFunction(value: Object): boolean +Obtains all values in this buffer, listed from the most to the least recently accessed. -Checks whether the input value is a generator function. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| +| V [] | All values in the buffer, listed from the most to the least recently accessed.| **Example** ```js - let that = new util.types(); - let result = that.isGeneratorFunction(function* foo() {}); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(2,"anhu"); + pro.put("afaf","grfb"); + let result = pro.values(); ``` +### keys(deprecated) -### isGeneratorObject8+ +keys(): K[] -isGeneratorObject(value: Object): boolean +Obtains all keys in this buffer, listed from the most to the least recently accessed. -Checks whether the input value is a generator object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| +| K [] | All keys in the buffer, listed from the most to the least recently accessed.| **Example** - ```js - let that = new util.types(); - function* foo() {} - const generator = foo(); - let result = that.isGeneratorObject(generator); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.keys(); ``` +### remove(deprecated) -### isInt8Array8+ +remove(key: K): V | undefined -isInt8Array(value: Object): boolean +Removes the specified key and its value from this buffer. -Checks whether the input value is of the **Int8Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3826,27 +3765,30 @@ Checks whether the input value is of the **Int8Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key to remove.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| **Example** - ```js - let that = new util.types(); - let result = that.isInt8Array(new Int8Array([])); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.remove(20); ``` +### afterRemoval(deprecated) -### isInt16Array8+ +afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void -isInt16Array(value: Object): boolean +Performs subsequent operations after a value is removed. -Checks whether the input value is of the **Int16Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3854,27 +3796,43 @@ Checks whether the input value is of the **Int16Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| +| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| +| key | K | Yes| Key removed.| +| value | V | Yes| Value removed.| +| newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** ```js - let that = new util.types(); - let result = that.isInt16Array(new Int16Array([])); + let arr = []; + class ChildLruBuffer extends util.LruBuffer + { + constructor() + { + super(); + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } + } + let lru = new ChildLruBuffer(); + lru.afterRemoval(false,10,30,null); ``` +### contains(deprecated) -### isInt32Array8+ +contains(key: K): boolean -isInt32Array(value: Object): boolean +Checks whether this buffer contains the specified key. -Checks whether the input value is of the **Int32Array** type. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3882,27 +3840,31 @@ Checks whether the input value is of the **Int32Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| +| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isInt32Array(new Int32Array([])); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.contains(20); ``` +### createDefault(deprecated) -### isMap8+ +createDefault(key: K): V -isMap(value: Object): boolean +Creates a value if the value of the specified key is not available. -Checks whether the input value is of the **Map** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3910,85 +3872,89 @@ Checks whether the input value is of the **Map** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key of which the value is missing.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| +| V | Value of the key.| **Example** ```js - let that = new util.types(); - let result = that.isMap(new Map()); + let pro = new util.LruBuffer(); + let result = pro.createDefault(50); ``` +### entries(deprecated) -### isMapIterator8+ +entries(): IterableIterator<[K,V]> -isMapIterator(value: Object): boolean +Obtains a new iterator object that contains all key-value pairs in this object. -Checks whether the input value is of the **MapIterator** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| +| [K, V] | Iterable array.| **Example** ```js - let that = new util.types(); - const map = new Map(); - let result = that.isMapIterator(map.keys()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.entries(); ``` +### [Symbol.iterator](deprecated) -### isNativeError8+ +[Symbol.iterator]\(): IterableIterator<[K, V]> -isNativeError(value: Object): boolean +Obtains a two-dimensional array in key-value pairs. -Checks whether the input value is of the **Error** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| +| [K, V] | Two-dimensional array in key-value pairs.| **Example** ```js - let that = new util.types(); - let result = that.isNativeError(new TypeError()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro[Symbol.iterator](); ``` +## Scope(deprecated) -### isNumberObject8+ +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. -isNumberObject(value: Object): boolean +### constructor(deprecated) + +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +A constructor used to create a **Scope** object with the specified upper and lower limits. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. -Checks whether the input value is a number object. **System capability**: SystemCapability.Utils.Lang @@ -3996,55 +3962,52 @@ Checks whether the input value is a number object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit of the **Scope** object.| **Example** - ```js - let that = new util.types(); - let result = that.isNumberObject(new Number(0)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); ``` +### toString(deprecated) -### isPromise8+ +toString(): string -isPromise(value: Object): boolean +Obtains a string representation that contains this **Scope**. -Checks whether the input value is a promise. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| +| string | String representation containing the **Scope**.| **Example** ```js - let that = new util.types(); - let result = that.isPromise(Promise.resolve(1)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.toString(); ``` +### intersect(deprecated) -### isProxy8+ +intersect(range: Scope): Scope -isProxy(value: Object): boolean +Obtains the intersection of this **Scope** and the given **Scope**. -Checks whether the input value is a proxy. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4052,29 +4015,35 @@ Checks whether the input value is a proxy. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given **Scope**.| **Example** ```js - let that = new util.types(); - const target = {}; - const proxy = new Proxy(target, {}); - let result = that.isProxy(proxy); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let rangeFir = new util.Scope(tempMiDF, tempMidS); + range.intersect(rangeFir ); ``` +### intersect(deprecated) -### isRegExp8+ +intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope -isRegExp(value: Object): boolean +Obtains the intersection of this **Scope** and the given lower and upper limits. -Checks whether the input value is of the **RegExp** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4082,84 +4051,89 @@ Checks whether the input value is of the **RegExp** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| **Example** ```js - let that = new util.types(); - let result = that.isRegExp(new RegExp('abc')); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.intersect(tempMiDF, tempMidS); ``` +### getUpper(deprecated) -### isSet8+ +getUpper(): ScopeType -isSet(value: Object): boolean +Obtains the upper limit of this **Scope**. -Checks whether the input value is of the **Set** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** ```js - let that = new util.types(); - let result = that.isSet(new Set()); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getUpper(); ``` +### getLower(deprecated) -### isSetIterator8+ +getLower(): ScopeType -isSetIterator(value: Object): boolean +Obtains the lower limit of this **Scope**. -Checks whether the input value is of the **SetIterator** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** ```js - let that = new util.types(); - const set = new Set(); - let result = that.isSetIterator(set.keys()); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getLower(); ``` +### expand(deprecated) -### isStringObject8+ +expand(lowerObj: ScopeType,upperObj: ScopeType): Scope -isStringObject(value: Object): boolean +Obtains the union set of this **Scope** and the given lower and upper limits. -Checks whether the input value is a string object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4167,27 +4141,35 @@ Checks whether the input value is a string object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given lower and upper limits.| **Example** ```js - let that = new util.types(); - let result = that.isStringObject(new String('foo')); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF, tempMidS); ``` +### expand(deprecated) -### isSymbolObjec8+ +expand(range: Scope): Scope -isSymbolObject(value: Object): boolean +Obtains the union set of this **Scope** and the given **Scope**. -Checks whether the input value is a symbol object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4195,30 +4177,35 @@ Checks whether the input value is a symbol object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| **Example** ```js - let that = new util.types(); - const symbols = Symbol('foo'); - let result = that.isSymbolObject(Object(symbols)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let rangeFir = new util.Scope(tempMiDF, tempMidS); + let result = range.expand(rangeFir); ``` +### expand(deprecated) -### isTypedArray8+ - -isTypedArray(value: Object): boolean +expand(value: ScopeType): Scope -Checks whether the input value is of the **TypedArray** type. +Obtains the union set of this **Scope** and the given value. -**TypedArray** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint16Array**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4226,27 +4213,33 @@ Checks whether the input value is of the **TypedArray** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| **Example** ```js - let that = new util.types(); - let result = that.isTypedArray(new Float64Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF); ``` +### contains(deprecated) -### isUint8Array8+ +contains(value: ScopeType): boolean -isUint8Array(value: Object): boolean +Checks whether a value is within this **Scope**. -Checks whether the input value is of the **Uint8Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4254,27 +4247,33 @@ Checks whether the input value is of the **Uint8Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| +| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isUint8Array(new Uint8Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + range.contains(tempMiDF); ``` +### contains(deprecated) -### isUint8ClampedArray8+ +contains(range: Scope): boolean -isUint8ClampedArray(value: Object): boolean +Checks whether a range is within this **Scope**. -Checks whether the input value is of the **Uint8ClampedArray** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4282,27 +4281,36 @@ Checks whether the input value is of the **Uint8ClampedArray** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| +| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempLess = new Temperature(20); + let tempMore = new Temperature(45); + let rangeSec = new util.Scope(tempLess, tempMore); + let result = range.contains(rangeSec); ``` +### clamp(deprecated) -### isUint16Array8+ -isUint16Array(value: Object): boolean +clamp(value: ScopeType): ScopeType -Checks whether the input value is of the **Uint16Array** type. +Limits a value to this **Scope**. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4310,55 +4318,58 @@ Checks whether the input value is of the **Uint16Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** ```js - let that = new util.types(); - let result = that.isUint16Array(new Uint16Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.clamp(tempMiDF); ``` -### isUint32Array8+ - -isUint32Array(value: Object): boolean +## Base64(deprecated) -Checks whether the input value is of the **Uint32Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. -**System capability**: SystemCapability.Utils.Lang +### constructor(deprecated) -**Parameters** +constructor() -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +A constructor used to create a **Base64** object. -**Return value** +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| +**System capability**: SystemCapability.Utils.Lang **Example** ```js - let that = new util.types(); - let result = that.isUint32Array(new Uint32Array([])); + let base64 = new util.Base64(); ``` +### encodeSync(deprecated) -### isWeakMap8+ +encodeSync(src: Uint8Array): Uint8Array -isWeakMap(value: Object): boolean +Encodes the input content. -Checks whether the input value is of the **WeakMap** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4366,27 +4377,31 @@ Checks whether the input value is of the **WeakMap** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| +| Uint8Array | Uint8Array encoded.| **Example** ```js - let that = new util.types(); - let result = that.isWeakMap(new WeakMap()); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeSync(array); ``` +### encodeToStringSync(deprecated) -### isWeakSet8+ +encodeToStringSync(src: Uint8Array): string -isWeakSet(value: Object): boolean +Encodes the input content. -Checks whether the input value is of the **WeakSet** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4394,27 +4409,31 @@ Checks whether the input value is of the **WeakSet** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| +| string | String encoded from the Uint8Array.| **Example** ```js - let that = new util.types(); - let result = that.isWeakSet(new WeakSet()); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeToStringSync(array); ``` +### decodeSync(deprecated) -### isBigInt64Array8+ +decodeSync(src: Uint8Array | string): Uint8Array -isBigInt64Array(value: Object): boolean +Decodes the input content. -Checks whether the input value is of the **BigInt64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4422,27 +4441,31 @@ Checks whether the input value is of the **BigInt64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array \| string | Yes| Uint8Array or string to decode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| +| Uint8Array | Uint8Array decoded.| **Example** ```js - let that = new util.types(); - let result = that.isBigInt64Array(new BigInt64Array([])); + let that = new util.Base64(); + let buff = 'czEz'; + let result = that.decodeSync(buff); ``` +### encode(deprecated) -### isBigUint64Array8+ +encode(src: Uint8Array): Promise<Uint8Array> -isBigUint64Array(value: Object): boolean +Encodes the input content asynchronously. -Checks whether the input value is of the **BigUint64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4450,27 +4473,36 @@ Checks whether the input value is of the **BigUint64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| +| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** ```js - let that = new util.types(); - let result = that.isBigUint64Array(new BigUint64Array([])); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let rarray = new Uint8Array([99,122,69,122]); + that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } + }) ``` +### encodeToString(deprecated) -### isModuleNamespaceObject8+ +encodeToString(src: Uint8Array): Promise<string> -isModuleNamespaceObject(value: Object): boolean +Encodes the input content asynchronously. -Checks whether the input value is a module namespace object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4478,28 +4510,34 @@ Checks whether the input value is a module namespace object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| +| Promise<string> | String obtained after asynchronous encoding.| **Example** ```js - import url from '@ohos.url' - let that = new util.types(); - let result = that.isModuleNamespaceObject(url); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + that.encodeToString(array).then(val=>{ + console.log(val) + }) ``` +### decode(deprecated) + -### isSharedArrayBuffer8+ +decode(src: Uint8Array | string): Promise<Uint8Array> -isSharedArrayBuffer(value: Object): boolean +Decodes the input content asynchronously. -Checks whether the input value is of the **SharedArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4507,18 +4545,25 @@ Checks whether the input value is of the **SharedArrayBuffer** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| +| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** ```js - let that = new util.types(); - let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); + let that = new util.Base64(); + let array = new Uint8Array([99,122,69,122]); + let rarray = new Uint8Array([115,49,51]); + that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } + }) ``` + diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index cff7eed5a375d77355bf7f20d26b497bff57d7a9..f99f74149b06752ec0d1edf51ba5c46e40e3e43e 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -1,4 +1,4 @@ -# Vibrator +# @ohos.vibrator (Vibrator) The **vibrator** module provides APIs for starting or stopping vibration. diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index b0bad9b58fd5a74501fe45c9e2995a26236a8f30..215816e358a3c70d147a149db7c9142a15535ec1 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -707,7 +707,7 @@ WantAgent.equal(wantAgent1, wantAgent2, equalCallback) equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index a205de94d8080753ed0305f56fb6fc5ce8534707..455416ed7c1290971e5a797766d35c52ed08b537 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -43,9 +43,9 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); **Table 1** Type -| Name| Type| +| Name| Type| | -------- | -------- | -| GLenum | number | +| GLenum | number | | GLboolean | boolean | | GLbitfield | number | | GLbyte | number | @@ -58,7 +58,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | GLushort | number | | GLuint | number | | GLfloat | number | -| GLclampf | number | +| GLclampf | number | | TexImageSource | ImageData | | Float32List | array | | Int32List | array | @@ -81,7 +81,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | WebGLShader | | WebGLTexture | | WebGLUniformLocation | -| [WebGLActiveInfo](#webglactiveinfo) | +| [WebGLActiveInfo](#webglactiveinfo) | | [WebGLShaderPrecisionFormat](#webglshaderprecisionformat) | | [WebGLRenderingContextBase](#webglrenderingcontextbase) | | [WebGLRenderingContextOverloads](#webglrenderingcontextoverloads) | @@ -92,39 +92,39 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); WebGLContextAttributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| alpha | boolean | No| -| depth | boolean | No| -| stencil | boolean | No| -| antialias | boolean | No| -| premultipliedAlpha | boolean | No| -| preserveDrawingBuffer | boolean | No| -| powerPreference | WebGLPowerPreference | No| -| failIfMajorPerformanceCaveat | boolean | No| -| desynchronized | boolean | No| +| alpha | boolean | No| +| depth | boolean | No| +| stencil | boolean | No| +| antialias | boolean | No| +| premultipliedAlpha | boolean | No| +| preserveDrawingBuffer | boolean | No| +| powerPreference | WebGLPowerPreference | No| +| failIfMajorPerformanceCaveat | boolean | No| +| desynchronized | boolean | No| ## WebGLActiveInfo WebGLActiveInfo -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| size | GLint | Yes| -| type | GLenum | Yes| -| name | string | Yes| +| size | GLint | Yes| +| type | GLenum | Yes| +| name | string | Yes| ## WebGLShaderPrecisionFormat WebGLShaderPrecisionFormat -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| rangeMin | GLint | Yes| -| rangeMax | GLint | Yes| -| precision | GLint | Yes| +| rangeMin | GLint | Yes| +| rangeMax | GLint | Yes| +| precision | GLint | Yes| ## WebGLRenderingContextBase @@ -134,455 +134,455 @@ WebGLRenderingContextBase ### Attributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| DEPTH_BUFFER_BIT | GLenum | Yes| -| STENCIL_BUFFER_BIT | GLenum | Yes| -| COLOR_BUFFER_BIT | GLenum | Yes| -| POINTS | GLenum | Yes| -| LINES | GLenum | Yes| -| LINE_LOOP | GLenum | Yes| -| LINE_STRIP | GLenum | Yes| -| TRIANGLES | GLenum | Yes| -| TRIANGLE_STRIP | GLenum | Yes| -| TRIANGLE_FAN | GLenum | Yes| -| ZERO | GLenum | Yes| -| ONE | GLenum | Yes| -| SRC_COLOR | GLenum | Yes| -| ONE_MINUS_SRC_COLOR | GLenum | Yes| -| SRC_ALPHA | GLenum | Yes| -| ONE_MINUS_SRC_ALPHA | GLenum | Yes| -| DST_ALPHA | GLenum | Yes| -| ONE_MINUS_DST_ALPHA | GLenum | Yes| -| DST_COLOR | GLenum | Yes| -| ONE_MINUS_DST_COLOR | GLenum | Yes| -| SRC_ALPHA_SATURATE | GLenum | Yes| -| FUNC_ADD | GLenum | Yes| -| BLEND_EQUATION | GLenum | Yes| -| BLEND_EQUATION_RGB | GLenum | Yes| -| BLEND_EQUATION_ALPHA | GLenum | Yes| -| FUNC_SUBTRACT | GLenum | Yes| -| FUNC_REVERSE_SUBTRACT | GLenum | Yes| -| BLEND_DST_RGB | GLenum | Yes| -| BLEND_SRC_RGB | GLenum | Yes| -| BLEND_DST_ALPHA | GLenum | Yes| -| BLEND_SRC_ALPHA | GLenum | Yes| -| CONSTANT_COLOR | GLenum | Yes| -| ONE_MINUS_CONSTANT_COLOR | GLenum | Yes| -| CONSTANT_ALPHA | GLenum | Yes| -| ONE_MINUS_CONSTANT_ALPHA | GLenum | Yes| -| BLEND_COLOR | GLenum | Yes| -| ARRAY_BUFFER | GLenum | Yes| -| ELEMENT_ARRAY_BUFFER | GLenum | Yes| -| ARRAY_BUFFER_BINDING | GLenum | Yes| -| ELEMENT_ARRAY_BUFFER_BINDING | GLenum | Yes| -| STREAM_DRAW | GLenum | Yes| -| STATIC_DRAW | GLenum | Yes| -| DYNAMIC_DRAW | GLenum | Yes| -| BUFFER_SIZE | GLenum | Yes| -| BUFFER_USAGE | GLenum | Yes| -| CURRENT_VERTEX_ATTRIB | GLenum | Yes| -| FRONT | GLenum | Yes| -| BACK | GLenum | Yes| -| FRONT_AND_BACK | GLenum | Yes| -| CULL_FACE | GLenum | Yes| -| BLEND | GLenum | Yes| -| DITHER | GLenum | Yes| -| STENCIL_TEST | GLenum | Yes| -| DEPTH_TEST | GLenum | Yes| -| SCISSOR_TEST | GLenum | Yes| -| POLYGON_OFFSET_FILL | GLenum | Yes| -| SAMPLE_ALPHA_TO_COVERAGE | GLenum | Yes| -| SAMPLE_COVERAGE | GLenum | Yes| -| NO_ERROR | GLenum | Yes| -| INVALID_ENUM | GLenum | Yes| -| INVALID_VALUE | GLenum | Yes| -| INVALID_OPERATION | GLenum | Yes| -| OUT_OF_MEMORY | GLenum | Yes| -| CW | GLenum | Yes| -| CCW | GLenum | Yes| -| LINE_WIDTH | GLenum | Yes| -| ALIASED_POINT_SIZE_RANGE | GLenum | Yes| -| ALIASED_LINE_WIDTH_RANGE | GLenum | Yes| -| CULL_FACE_MODE | GLenum | Yes| -| FRONT_FACE | GLenum | Yes| -| DEPTH_RANGE | GLenum | Yes| -| DEPTH_WRITEMASK | GLenum | Yes| -| DEPTH_CLEAR_VALUE | GLenum | Yes| -| DEPTH_FUNC | GLenum | Yes| -| STENCIL_CLEAR_VALUE | GLenum | Yes| -| STENCIL_FUNC | GLenum | Yes| -| STENCIL_FAIL | GLenum | Yes| -| STENCIL_PASS_DEPTH_FAIL | GLenum | Yes| -| STENCIL_PASS_DEPTH_PASS | GLenum | Yes| -| STENCIL_REF | GLenum | Yes| -| STENCIL_VALUE_MASK | GLenum | Yes| -| STENCIL_WRITEMASK | GLenum | Yes| -| STENCIL_BACK_FUNC | GLenum | Yes| -| STENCIL_BACK_FAIL | GLenum | Yes| -| STENCIL_BACK_PASS_DEPTH_FAIL | GLenum | Yes| -| STENCIL_BACK_PASS_DEPTH_PASS | GLenum | Yes| -| STENCIL_BACK_REF | GLenum | Yes| -| STENCIL_BACK_VALUE_MASK | GLenum | Yes| -| STENCIL_BACK_WRITEMASK | GLenum | Yes| -| VIEWPORT | GLenum | Yes| -| SCISSOR_BOX | GLenum | Yes| -| COLOR_CLEAR_VALUE | GLenum | Yes| -| COLOR_WRITEMASK | GLenum | Yes| -| UNPACK_ALIGNMENT | GLenum | Yes| -| PACK_ALIGNMENT | GLenum | Yes| -| MAX_TEXTURE_SIZE | GLenum | Yes| -| MAX_VIEWPORT_DIMS | GLenum | Yes| -| SUBPIXEL_BITS | GLenum | Yes| -| RED_BITS | GLenum | Yes| -| GREEN_BITS | GLenum | Yes| -| BLUE_BITS | GLenum | Yes| -| ALPHA_BITS | GLenum | Yes| -| DEPTH_BITS | GLenum | Yes| -| STENCIL_BITS | GLenum | Yes| -| POLYGON_OFFSET_UNITS | GLenum | Yes| -| POLYGON_OFFSET_FACTOR | GLenum | Yes| -| TEXTURE_BINDING_2D | GLenum | Yes| -| SAMPLE_BUFFERS | GLenum | Yes| -| SAMPLES | GLenum | Yes| -| SAMPLE_COVERAGE_VALUE | GLenum | Yes| -| SAMPLE_COVERAGE_INVERT | GLenum | Yes| -| COMPRESSED_TEXTURE_FORMATS | GLenum | Yes| -| DONT_CARE | GLenum | Yes| -| FASTEST | GLenum | Yes| -| NICEST | GLenum | Yes| -| GENERATE_MIPMAP_HINT | GLenum | Yes| -| BYTE | GLenum | Yes| -| UNSIGNED_BYTE | GLenum | Yes| -| SHORT | GLenum | Yes| -| UNSIGNED_SHORT | GLenum | Yes| -| INT | GLenum | Yes| -| UNSIGNED_INT | GLenum | Yes| -| FLOAT | GLenum | Yes| -| DEPTH_COMPONENT | GLenum | Yes| -| ALPHA | GLenum | Yes| -| RGB | GLenum | Yes| -| RGBA | GLenum | Yes| -| LUMINANCE | GLenum | Yes| -| LUMINANCE_ALPHA | GLenum | Yes| -| UNSIGNED_SHORT_4_4_4_4 | GLenum | Yes| -| UNSIGNED_SHORT_5_5_5_1 | GLenum | Yes| -| UNSIGNED_SHORT_5_6_5 | GLenum | Yes| -| FRAGMENT_SHADER | GLenum | Yes| -| VERTEX_SHADER | GLenum | Yes| -| MAX_VERTEX_ATTRIBS | GLenum | Yes| -| MAX_VERTEX_UNIFORM_VECTORS | GLenum | Yes| -| MAX_VARYING_VECTORS | GLenum | Yes| -| MAX_COMBINED_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_VERTEX_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_VECTORS | GLenum | Yes| -| SHADER_TYPE | GLenum | Yes| -| DELETE_STATUS | GLenum | Yes| -| LINK_STATUS | GLenum | Yes| -| VALIDATE_STATUS | GLenum | Yes| -| ATTACHED_SHADERS | GLenum | Yes| -| ACTIVE_UNIFORMS | GLenum | Yes| -| ACTIVE_ATTRIBUTES | GLenum | Yes| -| SHADING_LANGUAGE_VERSION | GLenum | Yes| -| CURRENT_PROGRAM | GLenum | Yes| -| NEVER | GLenum | Yes| -| LESS | GLenum | Yes| -| EQUAL | GLenum | Yes| -| LEQUAL | GLenum | Yes| -| GREATER | GLenum | Yes| -| NOTEQUAL | GLenum | Yes| -| GEQUAL | GLenum | Yes| -| ALWAYS | GLenum | Yes| -| KEEP | GLenum | Yes| -| REPLACE | GLenum | Yes| -| INCR | GLenum | Yes| -| DECR | GLenum | Yes| -| INVERT | GLenum | Yes| -| INCR_WRAP | GLenum | Yes| -| DECR_WRAP | GLenum | Yes| -| VENDOR | GLenum | Yes| -| RENDERER | GLenum | Yes| -| VERSION | GLenum | Yes| -| NEAREST | GLenum | Yes| -| LINEAR | GLenum | Yes| -| NEAREST_MIPMAP_NEAREST | GLenum | Yes| -| LINEAR_MIPMAP_NEAREST | GLenum | Yes| -| NEAREST_MIPMAP_LINEAR | GLenum | Yes| -| LINEAR_MIPMAP_LINEAR | GLenum | Yes| -| TEXTURE_MIN_FILTER | GLenum | Yes| -| TEXTURE_WRAP_S | GLenum | Yes| -| TEXTURE_WRAP_T | GLenum | Yes| -| TEXTURE_2D | GLenum | Yes| -| TEXTURE | GLenum | Yes| -| TEXTURE_CUBE_MAP | GLenum | Yes| -| TEXTURE_BINDING_CUBE_MAP | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_X | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_X | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_Y | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_Y | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_Z | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_Z | GLenum | Yes| -| MAX_CUBE_MAP_TEXTURE_SIZE | GLenum | Yes| -| TEXTURE0 | GLenum | Yes| -| TEXTURE1 | GLenum | Yes| -| TEXTURE2 | GLenum | Yes| -| TEXTURE3 | GLenum | Yes| -| TEXTURE4 | GLenum | Yes| -| TEXTURE5 | GLenum | Yes| -| TEXTURE6 | GLenum | Yes| -| TEXTURE7 | GLenum | Yes| -| TEXTURE8 | GLenum | Yes| -| TEXTURE9 | GLenum | Yes| -| TEXTURE10 | GLenum | Yes| -| TEXTURE11 | GLenum | Yes| -| TEXTURE12 | GLenum | Yes| -| TEXTURE13 | GLenum | Yes| -| TEXTURE14 | GLenum | Yes| -| TEXTURE15 | GLenum | Yes| -| TEXTURE16 | GLenum | Yes| -| TEXTURE17 | GLenum | Yes| -| TEXTURE18 | GLenum | Yes| -| TEXTURE19 | GLenum | Yes| -| TEXTURE20 | GLenum | Yes| -| TEXTURE21 | GLenum | Yes| -| TEXTURE22 | GLenum | Yes| -| TEXTURE23 | GLenum | Yes| -| TEXTURE24 | GLenum | Yes| -| TEXTURE25 | GLenum | Yes| -| TEXTURE26 | GLenum | Yes| -| TEXTURE27 | GLenum | Yes| -| TEXTURE28 | GLenum | Yes| -| TEXTURE29 | GLenum | Yes| -| TEXTURE30 | GLenum | Yes| -| TEXTURE31 | GLenum | Yes| -| ACTIVE_TEXTURE | GLenum | Yes| -| REPEAT | GLenum | Yes| -| CLAMP_TO_EDGE | GLenum | Yes| -| MIRRORED_REPEAT | GLenum | Yes| -| FLOAT_VEC2 | GLenum | Yes| -| FLOAT_VEC3 | GLenum | Yes| -| FLOAT_VEC4 | GLenum | Yes| -| INT_VEC2 | GLenum | Yes| -| INT_VEC3 | GLenum | Yes| -| INT_VEC4 | GLenum | Yes| -| BOOL | GLenum | Yes| -| BOOL_VEC2 | GLenum | Yes| -| BOOL_VEC3 | GLenum | Yes| -| BOOL_VEC4 | GLenum | Yes| -| FLOAT_MAT2 | GLenum | Yes| -| FLOAT_MAT3 | GLenum | Yes| -| FLOAT_MAT4 | GLenum | Yes| -| SAMPLER_2D | GLenum | Yes| -| SAMPLER_CUBE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_ENABLED | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_SIZE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_STRIDE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_TYPE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_NORMALIZED | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_POINTER | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_BUFFER_BINDING | GLenum | Yes| -| IMPLEMENTATION_COLOR_READ_TYPE | GLenum | Yes| -| IMPLEMENTATION_COLOR_READ_FORMAT | GLenum | Yes| -| COMPILE_STATUS | GLenum | Yes| -| LOW_FLOAT | GLenum | Yes| -| MEDIUM_FLOAT | GLenum | Yes| -| HIGH_FLOAT | GLenum | Yes| -| LOW_INT | GLenum | Yes| -| MEDIUM_INT | GLenum | Yes| -| HIGH_INT | GLenum | Yes| -| FRAMEBUFFER | GLenum | Yes| -| RENDERBUFFER | GLenum | Yes| -| RGBA4 | GLenum | Yes| -| RGB5_A1 | GLenum | Yes| -| RGB565 | GLenum | Yes| -| DEPTH_COMPONENT16 | GLenum | Yes| -| STENCIL_INDEX8 | GLenum | Yes| -| DEPTH_STENCIL | GLenum | Yes| -| RENDERBUFFER_WIDTH | GLenum | Yes| -| RENDERBUFFER_HEIGHT | GLenum | Yes| -| RENDERBUFFER_INTERNAL_FORMAT | GLenum | Yes| -| RENDERBUFFER_RED_SIZE | GLenum | Yes| -| RENDERBUFFER_GREEN_SIZE | GLenum | Yes| -| RENDERBUFFER_BLUE_SIZE | GLenum | Yes| -| RENDERBUFFER_ALPHA_SIZE | GLenum | Yes| -| RENDERBUFFER_DEPTH_SIZE | GLenum | Yes| -| RENDERBUFFER_STENCIL_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE | GLenum | Yes| -| COLOR_ATTACHMENT0 | GLenum | Yes| -| DEPTH_ATTACHMENT | GLenum | Yes| -| STENCIL_ATTACHMENT | GLenum | Yes| -| DEPTH_STENCIL_ATTACHMENT | GLenum | Yes| -| NONE | GLenum | Yes| -| FRAMEBUFFER_COMPLETE | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_ATTACHMENT | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_DIMENSIONS | GLenum | Yes| -| FRAMEBUFFER_UNSUPPORTED | GLenum | Yes| -| FRAMEBUFFER_BINDING | GLenum | Yes| -| RENDERBUFFER_BINDING | GLenum | Yes| -| MAX_RENDERBUFFER_SIZE | GLenum | Yes| -| INVALID_FRAMEBUFFER_OPERATION | GLenum | Yes| -| UNPACK_FLIP_Y_WEBGL | GLenum | Yes| -| UNPACK_PREMULTIPLY_ALPHA_WEBGL | GLenum | Yes| -| CONTEXT_LOST_WEBGL | GLenum | Yes| -| UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| -| BROWSER_DEFAULT_WEBGL | GLenum | Yes| -| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| -| drawingBufferWidth | GLsizei | Yes| -| drawingBufferHeight | GLsizei | Yes| +| DEPTH_BUFFER_BIT | GLenum | Yes| +| STENCIL_BUFFER_BIT | GLenum | Yes| +| COLOR_BUFFER_BIT | GLenum | Yes| +| POINTS | GLenum | Yes| +| LINES | GLenum | Yes| +| LINE_LOOP | GLenum | Yes| +| LINE_STRIP | GLenum | Yes| +| TRIANGLES | GLenum | Yes| +| TRIANGLE_STRIP | GLenum | Yes| +| TRIANGLE_FAN | GLenum | Yes| +| ZERO | GLenum | Yes| +| ONE | GLenum | Yes| +| SRC_COLOR | GLenum | Yes| +| ONE_MINUS_SRC_COLOR | GLenum | Yes| +| SRC_ALPHA | GLenum | Yes| +| ONE_MINUS_SRC_ALPHA | GLenum | Yes| +| DST_ALPHA | GLenum | Yes| +| ONE_MINUS_DST_ALPHA | GLenum | Yes| +| DST_COLOR | GLenum | Yes| +| ONE_MINUS_DST_COLOR | GLenum | Yes| +| SRC_ALPHA_SATURATE | GLenum | Yes| +| FUNC_ADD | GLenum | Yes| +| BLEND_EQUATION | GLenum | Yes| +| BLEND_EQUATION_RGB | GLenum | Yes| +| BLEND_EQUATION_ALPHA | GLenum | Yes| +| FUNC_SUBTRACT | GLenum | Yes| +| FUNC_REVERSE_SUBTRACT | GLenum | Yes| +| BLEND_DST_RGB | GLenum | Yes| +| BLEND_SRC_RGB | GLenum | Yes| +| BLEND_DST_ALPHA | GLenum | Yes| +| BLEND_SRC_ALPHA | GLenum | Yes| +| CONSTANT_COLOR | GLenum | Yes| +| ONE_MINUS_CONSTANT_COLOR | GLenum | Yes| +| CONSTANT_ALPHA | GLenum | Yes| +| ONE_MINUS_CONSTANT_ALPHA | GLenum | Yes| +| BLEND_COLOR | GLenum | Yes| +| ARRAY_BUFFER | GLenum | Yes| +| ELEMENT_ARRAY_BUFFER | GLenum | Yes| +| ARRAY_BUFFER_BINDING | GLenum | Yes| +| ELEMENT_ARRAY_BUFFER_BINDING | GLenum | Yes| +| STREAM_DRAW | GLenum | Yes| +| STATIC_DRAW | GLenum | Yes| +| DYNAMIC_DRAW | GLenum | Yes| +| BUFFER_SIZE | GLenum | Yes| +| BUFFER_USAGE | GLenum | Yes| +| CURRENT_VERTEX_ATTRIB | GLenum | Yes| +| FRONT | GLenum | Yes| +| BACK | GLenum | Yes| +| FRONT_AND_BACK | GLenum | Yes| +| CULL_FACE | GLenum | Yes| +| BLEND | GLenum | Yes| +| DITHER | GLenum | Yes| +| STENCIL_TEST | GLenum | Yes| +| DEPTH_TEST | GLenum | Yes| +| SCISSOR_TEST | GLenum | Yes| +| POLYGON_OFFSET_FILL | GLenum | Yes| +| SAMPLE_ALPHA_TO_COVERAGE | GLenum | Yes| +| SAMPLE_COVERAGE | GLenum | Yes| +| NO_ERROR | GLenum | Yes| +| INVALID_ENUM | GLenum | Yes| +| INVALID_VALUE | GLenum | Yes| +| INVALID_OPERATION | GLenum | Yes| +| OUT_OF_MEMORY | GLenum | Yes| +| CW | GLenum | Yes| +| CCW | GLenum | Yes| +| LINE_WIDTH | GLenum | Yes| +| ALIASED_POINT_SIZE_RANGE | GLenum | Yes| +| ALIASED_LINE_WIDTH_RANGE | GLenum | Yes| +| CULL_FACE_MODE | GLenum | Yes| +| FRONT_FACE | GLenum | Yes| +| DEPTH_RANGE | GLenum | Yes| +| DEPTH_WRITEMASK | GLenum | Yes| +| DEPTH_CLEAR_VALUE | GLenum | Yes| +| DEPTH_FUNC | GLenum | Yes| +| STENCIL_CLEAR_VALUE | GLenum | Yes| +| STENCIL_FUNC | GLenum | Yes| +| STENCIL_FAIL | GLenum | Yes| +| STENCIL_PASS_DEPTH_FAIL | GLenum | Yes| +| STENCIL_PASS_DEPTH_PASS | GLenum | Yes| +| STENCIL_REF | GLenum | Yes| +| STENCIL_VALUE_MASK | GLenum | Yes| +| STENCIL_WRITEMASK | GLenum | Yes| +| STENCIL_BACK_FUNC | GLenum | Yes| +| STENCIL_BACK_FAIL | GLenum | Yes| +| STENCIL_BACK_PASS_DEPTH_FAIL | GLenum | Yes| +| STENCIL_BACK_PASS_DEPTH_PASS | GLenum | Yes| +| STENCIL_BACK_REF | GLenum | Yes| +| STENCIL_BACK_VALUE_MASK | GLenum | Yes| +| STENCIL_BACK_WRITEMASK | GLenum | Yes| +| VIEWPORT | GLenum | Yes| +| SCISSOR_BOX | GLenum | Yes| +| COLOR_CLEAR_VALUE | GLenum | Yes| +| COLOR_WRITEMASK | GLenum | Yes| +| UNPACK_ALIGNMENT | GLenum | Yes| +| PACK_ALIGNMENT | GLenum | Yes| +| MAX_TEXTURE_SIZE | GLenum | Yes| +| MAX_VIEWPORT_DIMS | GLenum | Yes| +| SUBPIXEL_BITS | GLenum | Yes| +| RED_BITS | GLenum | Yes| +| GREEN_BITS | GLenum | Yes| +| BLUE_BITS | GLenum | Yes| +| ALPHA_BITS | GLenum | Yes| +| DEPTH_BITS | GLenum | Yes| +| STENCIL_BITS | GLenum | Yes| +| POLYGON_OFFSET_UNITS | GLenum | Yes| +| POLYGON_OFFSET_FACTOR | GLenum | Yes| +| TEXTURE_BINDING_2D | GLenum | Yes| +| SAMPLE_BUFFERS | GLenum | Yes| +| SAMPLES | GLenum | Yes| +| SAMPLE_COVERAGE_VALUE | GLenum | Yes| +| SAMPLE_COVERAGE_INVERT | GLenum | Yes| +| COMPRESSED_TEXTURE_FORMATS | GLenum | Yes| +| DONT_CARE | GLenum | Yes| +| FASTEST | GLenum | Yes| +| NICEST | GLenum | Yes| +| GENERATE_MIPMAP_HINT | GLenum | Yes| +| BYTE | GLenum | Yes| +| UNSIGNED_BYTE | GLenum | Yes| +| SHORT | GLenum | Yes| +| UNSIGNED_SHORT | GLenum | Yes| +| INT | GLenum | Yes| +| UNSIGNED_INT | GLenum | Yes| +| FLOAT | GLenum | Yes| +| DEPTH_COMPONENT | GLenum | Yes| +| ALPHA | GLenum | Yes| +| RGB | GLenum | Yes| +| RGBA | GLenum | Yes| +| LUMINANCE | GLenum | Yes| +| LUMINANCE_ALPHA | GLenum | Yes| +| UNSIGNED_SHORT_4_4_4_4 | GLenum | Yes| +| UNSIGNED_SHORT_5_5_5_1 | GLenum | Yes| +| UNSIGNED_SHORT_5_6_5 | GLenum | Yes| +| FRAGMENT_SHADER | GLenum | Yes| +| VERTEX_SHADER | GLenum | Yes| +| MAX_VERTEX_ATTRIBS | GLenum | Yes| +| MAX_VERTEX_UNIFORM_VECTORS | GLenum | Yes| +| MAX_VARYING_VECTORS | GLenum | Yes| +| MAX_COMBINED_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_VERTEX_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_VECTORS | GLenum | Yes| +| SHADER_TYPE | GLenum | Yes| +| DELETE_STATUS | GLenum | Yes| +| LINK_STATUS | GLenum | Yes| +| VALIDATE_STATUS | GLenum | Yes| +| ATTACHED_SHADERS | GLenum | Yes| +| ACTIVE_UNIFORMS | GLenum | Yes| +| ACTIVE_ATTRIBUTES | GLenum | Yes| +| SHADING_LANGUAGE_VERSION | GLenum | Yes| +| CURRENT_PROGRAM | GLenum | Yes| +| NEVER | GLenum | Yes| +| LESS | GLenum | Yes| +| EQUAL | GLenum | Yes| +| LEQUAL | GLenum | Yes| +| GREATER | GLenum | Yes| +| NOTEQUAL | GLenum | Yes| +| GEQUAL | GLenum | Yes| +| ALWAYS | GLenum | Yes| +| KEEP | GLenum | Yes| +| REPLACE | GLenum | Yes| +| INCR | GLenum | Yes| +| DECR | GLenum | Yes| +| INVERT | GLenum | Yes| +| INCR_WRAP | GLenum | Yes| +| DECR_WRAP | GLenum | Yes| +| VENDOR | GLenum | Yes| +| RENDERER | GLenum | Yes| +| VERSION | GLenum | Yes| +| NEAREST | GLenum | Yes| +| LINEAR | GLenum | Yes| +| NEAREST_MIPMAP_NEAREST | GLenum | Yes| +| LINEAR_MIPMAP_NEAREST | GLenum | Yes| +| NEAREST_MIPMAP_LINEAR | GLenum | Yes| +| LINEAR_MIPMAP_LINEAR | GLenum | Yes| +| TEXTURE_MIN_FILTER | GLenum | Yes| +| TEXTURE_WRAP_S | GLenum | Yes| +| TEXTURE_WRAP_T | GLenum | Yes| +| TEXTURE_2D | GLenum | Yes| +| TEXTURE | GLenum | Yes| +| TEXTURE_CUBE_MAP | GLenum | Yes| +| TEXTURE_BINDING_CUBE_MAP | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_X | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_X | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_Y | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_Y | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_Z | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_Z | GLenum | Yes| +| MAX_CUBE_MAP_TEXTURE_SIZE | GLenum | Yes| +| TEXTURE0 | GLenum | Yes| +| TEXTURE1 | GLenum | Yes| +| TEXTURE2 | GLenum | Yes| +| TEXTURE3 | GLenum | Yes| +| TEXTURE4 | GLenum | Yes| +| TEXTURE5 | GLenum | Yes| +| TEXTURE6 | GLenum | Yes| +| TEXTURE7 | GLenum | Yes| +| TEXTURE8 | GLenum | Yes| +| TEXTURE9 | GLenum | Yes| +| TEXTURE10 | GLenum | Yes| +| TEXTURE11 | GLenum | Yes| +| TEXTURE12 | GLenum | Yes| +| TEXTURE13 | GLenum | Yes| +| TEXTURE14 | GLenum | Yes| +| TEXTURE15 | GLenum | Yes| +| TEXTURE16 | GLenum | Yes| +| TEXTURE17 | GLenum | Yes| +| TEXTURE18 | GLenum | Yes| +| TEXTURE19 | GLenum | Yes| +| TEXTURE20 | GLenum | Yes| +| TEXTURE21 | GLenum | Yes| +| TEXTURE22 | GLenum | Yes| +| TEXTURE23 | GLenum | Yes| +| TEXTURE24 | GLenum | Yes| +| TEXTURE25 | GLenum | Yes| +| TEXTURE26 | GLenum | Yes| +| TEXTURE27 | GLenum | Yes| +| TEXTURE28 | GLenum | Yes| +| TEXTURE29 | GLenum | Yes| +| TEXTURE30 | GLenum | Yes| +| TEXTURE31 | GLenum | Yes| +| ACTIVE_TEXTURE | GLenum | Yes| +| REPEAT | GLenum | Yes| +| CLAMP_TO_EDGE | GLenum | Yes| +| MIRRORED_REPEAT | GLenum | Yes| +| FLOAT_VEC2 | GLenum | Yes| +| FLOAT_VEC3 | GLenum | Yes| +| FLOAT_VEC4 | GLenum | Yes| +| INT_VEC2 | GLenum | Yes| +| INT_VEC3 | GLenum | Yes| +| INT_VEC4 | GLenum | Yes| +| BOOL | GLenum | Yes| +| BOOL_VEC2 | GLenum | Yes| +| BOOL_VEC3 | GLenum | Yes| +| BOOL_VEC4 | GLenum | Yes| +| FLOAT_MAT2 | GLenum | Yes| +| FLOAT_MAT3 | GLenum | Yes| +| FLOAT_MAT4 | GLenum | Yes| +| SAMPLER_2D | GLenum | Yes| +| SAMPLER_CUBE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_ENABLED | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_SIZE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_STRIDE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_TYPE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_NORMALIZED | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_POINTER | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_BUFFER_BINDING | GLenum | Yes| +| IMPLEMENTATION_COLOR_READ_TYPE | GLenum | Yes| +| IMPLEMENTATION_COLOR_READ_FORMAT | GLenum | Yes| +| COMPILE_STATUS | GLenum | Yes| +| LOW_FLOAT | GLenum | Yes| +| MEDIUM_FLOAT | GLenum | Yes| +| HIGH_FLOAT | GLenum | Yes| +| LOW_INT | GLenum | Yes| +| MEDIUM_INT | GLenum | Yes| +| HIGH_INT | GLenum | Yes| +| FRAMEBUFFER | GLenum | Yes| +| RENDERBUFFER | GLenum | Yes| +| RGBA4 | GLenum | Yes| +| RGB5_A1 | GLenum | Yes| +| RGB565 | GLenum | Yes| +| DEPTH_COMPONENT16 | GLenum | Yes| +| STENCIL_INDEX8 | GLenum | Yes| +| DEPTH_STENCIL | GLenum | Yes| +| RENDERBUFFER_WIDTH | GLenum | Yes| +| RENDERBUFFER_HEIGHT | GLenum | Yes| +| RENDERBUFFER_INTERNAL_FORMAT | GLenum | Yes| +| RENDERBUFFER_RED_SIZE | GLenum | Yes| +| RENDERBUFFER_GREEN_SIZE | GLenum | Yes| +| RENDERBUFFER_BLUE_SIZE | GLenum | Yes| +| RENDERBUFFER_ALPHA_SIZE | GLenum | Yes| +| RENDERBUFFER_DEPTH_SIZE | GLenum | Yes| +| RENDERBUFFER_STENCIL_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE | GLenum | Yes| +| COLOR_ATTACHMENT0 | GLenum | Yes| +| DEPTH_ATTACHMENT | GLenum | Yes| +| STENCIL_ATTACHMENT | GLenum | Yes| +| DEPTH_STENCIL_ATTACHMENT | GLenum | Yes| +| NONE | GLenum | Yes| +| FRAMEBUFFER_COMPLETE | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_ATTACHMENT | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_DIMENSIONS | GLenum | Yes| +| FRAMEBUFFER_UNSUPPORTED | GLenum | Yes| +| FRAMEBUFFER_BINDING | GLenum | Yes| +| RENDERBUFFER_BINDING | GLenum | Yes| +| MAX_RENDERBUFFER_SIZE | GLenum | Yes| +| INVALID_FRAMEBUFFER_OPERATION | GLenum | Yes| +| UNPACK_FLIP_Y_WEBGL | GLenum | Yes| +| UNPACK_PREMULTIPLY_ALPHA_WEBGL | GLenum | Yes| +| CONTEXT_LOST_WEBGL | GLenum | Yes| +| UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| +| BROWSER_DEFAULT_WEBGL | GLenum | Yes| +| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| +| drawingBufferWidth | GLsizei | Yes| +| drawingBufferHeight | GLsizei | Yes| ### Methods -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| getContextAttributes() | WebGLContextAttributes \| null | -| isContextLost() | boolean | -| getSupportedExtensions() | string[] \| null | -| getExtension(name: string) | any | -| activeTexture(texture: GLenum) | void | -| attachShader(program: WebGLProgram, shader: WebGLShader) | void | -| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | -| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | -| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | -| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | -| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| blendEquation(mode: GLenum) | void | -| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | -| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | -| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | -| checkFramebufferStatus(target: GLenum) | GLenum | -| clear(mask: GLbitfield) | void | -| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| clearDepth(depth: GLclampf) | void | -| clearStencil(s: GLint) | void | -| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | -| compileShader(shader: WebGLShader) | void | -| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | -| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| createBuffer() | WebGLBuffer \| null | -| createFramebuffer() | WebGLFramebuffer \| null | -| createProgram() | WebGLProgram \| null | -| createRenderbuffer() | WebGLRenderbuffer \| null | -| createShader(type: GLenum) | WebGLShader \| null | -| createTexture() | WebGLTexture \| null | -| cullFace(mode: GLenum) | void | -| deleteBuffer(buffer: WebGLBuffer \| null) | void | -| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | -| deleteProgram(program: WebGLProgram \| null) | void | -| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | -| deleteShader(shader: WebGLShader \| null) | void | -| deleteTexture(texture: WebGLTexture \| null) | void | -| depthFunc(func: GLenum) | void | -| depthMask(flag: GLboolean) | void | -| depthRange(zNear: GLclampf, zFar: GLclampf) | void | -| detachShader(program: WebGLProgram, shader: WebGLShader) | void | -| disable(cap: GLenum) | void | -| disableVertexAttribArray(index: GLuint) | void | -| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | -| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| enable(cap: GLenum) | void | -| enableVertexAttribArray(index: GLuint) | void | -| finish() | void | -| flush() | void | -| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | -| frontFace(mode: GLenum) | void | -| generateMipmap(target: GLenum) | void | -| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | -| getAttribLocation(program: WebGLProgram, name: string) | GLint | -| getBufferParameter(target: GLenum, pname: GLenum) | any | -| getParameter(pname: GLenum) | any | -| getError() | GLenum | -| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | -| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | -| getProgramInfoLog(program: WebGLProgram) | string \| null | -| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | -| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | -| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | -| getShaderInfoLog(shader: WebGLShader) | string \| null | -| getShaderSource(shader: WebGLShader) | string \| null | -| getTexParameter(target: GLenum, pname: GLenum) | any | -| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | -| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | -| getVertexAttrib(index: GLuint, pname: GLenum) | any | -| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | -| hint(target: GLenum, mode: GLenum) | void | -| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | -| isEnabled(cap: GLenum) | GLboolean | -| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | -| isProgram(program: WebGLProgram \| null) | GLboolean | -| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | -| isShader(shader: WebGLShader \| null) | GLboolean | -| isTexture(texture: WebGLTexture \| null) | GLboolean | -| lineWidth(width: GLfloat) | void | -| linkProgram(program: WebGLProgram) | void | -| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | -| polygonOffset(factor: GLfloat, units: GLfloat) | void | -| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| sampleCoverage(value: GLclampf, invert: GLboolean) | void | -| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| shaderSource(shader: WebGLShader, source: string) | void | -| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilMask(mask: GLuint) | void | -| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | -| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | -| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | -| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | -| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | -| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | -| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | -| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | -| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| useProgram(program: WebGLProgram \| null) | void | -| validateProgram(program: WebGLProgram) | void | -| vertexAttrib1f(index: GLuint, x: GLfloat) | void | -| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | -| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| vertexAttrib1fv(index: GLuint, values: Float32List) | void | -| vertexAttrib2fv(index: GLuint, values: Float32List) | void | -| vertexAttrib3fv(index: GLuint, values: Float32List) | void | -| vertexAttrib4fv(index: GLuint, values: Float32List) | void | -| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | -| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| getContextAttributes() | WebGLContextAttributes \| null | +| isContextLost() | boolean | +| getSupportedExtensions() | string[] \| null | +| getExtension(name: string) | any | +| activeTexture(texture: GLenum) | void | +| attachShader(program: WebGLProgram, shader: WebGLShader) | void | +| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | +| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | +| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | +| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | +| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| blendEquation(mode: GLenum) | void | +| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | +| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | +| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | +| checkFramebufferStatus(target: GLenum) | GLenum | +| clear(mask: GLbitfield) | void | +| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| clearDepth(depth: GLclampf) | void | +| clearStencil(s: GLint) | void | +| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | +| compileShader(shader: WebGLShader) | void | +| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | +| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| createBuffer() | WebGLBuffer \| null | +| createFramebuffer() | WebGLFramebuffer \| null | +| createProgram() | WebGLProgram \| null | +| createRenderbuffer() | WebGLRenderbuffer \| null | +| createShader(type: GLenum) | WebGLShader \| null | +| createTexture() | WebGLTexture \| null | +| cullFace(mode: GLenum) | void | +| deleteBuffer(buffer: WebGLBuffer \| null) | void | +| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | +| deleteProgram(program: WebGLProgram \| null) | void | +| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | +| deleteShader(shader: WebGLShader \| null) | void | +| deleteTexture(texture: WebGLTexture \| null) | void | +| depthFunc(func: GLenum) | void | +| depthMask(flag: GLboolean) | void | +| depthRange(zNear: GLclampf, zFar: GLclampf) | void | +| detachShader(program: WebGLProgram, shader: WebGLShader) | void | +| disable(cap: GLenum) | void | +| disableVertexAttribArray(index: GLuint) | void | +| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | +| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| enable(cap: GLenum) | void | +| enableVertexAttribArray(index: GLuint) | void | +| finish() | void | +| flush() | void | +| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | +| frontFace(mode: GLenum) | void | +| generateMipmap(target: GLenum) | void | +| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | +| getAttribLocation(program: WebGLProgram, name: string) | GLint | +| getBufferParameter(target: GLenum, pname: GLenum) | any | +| getParameter(pname: GLenum) | any | +| getError() | GLenum | +| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | +| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | +| getProgramInfoLog(program: WebGLProgram) | string \| null | +| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | +| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | +| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | +| getShaderInfoLog(shader: WebGLShader) | string \| null | +| getShaderSource(shader: WebGLShader) | string \| null | +| getTexParameter(target: GLenum, pname: GLenum) | any | +| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | +| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | +| getVertexAttrib(index: GLuint, pname: GLenum) | any | +| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | +| hint(target: GLenum, mode: GLenum) | void | +| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | +| isEnabled(cap: GLenum) | GLboolean | +| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | +| isProgram(program: WebGLProgram \| null) | GLboolean | +| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | +| isShader(shader: WebGLShader \| null) | GLboolean | +| isTexture(texture: WebGLTexture \| null) | GLboolean | +| lineWidth(width: GLfloat) | void | +| linkProgram(program: WebGLProgram) | void | +| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | +| polygonOffset(factor: GLfloat, units: GLfloat) | void | +| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| sampleCoverage(value: GLclampf, invert: GLboolean) | void | +| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| shaderSource(shader: WebGLShader, source: string) | void | +| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilMask(mask: GLuint) | void | +| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | +| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | +| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | +| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | +| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | +| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | +| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | +| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | +| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| useProgram(program: WebGLProgram \| null) | void | +| validateProgram(program: WebGLProgram) | void | +| vertexAttrib1f(index: GLuint, x: GLfloat) | void | +| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | +| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| vertexAttrib1fv(index: GLuint, values: Float32List) | void | +| vertexAttrib2fv(index: GLuint, values: Float32List) | void | +| vertexAttrib3fv(index: GLuint, values: Float32List) | void | +| vertexAttrib4fv(index: GLuint, values: Float32List) | void | +| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | +| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | ## WebGLRenderingContextOverloads WebGLRenderingContextOverloads -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index 6fc36366d38b7d65484822911e8acdf926b8e931..dc19039007c1f8207e2dd3ac026c67bdac169d9f 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -75,409 +75,409 @@ WebGL2RenderingContextBase ### Attributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| READ_BUFFER | GLenum | Yes| -| UNPACK_ROW_LENGTH | GLenum | Yes| -| UNPACK_SKIP_ROWS | GLenum | Yes| -| UNPACK_SKIP_PIXELS | GLenum | Yes| -| PACK_ROW_LENGTH | GLenum | Yes| -| PACK_SKIP_ROWS | GLenum | Yes| -| PACK_SKIP_PIXELS | GLenum | Yes| -| COLOR | GLenum | Yes| -| DEPTH | GLenum | Yes| -| STENCIL | GLenum | Yes| -| RED | GLenum | Yes| -| RGB8 | GLenum | Yes| -| RGBA8 | GLenum | Yes| -| RGB10_A2 | GLenum | Yes| -| TEXTURE_BINDING_3D | GLenum | Yes| -| UNPACK_SKIP_IMAGES | GLenum | Yes| -| UNPACK_IMAGE_HEIGHT | GLenum | Yes| -| TEXTURE_3D | GLenum | Yes| -| TEXTURE_WRAP_R | GLenum | Yes| -| MAX_3D_TEXTURE_SIZE | GLenum | Yes| -| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| -| MAX_ELEMENTS_VERTICES | GLenum | Yes| -| MAX_ELEMENTS_INDICES | GLenum | Yes| -| TEXTURE_MIN_LOD | GLenum | Yes| -| TEXTURE_MAX_LOD | GLenum | Yes| -| TEXTURE_BASE_LEVEL | GLenum | Yes| -| TEXTURE_MAX_LEVEL | GLenum | Yes| -| MIN | GLenum | Yes| -| MAX | GLenum | Yes| -| DEPTH_COMPONENT24 | GLenum | Yes| -| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| -| TEXTURE_COMPARE_MODE | GLenum | Yes| -| TEXTURE_COMPARE_FUNC | GLenum | Yes| -| CURRENT_QUERY | GLenum | Yes| -| QUERY_RESULT | GLenum | Yes| -| QUERY_RESULT_AVAILABLE | GLenum | Yes| -| STREAM_READ | GLenum | Yes| -| STREAM_COPY | GLenum | Yes| -| STATIC_READ | GLenum | Yes| -| STATIC_COPY | GLenum | Yes| -| DYNAMIC_READ | GLenum | Yes| -| DYNAMIC_COPY | GLenum | Yes| -| MAX_DRAW_BUFFERS | GLenum | Yes| -| DRAW_BUFFER0 | GLenum | Yes| -| DRAW_BUFFER1 | GLenum | Yes| -| DRAW_BUFFER2 | GLenum | Yes| -| DRAW_BUFFER3 | GLenum | Yes| -| DRAW_BUFFER4 | GLenum | Yes| -| DRAW_BUFFER5 | GLenum | Yes| -| DRAW_BUFFER6 | GLenum | Yes| -| DRAW_BUFFER7 | GLenum | Yes| -| DRAW_BUFFER8 | GLenum | Yes| -| DRAW_BUFFER9 | GLenum | Yes| -| DRAW_BUFFER10 | GLenum | Yes| -| DRAW_BUFFER11 | GLenum | Yes| -| DRAW_BUFFER12 | GLenum | Yes| -| DRAW_BUFFER13 | GLenum | Yes| -| DRAW_BUFFER14 | GLenum | Yes| -| DRAW_BUFFER15 | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| SAMPLER_3D | GLenum | Yes| -| SAMPLER_2D_SHADOW | GLenum | Yes| -| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| -| PIXEL_PACK_BUFFER | GLenum | Yes| -| PIXEL_UNPACK_BUFFER | GLenum | Yes| -| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| -| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| -| FLOAT_MAT2x3 | GLenum | Yes| -| FLOAT_MAT2x4 | GLenum | Yes| -| FLOAT_MAT3x2 | GLenum | Yes| -| FLOAT_MAT3x4 | GLenum | Yes| -| FLOAT_MAT4x2 | GLenum | Yes| -| FLOAT_MAT4x3 | GLenum | Yes| -| SRGB | GLenum | Yes| -| SRGB8 | GLenum | Yes| -| SRGB8_ALPHA8 | GLenum | Yes| -| COMPARE_REF_TO_TEXTURE | GLenum | Yes| -| RGBA32F | GLenum | Yes| -| RGB32F | GLenum | Yes| -| RGBA16F | GLenum | Yes| -| RGB16F | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| -| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| -| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_VARYING_COMPONENTS | GLenum | Yes| -| TEXTURE_2D_ARRAY | GLenum | Yes| -| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| -| R11F_G11F_B10F | GLenum | Yes| -| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| -| RGB9_E5 | GLenum | Yes| -| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| -| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| -| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| -| RASTERIZER_DISCARD | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| -| INTERLEAVED_ATTRIBS | GLenum | Yes| -| SEPARATE_ATTRIBS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| -| RGBA32UI | GLenum | Yes| -| RGB32UI | GLenum | Yes| -| RGBA16UI | GLenum | Yes| -| RGB16UI | GLenum | Yes| -| RGBA8UI | GLenum | Yes| -| RGB8UI | GLenum | Yes| -| RGBA32I | GLenum | Yes| -| RGB32I | GLenum | Yes| -| RGBA16I | GLenum | Yes| -| RGB16I | GLenum | Yes| -| RGBA8I | GLenum | Yes| -| RGB8I | GLenum | Yes| -| RED_INTEGER | GLenum | Yes| -| RGB_INTEGER | GLenum | Yes| -| RGBA_INTEGER | GLenum | Yes| -| SAMPLER_2D_ARRAY | GLenum | Yes| -| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| -| SAMPLER_CUBE_SHADOW | GLenum | Yes| -| UNSIGNED_INT_VEC2 | GLenum | Yes| -| UNSIGNED_INT_VEC3 | GLenum | Yes| -| UNSIGNED_INT_VEC4 | GLenum | Yes| -| INT_SAMPLER_2D | GLenum | Yes| -| INT_SAMPLER_3D | GLenum | Yes| -| INT_SAMPLER_CUBE | GLenum | Yes| -| INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| DEPTH_COMPONENT32F | GLenum | Yes| -| DEPTH32F_STENCIL8 | GLenum | Yes| -| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| -| FRAMEBUFFER_DEFAULT | GLenum | Yes| -| UNSIGNED_INT_24_8 | GLenum | Yes| -| DEPTH24_STENCIL8 | GLenum | Yes| -| UNSIGNED_NORMALIZED | GLenum | Yes| -| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| -| READ_FRAMEBUFFER | GLenum | Yes| -| DRAW_FRAMEBUFFER | GLenum | Yes| -| READ_FRAMEBUFFER_BINDING | GLenum | Yes| -| RENDERBUFFER_SAMPLES | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| -| MAX_COLOR_ATTACHMENTS | GLenum | Yes| -| COLOR_ATTACHMENT1 | GLenum | Yes| -| COLOR_ATTACHMENT2 | GLenum | Yes| -| COLOR_ATTACHMENT3 | GLenum | Yes| -| COLOR_ATTACHMENT4 | GLenum | Yes| -| COLOR_ATTACHMENT5 | GLenum | Yes| -| COLOR_ATTACHMENT6 | GLenum | Yes| -| COLOR_ATTACHMENT7 | GLenum | Yes| -| COLOR_ATTACHMENT8 | GLenum | Yes| -| COLOR_ATTACHMENT9 | GLenum | Yes| -| COLOR_ATTACHMENT10 | GLenum | Yes| -| COLOR_ATTACHMENT11 | GLenum | Yes| -| COLOR_ATTACHMENT12 | GLenum | Yes| -| COLOR_ATTACHMENT13 | GLenum | Yes| -| COLOR_ATTACHMENT14 | GLenum | Yes| -| COLOR_ATTACHMENT15 | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| -| MAX_SAMPLES | GLenum | Yes| -| HALF_FLOAT | GLenum | Yes| -| RG | GLenum | Yes| -| RG_INTEGER | GLenum | Yes| -| R8 | GLenum | Yes| -| RG8 | GLenum | Yes| -| R16F | GLenum | Yes| -| R32F | GLenum | Yes| -| RG16F | GLenum | Yes| -| RG32F | GLenum | Yes| -| R8I | GLenum | Yes| -| R8UI | GLenum | Yes| -| R16I | GLenum | Yes| -| R16UI | GLenum | Yes| -| R32I | GLenum | Yes| -| R32UI | GLenum | Yes| -| RG8I | GLenum | Yes| -| RG8UI | GLenum | Yes| -| RG16I | GLenum | Yes| -| RG16UI | GLenum | Yes| -| RG32I | GLenum | Yes| -| RG32UI | GLenum | Yes| -| VERTEX_ARRAY_BINDING | GLenum | Yes| -| R8_SNORM | GLenum | Yes| -| RG8_SNORM | GLenum | Yes| -| RGB8_SNORM | GLenum | Yes| -| SIGNED_NORMALIZED | GLenum | Yes| -| COPY_READ_BUFFER | GLenum | Yes| -| COPY_WRITE_BUFFER | GLenum | Yes| -| COPY_READ_BUFFER_BINDING | GLenum | Yes| -| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER | GLenum | Yes| -| UNIFORM_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER_START | GLenum | Yes| -| UNIFORM_BUFFER_SIZE | GLenum | Yes| -| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| -| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| -| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| -| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| -| UNIFORM_TYPE | GLenum | Yes| -| UNIFORM_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_INDEX | GLenum | Yes| -| UNIFORM_OFFSET | GLenum | Yes| -| UNIFORM_ARRAY_STRIDE | GLenum | Yes| -| UNIFORM_MATRIX_STRIDE | GLenum | Yes| -| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| -| UNIFORM_BLOCK_BINDING | GLenum | Yes| -| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| -| INVALID_INDEX | GLenum | Yes| -| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| -| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| -| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| -| OBJECT_TYPE | GLenum | Yes| -| SYNC_CONDITION | GLenum | Yes| -| SYNC_STATUS | GLenum | Yes| -| SYNC_FLAGS | GLenum | Yes| -| SYNC_FENCE | GLenum | Yes| -| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| -| UNSIGNALED | GLenum | Yes| -| SIGNALED | GLenum | Yes| -| ALREADY_SIGNALED | GLenum | Yes| -| TIMEOUT_EXPIRED | GLenum | Yes| -| CONDITION_SATISFIED | GLenum | Yes| -| WAIT_FAILED | GLenum | Yes| -| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| -| ANY_SAMPLES_PASSED | GLenum | Yes| -| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| -| SAMPLER_BINDING | GLenum | Yes| -| RGB10_A2UI | GLenum | Yes| -| INT_2_10_10_10_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK | GLenum | Yes| -| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| -| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| -| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| -| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| -| MAX_ELEMENT_INDEX | GLenum | Yes| -| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| -| TIMEOUT_IGNORED | GLint64 | Yes| -| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| +| READ_BUFFER | GLenum | Yes| +| UNPACK_ROW_LENGTH | GLenum | Yes| +| UNPACK_SKIP_ROWS | GLenum | Yes| +| UNPACK_SKIP_PIXELS | GLenum | Yes| +| PACK_ROW_LENGTH | GLenum | Yes| +| PACK_SKIP_ROWS | GLenum | Yes| +| PACK_SKIP_PIXELS | GLenum | Yes| +| COLOR | GLenum | Yes| +| DEPTH | GLenum | Yes| +| STENCIL | GLenum | Yes| +| RED | GLenum | Yes| +| RGB8 | GLenum | Yes| +| RGBA8 | GLenum | Yes| +| RGB10_A2 | GLenum | Yes| +| TEXTURE_BINDING_3D | GLenum | Yes| +| UNPACK_SKIP_IMAGES | GLenum | Yes| +| UNPACK_IMAGE_HEIGHT | GLenum | Yes| +| TEXTURE_3D | GLenum | Yes| +| TEXTURE_WRAP_R | GLenum | Yes| +| MAX_3D_TEXTURE_SIZE | GLenum | Yes| +| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| +| MAX_ELEMENTS_VERTICES | GLenum | Yes| +| MAX_ELEMENTS_INDICES | GLenum | Yes| +| TEXTURE_MIN_LOD | GLenum | Yes| +| TEXTURE_MAX_LOD | GLenum | Yes| +| TEXTURE_BASE_LEVEL | GLenum | Yes| +| TEXTURE_MAX_LEVEL | GLenum | Yes| +| MIN | GLenum | Yes| +| MAX | GLenum | Yes| +| DEPTH_COMPONENT24 | GLenum | Yes| +| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| +| TEXTURE_COMPARE_MODE | GLenum | Yes| +| TEXTURE_COMPARE_FUNC | GLenum | Yes| +| CURRENT_QUERY | GLenum | Yes| +| QUERY_RESULT | GLenum | Yes| +| QUERY_RESULT_AVAILABLE | GLenum | Yes| +| STREAM_READ | GLenum | Yes| +| STREAM_COPY | GLenum | Yes| +| STATIC_READ | GLenum | Yes| +| STATIC_COPY | GLenum | Yes| +| DYNAMIC_READ | GLenum | Yes| +| DYNAMIC_COPY | GLenum | Yes| +| MAX_DRAW_BUFFERS | GLenum | Yes| +| DRAW_BUFFER0 | GLenum | Yes| +| DRAW_BUFFER1 | GLenum | Yes| +| DRAW_BUFFER2 | GLenum | Yes| +| DRAW_BUFFER3 | GLenum | Yes| +| DRAW_BUFFER4 | GLenum | Yes| +| DRAW_BUFFER5 | GLenum | Yes| +| DRAW_BUFFER6 | GLenum | Yes| +| DRAW_BUFFER7 | GLenum | Yes| +| DRAW_BUFFER8 | GLenum | Yes| +| DRAW_BUFFER9 | GLenum | Yes| +| DRAW_BUFFER10 | GLenum | Yes| +| DRAW_BUFFER11 | GLenum | Yes| +| DRAW_BUFFER12 | GLenum | Yes| +| DRAW_BUFFER13 | GLenum | Yes| +| DRAW_BUFFER14 | GLenum | Yes| +| DRAW_BUFFER15 | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| SAMPLER_3D | GLenum | Yes| +| SAMPLER_2D_SHADOW | GLenum | Yes| +| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| +| PIXEL_PACK_BUFFER | GLenum | Yes| +| PIXEL_UNPACK_BUFFER | GLenum | Yes| +| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| +| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| +| FLOAT_MAT2x3 | GLenum | Yes| +| FLOAT_MAT2x4 | GLenum | Yes| +| FLOAT_MAT3x2 | GLenum | Yes| +| FLOAT_MAT3x4 | GLenum | Yes| +| FLOAT_MAT4x2 | GLenum | Yes| +| FLOAT_MAT4x3 | GLenum | Yes| +| SRGB | GLenum | Yes| +| SRGB8 | GLenum | Yes| +| SRGB8_ALPHA8 | GLenum | Yes| +| COMPARE_REF_TO_TEXTURE | GLenum | Yes| +| RGBA32F | GLenum | Yes| +| RGB32F | GLenum | Yes| +| RGBA16F | GLenum | Yes| +| RGB16F | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| +| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| +| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_VARYING_COMPONENTS | GLenum | Yes| +| TEXTURE_2D_ARRAY | GLenum | Yes| +| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| +| R11F_G11F_B10F | GLenum | Yes| +| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| +| RGB9_E5 | GLenum | Yes| +| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| +| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| +| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| +| RASTERIZER_DISCARD | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| +| INTERLEAVED_ATTRIBS | GLenum | Yes| +| SEPARATE_ATTRIBS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| +| RGBA32UI | GLenum | Yes| +| RGB32UI | GLenum | Yes| +| RGBA16UI | GLenum | Yes| +| RGB16UI | GLenum | Yes| +| RGBA8UI | GLenum | Yes| +| RGB8UI | GLenum | Yes| +| RGBA32I | GLenum | Yes| +| RGB32I | GLenum | Yes| +| RGBA16I | GLenum | Yes| +| RGB16I | GLenum | Yes| +| RGBA8I | GLenum | Yes| +| RGB8I | GLenum | Yes| +| RED_INTEGER | GLenum | Yes| +| RGB_INTEGER | GLenum | Yes| +| RGBA_INTEGER | GLenum | Yes| +| SAMPLER_2D_ARRAY | GLenum | Yes| +| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| +| SAMPLER_CUBE_SHADOW | GLenum | Yes| +| UNSIGNED_INT_VEC2 | GLenum | Yes| +| UNSIGNED_INT_VEC3 | GLenum | Yes| +| UNSIGNED_INT_VEC4 | GLenum | Yes| +| INT_SAMPLER_2D | GLenum | Yes| +| INT_SAMPLER_3D | GLenum | Yes| +| INT_SAMPLER_CUBE | GLenum | Yes| +| INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| DEPTH_COMPONENT32F | GLenum | Yes| +| DEPTH32F_STENCIL8 | GLenum | Yes| +| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| +| FRAMEBUFFER_DEFAULT | GLenum | Yes| +| UNSIGNED_INT_24_8 | GLenum | Yes| +| DEPTH24_STENCIL8 | GLenum | Yes| +| UNSIGNED_NORMALIZED | GLenum | Yes| +| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| +| READ_FRAMEBUFFER | GLenum | Yes| +| DRAW_FRAMEBUFFER | GLenum | Yes| +| READ_FRAMEBUFFER_BINDING | GLenum | Yes| +| RENDERBUFFER_SAMPLES | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| +| MAX_COLOR_ATTACHMENTS | GLenum | Yes| +| COLOR_ATTACHMENT1 | GLenum | Yes| +| COLOR_ATTACHMENT2 | GLenum | Yes| +| COLOR_ATTACHMENT3 | GLenum | Yes| +| COLOR_ATTACHMENT4 | GLenum | Yes| +| COLOR_ATTACHMENT5 | GLenum | Yes| +| COLOR_ATTACHMENT6 | GLenum | Yes| +| COLOR_ATTACHMENT7 | GLenum | Yes| +| COLOR_ATTACHMENT8 | GLenum | Yes| +| COLOR_ATTACHMENT9 | GLenum | Yes| +| COLOR_ATTACHMENT10 | GLenum | Yes| +| COLOR_ATTACHMENT11 | GLenum | Yes| +| COLOR_ATTACHMENT12 | GLenum | Yes| +| COLOR_ATTACHMENT13 | GLenum | Yes| +| COLOR_ATTACHMENT14 | GLenum | Yes| +| COLOR_ATTACHMENT15 | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| +| MAX_SAMPLES | GLenum | Yes| +| HALF_FLOAT | GLenum | Yes| +| RG | GLenum | Yes| +| RG_INTEGER | GLenum | Yes| +| R8 | GLenum | Yes| +| RG8 | GLenum | Yes| +| R16F | GLenum | Yes| +| R32F | GLenum | Yes| +| RG16F | GLenum | Yes| +| RG32F | GLenum | Yes| +| R8I | GLenum | Yes| +| R8UI | GLenum | Yes| +| R16I | GLenum | Yes| +| R16UI | GLenum | Yes| +| R32I | GLenum | Yes| +| R32UI | GLenum | Yes| +| RG8I | GLenum | Yes| +| RG8UI | GLenum | Yes| +| RG16I | GLenum | Yes| +| RG16UI | GLenum | Yes| +| RG32I | GLenum | Yes| +| RG32UI | GLenum | Yes| +| VERTEX_ARRAY_BINDING | GLenum | Yes| +| R8_SNORM | GLenum | Yes| +| RG8_SNORM | GLenum | Yes| +| RGB8_SNORM | GLenum | Yes| +| SIGNED_NORMALIZED | GLenum | Yes| +| COPY_READ_BUFFER | GLenum | Yes| +| COPY_WRITE_BUFFER | GLenum | Yes| +| COPY_READ_BUFFER_BINDING | GLenum | Yes| +| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER | GLenum | Yes| +| UNIFORM_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER_START | GLenum | Yes| +| UNIFORM_BUFFER_SIZE | GLenum | Yes| +| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| +| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| +| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| +| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| +| UNIFORM_TYPE | GLenum | Yes| +| UNIFORM_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_INDEX | GLenum | Yes| +| UNIFORM_OFFSET | GLenum | Yes| +| UNIFORM_ARRAY_STRIDE | GLenum | Yes| +| UNIFORM_MATRIX_STRIDE | GLenum | Yes| +| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| +| UNIFORM_BLOCK_BINDING | GLenum | Yes| +| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| +| INVALID_INDEX | GLenum | Yes| +| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| +| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| +| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| +| OBJECT_TYPE | GLenum | Yes| +| SYNC_CONDITION | GLenum | Yes| +| SYNC_STATUS | GLenum | Yes| +| SYNC_FLAGS | GLenum | Yes| +| SYNC_FENCE | GLenum | Yes| +| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| +| UNSIGNALED | GLenum | Yes| +| SIGNALED | GLenum | Yes| +| ALREADY_SIGNALED | GLenum | Yes| +| TIMEOUT_EXPIRED | GLenum | Yes| +| CONDITION_SATISFIED | GLenum | Yes| +| WAIT_FAILED | GLenum | Yes| +| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| +| ANY_SAMPLES_PASSED | GLenum | Yes| +| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| +| SAMPLER_BINDING | GLenum | Yes| +| RGB10_A2UI | GLenum | Yes| +| INT_2_10_10_10_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK | GLenum | Yes| +| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| +| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| +| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| +| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| +| MAX_ELEMENT_INDEX | GLenum | Yes| +| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| +| TIMEOUT_IGNORED | GLint64 | Yes| +| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| ### Methods -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | -| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | -| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | -| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | -| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | -| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| readBuffer(src: GLenum) | void | -| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | -| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | -| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| getFragDataLocation(program: WebGLProgram, name: string) | GLint | -| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | -| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | -| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | -| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | -| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| vertexAttribI4iv(index: GLuint, values: Int32List) | void | -| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | -| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | -| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | -| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | -| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | -| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | -| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| drawBuffers(buffers: GLenum[]) | void | -| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | -| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | -| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | -| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | -| createQuery() | WebGLQuery \| null | -| deleteQuery(query: WebGLQuery \| null) | void | -| isQuery(query: WebGLQuery \| null) | GLboolean | -| beginQuery(target: GLenum, query: WebGLQuery) | void | -| endQuery(target: GLenum) | void | -| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | -| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | -| createSampler() | WebGLSampler \| null | -| deleteSampler(sampler: WebGLSampler \| null) | void | -| isSampler(sampler: WebGLSampler \| null) | GLboolean | -| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | -| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | -| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | -| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | -| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | -| isSync(sync: WebGLSync \| null) | GLboolean | -| deleteSync(sync: WebGLSync \| null) | void | -| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | -| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | -| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | -| createTransformFeedback() | WebGLTransformFeedback \| null | -| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | -| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | -| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | -| beginTransformFeedback(primitiveMode: GLenum) | void | -| endTransformFeedback() | void | -| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | -| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| pauseTransformFeedback() | void | -| resumeTransformFeedback() | void | -| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | -| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | -| getIndexedParameter(target: GLenum, index: GLuint) | any | -| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | -| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | -| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | -| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | -| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | -| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | -| createVertexArray() | WebGLVertexArrayObject \| null | -| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | -| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | -| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | +| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | +| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | +| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | +| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | +| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | +| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| readBuffer(src: GLenum) | void | +| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | +| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | +| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| getFragDataLocation(program: WebGLProgram, name: string) | GLint | +| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | +| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | +| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | +| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | +| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| vertexAttribI4iv(index: GLuint, values: Int32List) | void | +| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | +| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | +| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | +| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | +| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | +| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | +| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| drawBuffers(buffers: GLenum[]) | void | +| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | +| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | +| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | +| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | +| createQuery() | WebGLQuery \| null | +| deleteQuery(query: WebGLQuery \| null) | void | +| isQuery(query: WebGLQuery \| null) | GLboolean | +| beginQuery(target: GLenum, query: WebGLQuery) | void | +| endQuery(target: GLenum) | void | +| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | +| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | +| createSampler() | WebGLSampler \| null | +| deleteSampler(sampler: WebGLSampler \| null) | void | +| isSampler(sampler: WebGLSampler \| null) | GLboolean | +| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | +| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | +| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | +| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | +| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | +| isSync(sync: WebGLSync \| null) | GLboolean | +| deleteSync(sync: WebGLSync \| null) | void | +| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | +| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | +| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | +| createTransformFeedback() | WebGLTransformFeedback \| null | +| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | +| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | +| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | +| beginTransformFeedback(primitiveMode: GLenum) | void | +| endTransformFeedback() | void | +| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | +| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| pauseTransformFeedback() | void | +| resumeTransformFeedback() | void | +| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | +| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | +| getIndexedParameter(target: GLenum, index: GLuint) | any | +| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | +| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | +| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | +| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | +| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | +| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | +| createVertexArray() | WebGLVertexArrayObject \| null | +| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | +| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | +| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | ## WebGL2RenderingContextOverloads WebGL2RenderingContextOverloads -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | -| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | +| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 523758e9caf5ffcba94df7e7efc6756bb5d1fa28..90a20044c16f8c9fe2dd11d3aaa294e7d869c55b 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -248,7 +248,7 @@ Enumerates the color spaces. | Name | Value| Description | | ---------- | ------ | -------------- | -| DEFAULT | 0 | Default gamut.| +| DEFAULT | 0 | Default SRGB gamut.| | WIDE_GAMUT | 1 | Wide-gamut. | ## ScaleOptions9+ @@ -1544,6 +1544,8 @@ moveWindowTo(x: number, y: number, callback: AsyncCallback<void>): void Moves this window. This API uses an asynchronous callback to return the result. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1585,6 +1587,8 @@ moveWindowTo(x: number, y: number): Promise<void> Moves this window. This API uses a promise to return the result. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1636,6 +1640,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1683,6 +1689,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -3721,6 +3729,41 @@ try { ### snapshot9+ +snapshot(callback: AsyncCallback<image.PixelMap>): void + +Captures this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| 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 | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +windowClass.snapshot((err, pixelMap) => { + if (err.code) { + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}); +``` + +### snapshot9+ + snapshot(): Promise<image.PixelMap> Captures this window. This API uses a promise to return the result. @@ -4041,6 +4084,7 @@ try { } catch (exception) { console.error('Failed to set backdrop blur. Cause: ' + JSON.stringify(exception)); } + ``` ### setBackdropBlurStyle9+ @@ -4282,6 +4326,8 @@ moveTo(x: number, y: number, callback: AsyncCallback<void>): void Moves this window. This API uses an asynchronous callback to return the result. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9) instead. @@ -4315,6 +4361,8 @@ moveTo(x: number, y: number): Promise<void> Moves this window. This API uses a promise to return the result. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9-1) instead. @@ -4358,6 +4406,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9) instead. @@ -4397,6 +4447,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9-1) instead. @@ -5864,12 +5916,12 @@ Describes the lifecycle of a window stage. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Value | Description | -| ---------- | ----- | ---------------------------------------------- | -| FOREGROUND | 1 | The window stage is running in the foreground. | -| ACTIVE | 2 | The window stage gains focus. | -| INACTIVE | 3 | The window stage loses focus. | -| BACKGROUND | 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+ @@ -5905,9 +5957,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -5952,9 +6006,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -5998,9 +6054,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6042,9 +6100,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6100,9 +6160,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6149,9 +6211,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6195,9 +6259,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6243,9 +6309,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); @@ -6302,9 +6370,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); @@ -6354,9 +6424,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6404,9 +6476,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6452,9 +6526,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6492,9 +6568,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('disableWindowDecor'); windowStage.disableWindowDecor(); @@ -6533,9 +6611,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6659,6 +6739,7 @@ controller.animationForShown = (context : window.TransitionContext) => { ); console.info('complete transition end'); }; + ``` ### animationForHidden9+ @@ -6705,5 +6786,4 @@ 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-windowAnimationManager.md b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md index 46d23a02136a6d042b3f05fb335d5bd620dfd82f..ffae7ffbf0941f4aa79fb0335b853fc281e66476 100644 --- a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md +++ b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -1,4 +1,5 @@ -# Window Animation Management +# @ohos.animation.windowAnimationManager (Window Animation Management) + The **WindowAnimationManager** module provides APIs to listen for application start/exit events and window minimization/maximization events and associate animations with these events. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 1b269ea33508c427b9480641ee08210b7906eddc..db8a73c0ff0b29ca6c753073f8ea0d297b19ccb8 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -1,9 +1,11 @@ -# @ohos.worker +# @ohos.worker (Worker Startup) The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. With the **Worker** module, you can provide a multithreading environment for an application, so that the application can perform a time-consuming operation in a background thread. This greatly prevents a computing-intensive or high-latency task from blocking the running of the main thread. A **Worker** instance will not be proactively destroyed once it is created. It consumes resources to keep running. Therefore, you should call the API to terminate it in a timely manner. +The **Context** object of the worker thread is different from that of the main thread. The worker thread does not support UI operations. + > **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. @@ -40,13 +42,13 @@ Provides options that can be set for the **Worker** instance to create. ## ThreadWorker9+ -Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [WorkerEventTarget](#workereventtarget9). +Before using the following APIs, you must create a **ThreadWorker** instance. The **ThreadWorker** class inherits from [WorkerEventTarget](#workereventtarget9). ### constructor9+ constructor(scriptURL: string, options?: WorkerOptions) -A constructor used to create a **Worker** instance. +A constructor used to create a **ThreadWorker** instance. **System capability**: SystemCapability.Utils.Lang @@ -59,9 +61,20 @@ A constructor used to create a **Worker** instance. **Return value** -| Type | Description | -| ------ | --------------------------------------------------------- | -| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.| +| Type | Description | +| ------------ | ------------------------------------------------------------ | +| ThreadWorker | Returns the **ThreadWorker** instance created; returns **undefined** if the **ThreadWorker** instance fails to be created.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200003 | Worker initialization failure. | +| 10200007 | The worker file patch is invalid path. | + + **Example** @@ -94,7 +107,7 @@ In the FA model: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -138,6 +151,40 @@ In the stage model: } ``` +### postMessage9+ + +postMessage(message: Object, transfer: ArrayBuffer[]): void; + +Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); + +workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); +``` ### postMessage9+ @@ -154,6 +201,15 @@ Sends a message to the worker thread. The data type of the message must be seque | 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**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + **Example** ```js @@ -165,7 +221,6 @@ var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` - ### on9+ on(type: string, listener: WorkerEventListener): void @@ -181,6 +236,15 @@ Adds an event listener for the worker thread. This API provides the same functio | type | string | Yes | Type of the event to listen for. | | listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -206,6 +270,15 @@ Adds an event listener for the worker thread and removes the event listener afte | type | string | Yes | Type of the event to listen for. | | listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -231,6 +304,15 @@ Removes an event listener for the worker thread. This API provides the same func | type | string | Yes | Type of the event for which the event listener is to be removed. | | listener | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -248,6 +330,14 @@ Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -270,6 +360,15 @@ Defines the event handler to be called when the worker thread exits. The handler | ------ | ------ | ---- | ------------------ | | code | number | Yes | Code indicating the worker thread exit state.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -301,6 +400,15 @@ Defines the event handler to be called when an exception occurs during worker ex | ------ | ------------------------- | ---- | ---------- | | err | [ErrorEvent](#errorevent) | Yes | Error data.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -325,6 +433,15 @@ Defines the event handler to be called when the host thread receives a message s | ------ | -------------------------------- | ---- | ---------------------- | | event | [MessageEvents](#messageevents9) | Yes | Message received.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -351,6 +468,15 @@ Defines the event handler to be called when the worker thread receives a message | ------ | -------------------------------- | ---- | ---------- | | event | [MessageEvents](#messageevents9) | Yes | Error data.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -360,6 +486,169 @@ workerInstance.onmessageerror= function(e) { } ``` +### addEventListener9+ + +addEventListener(type: string, listener: WorkerEventListener): void + +Adds an event listener for the worker thread. This API provides the same functionality as [on9+](#on9). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ---------------- | +| type | string | Yes | Type of the event to listen for.| +| listener | [WorkerEventListener](#workereventlistener9) | Yes | Callback to invoke when an event of the specified type occurs. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +``` + + +### removeEventListener9+ + +removeEventListener(type: string, callback?: WorkerEventListener): void + +Removes an event listener for the worker thread. This API provides the same functionality as [off9+](#off9). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ---------------------------- | +| type | string | Yes | Type of the event for which the event listener is to be removed. | +| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.removeEventListener("alert"); +``` + + +### dispatchEvent9+ + +dispatchEvent(event: Event): boolean + +Dispatches the event defined for the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------- | ---- | ---------------- | +| event | [Event](#event) | Yes | Event to dispatch.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------- | +| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) + +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. +// The event listener created by on will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); +``` + + +### removeAllListener9+ + +removeAllListener(): void + +Removes all event listeners for the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.removeAllListener(); +``` ## WorkerEventTarget9+ @@ -378,6 +667,15 @@ Adds an event listener for the worker thread. This API provides the same functio | type | string | Yes | Type of the event to listen for.| | listener | [WorkerEventListener](#workereventlistener9) | Yes | Callback to invoke when an event of the specified type occurs. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -401,7 +699,15 @@ Removes an event listener for the worker thread. This API provides the same func | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ---------------------------- | | type | string | Yes | Type of the event for which the event listener is to be removed. | -| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| +| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | **Example** @@ -434,6 +740,14 @@ Dispatches the event defined for the worker thread. | ------- | ------------------------------- | | boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -450,11 +764,11 @@ workerInstance.addEventListener("alert_add", (e)=>{ }) // The event listener created by once is removed after being executed once. -workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); -// The event listener created by on will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. +// The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will be always valid and will not be proactively deleted. +// The event listener created by addEventListener will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -484,6 +798,14 @@ Removes all event listeners for the worker thread. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -499,6 +821,53 @@ workerInstance.removeAllListener(); Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **ThreadWorkerGlobalScope** class inherits from [GlobalScope9+](#globalscope9). +### postMessage9+ + +postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; + +Sends a message to the host thread from the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + +**Example** + +```js +// main.js +import worker from '@ohos.worker'; +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.postMessage("hello world"); +workerInstance.onmessage = function(e) { + // let data = e.data; + console.log("receive data from worker.js"); +} +``` + +```js +// worker.js +import worker from '@ohos.worker'; +const workerPort = worker.workerPort; +workerPort.onmessage = function(e){ + // let data = e.data; + var buffer = new ArrayBuffer(8); + workerPort.postMessage(buffer, [buffer]); +} +``` ### postMessage9+ @@ -515,6 +884,15 @@ Sends a message to the host thread from the worker thread. | 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**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + **Example** ```js @@ -531,10 +909,10 @@ workerInstance.onmessage = function(e) { ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e){ +const workerPort = worker.workerPort; +workerPort.onmessage = function(e){ // let data = e.data; - parentPort.postMessage("receive data from main.js"); + workerPort.postMessage("receive data from main.js"); } ``` @@ -547,6 +925,14 @@ Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -558,16 +944,16 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e) { - parentPort.close() +const workerPort = worker.workerPort; +workerPort.onmessage = function(e) { + workerPort.close() } ``` ### onmessage9+ -onmessage?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void +onmessage?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => 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. @@ -578,7 +964,16 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | ------------------------ | | this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | -| event | [MessageEvents](#messageevents9) | Yes | Message received.| +| ev | [MessageEvents](#messageevents9) | Yes | Message received.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -592,8 +987,8 @@ workerInstance.postMessage("hello world"); ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e) { +const workerPort = worker.workerPort; +workerPort.onmessage = function(e) { console.log("receive main.js message"); } ``` @@ -601,7 +996,7 @@ parentPort.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void +onmessageerror?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => 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. @@ -612,7 +1007,16 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | -------------------------------- | ---- | ---------- | | this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | -| event | [MessageEvents](#messageevents9) | Yes | Error data.| +| ev | [MessageEvents](#messageevents9) | Yes | Error data.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -652,6 +1056,15 @@ Implements event listening. | ------------------------------------- | ------------------------------- | | void \| Promise<void> | Returns no value or returns a **Promise**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -701,8 +1114,8 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js") ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort -parentPort.onerror = function(e){ +const workerPort = worker.workerPort +workerPort.onerror = function(e){ console.log("worker.js onerror") } ``` @@ -779,7 +1192,7 @@ In the FA model: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -816,9 +1229,10 @@ In the stage model: } } ``` + ### postMessage(deprecated) -postMessage(message: Object, options?: PostMessageOptions): void +postMessage(message: Object, transfer: ArrayBuffer[]): void; Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). @@ -829,6 +1243,35 @@ Sends a message to the worker thread. The data type of the message must be seque **Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ----------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instances that can be transferred.| + +**Example** + +```js +const workerInstance = new worker.Worker("workers/worker.js"); + +workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); +``` + +### postMessage(deprecated) + +postMessage(message: Object, options?: PostMessageOptions): void + +Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9-1) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | message | Object | Yes | Message to be sent to the worker thread. | @@ -840,9 +1283,6 @@ 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]); ``` @@ -1024,7 +1464,7 @@ Defines the event handler to be called when the host thread receives a message s | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------------------- | -| event | [MessageEvent](#messageeventt) | Yes | Message received.| +| event | [MessageEvent](#messageevent)| Yes | Message received.| **Example** @@ -1053,7 +1493,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | -| event | [MessageEvent](#messageeventt) | Yes | Error data.| +| event | [MessageEvent](#messageevent)| Yes | Error data.| **Example** @@ -1166,7 +1606,7 @@ workerInstance.addEventListener("alert_add", (e)=>{ }) // The event listener created by once is removed after being executed once. -workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); @@ -1219,6 +1659,44 @@ 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. +### postMessage9+ + +postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; + +Sends a message to the host thread from the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ----------------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Example** + +```js +// main.js +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("hello world"); +workerInstance.onmessage = function(e) { + // let data = e.data; + console.log("receive data from worker.js"); +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort; +parentPort.onmessage = function(e){ + // let data = e.data; + let buffer = new ArrayBuffer(5) + parentPort.postMessage(buffer, [buffer]); +} +``` + ### postMessage(deprecated) postMessage(messageObject: Object, options?: PostMessageOptions): void @@ -1259,7 +1737,6 @@ parentPort.onmessage = function(e){ } ``` - ### close(deprecated) close(): void @@ -1290,7 +1767,7 @@ parentPort.onmessage = function(e) { ### onmessage(deprecated) -onmessage?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void +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. @@ -1304,7 +1781,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | -| event | [MessageEvent](#messageeventt) | Yes | Message received.| +| ev | [MessageEvent](#messageevent) | Yes | Message received.| **Example** @@ -1326,7 +1803,7 @@ parentPort.onmessage = function(e) { ### onmessageerror(deprecated) -onmessageerror?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void +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. @@ -1340,7 +1817,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| -| event | [MessageEvent](#messageeventt) | Yes | Error data.| +| ev | [MessageEvent](#messageevent)| Yes | Error data.| **Example** @@ -1376,10 +1853,10 @@ Defines the event. **System capability**: SystemCapability.Utils.Lang -| Name | Type | Readable| Writable| Description | -| --------- | ------ | ---- | ---- | ---------------------------------- | -| type | string | Yes | No | Type of the event. | -| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | -------------------------------------------- | +| type | string | Yes | No | Type of the event. | +| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created. This parameter is not supported yet.| ## EventListener(deprecated) @@ -1525,14 +2002,14 @@ workerInstance.onmessage = function(d) { ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; +const workerPort = worker.workerPort; class MyModel { name = "undefined" Init() { this.name = "MyModel" } } -parentPort.onmessage = function(d) { +workerPort.onmessage = function(d) { console.log("worker.js onmessage"); let data = d.data; let func1 = function() { @@ -1546,14 +2023,14 @@ parentPort.onmessage = function(d) { } } let obj2 = new MyModel(); - // parentPort.postMessage(func1); A serialization error occurs when passing func1. - // parentPort.postMessage(obj1); A serialization error occurs when passing obj1. - parentPort.postMessage(obj2); // No serialization error occurs when passing obj2. + // workerPort.postMessage(func1); A serialization error occurs when passing func1. + // workerPort.postMessage(obj1); A serialization error occurs when passing obj1. + workerPort.postMessage(obj2); // No serialization error occurs when passing obj2. } -parentPort.onmessageerror = function(e) { +workerPort.onmessageerror = function(e) { console.log("worker.js onmessageerror"); } -parentPort.onerror = function(e) { +workerPort.onerror = function(e) { console.log("worker.js onerror"); } ``` @@ -1571,6 +2048,7 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther - Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. - Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated). +- When creating a **Worker** project, do not import any UI construction method (such as .ets file) to the worker thread file (for example, **worker.ts** used in this document). Otherwise, the worker module becomes invalid. To check whether any UI construction method has been imported, decompress the generated HAP file, find **worker.js** in the directory where the worker thread is created, and search for the keyword **View** globally. If the keyword exists, a UI construction method has been packaged in **worker.js**. If this is your case, change the directory level of **src** in the statement **import "xxx" from src** in the worker thread file. ## Sample Code > **NOTE**
@@ -1611,23 +2089,23 @@ workerInstance.onexit = function() { import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. -const parentPort = worker.workerPort +const workerPort = worker.workerPort // In versions earlier than API version 9, use the following to create an object in the worker thread for communicating with the main thread. // const parentPort = worker.parentPort // The worker thread receives information from the main thread. -parentPort.onmessage = function(e) { +workerPort.onmessage = function(e) { // data carries the information sent by the main thread. let data = e.data; console.log("worker.ts onmessage"); // The worker thread sends information to the main thread. - parentPort.postMessage("123") + workerPort.postMessage("123") } // Trigger a callback when an error occurs in the worker thread. -parentPort.onerror= function(e) { +workerPort.onerror= function(e) { console.log("worker.ts onerror"); } ``` @@ -1636,7 +2114,7 @@ Configuration of the **build-profile.json5** file: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -1673,20 +2151,20 @@ workerInstance.onexit = function() { import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. -const parentPort = worker.workerPort +const workerPort = worker.workerPort // The worker thread receives information from the main thread. -parentPort.onmessage = function(e) { +workerPort.onmessage = function(e) { // data carries the information sent by the main thread. let data = e.data; console.log("worker.ts onmessage"); // The worker thread sends information to the main thread. - parentPort.postMessage("123") + workerPort.postMessage("123") } // Trigger a callback when an error occurs in the worker thread. -parentPort.onerror= function(e) { +workerPort.onerror= function(e) { console.log("worker.ts onerror"); } ``` diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index ec3549a4051ea6784a56be33c902fc167e1311a1..2f793c39a2234eb16b30d634d53279d1b1c70de3 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -32,9 +32,16 @@ A constructor used to create an **XmlSerializer** instance. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(2048); +let thatSer = new xml.XmlSerializer(arrayBuffer,"utf-8"); +thatSer.setDeclaration(); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -56,12 +63,19 @@ Sets an attribute. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); -thatSer.setAttributes("importance", "high"); -thatSer.endElement(); +thatSer.setAttributes("importance1", "high1"); +thatSer.endElement(); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -82,10 +96,17 @@ Adds an empty element. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.addEmptyElement("b"); // => +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.addEmptyElement("d"); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -100,10 +121,20 @@ Sets a declaration. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.setDeclaration() // => ; +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -124,13 +155,22 @@ Writes the start tag based on the given element name. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.startElement("notel"); -thatSer.endElement();// => ''; +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` - ### endElement endElement(): void @@ -142,14 +182,20 @@ Writes the end tag of the element. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); -thatSer.startElement("table"); -thatSer.setAttributes("importance", "high"); -thatSer.setText("Happy"); -thatSer.endElement(); // => Happy +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` @@ -171,12 +217,20 @@ Sets the namespace for an element tag. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setDeclaration(); -thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.startElement("note"); -thatSer.endElement();// = >'\r\n'; +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` ### setComment @@ -196,11 +250,17 @@ Sets the comment. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.startElement("note"); -thatSer.setComment("Hi!"); -thatSer.endElement(); // => '\r\n \r\n'; +thatSer.setComment("Hello, World!"); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //' ``` @@ -221,9 +281,17 @@ Sets CDATA attributes. **Example** ```js -let arrayBuffer = new ArrayBuffer(1028); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.setCDATA('root SYSTEM') // => ''; +thatSer.setCDATA('root SYSTEM') +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //''' ``` @@ -244,12 +312,20 @@ Sets **Text**. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); thatSer.setAttributes("importance", "high"); thatSer.setText("Happy1"); -thatSer.endElement(); // => 'Happy1'; +thatSer.endElement(); +let result = 'Happy1'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // 'Happy1' ``` @@ -270,9 +346,17 @@ Sets **DocType**. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.setDocType('root SYSTEM'); // => ''; +thatSer.setDocType('root SYSTEM "http://www.test.org/test.dtd"'); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //'' ``` @@ -298,19 +382,40 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa ```js let strXml = - '' + - '' + - ' Happy' + - ' Work' + - ' Play' + - ''; + '' + + ']>' + + '' + + ' ' + + ' ' + + ' John & Hans' + + ' Happy' + + ' Happy' + + ' Work' + + ' Play' + + ' ' + + ' ' + + ' ' + + ' ' + + ' Apples' + + ' Bananas' + + ' ' + + ' ' + + ''; let arrayBuffer = new ArrayBuffer(strXml.length); let bufView = new Uint8Array(arrayBuffer); let strLen = strXml.length; -for (var i = 0; i < strLen; ++i) { - bufView[i] = strXml.charCodeAt(i);// Set the ArrayBuffer mode. +for (let i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i); } -let that = new xml.XmlPullParser(arrayBuffer); +let that = new xml.XmlPullParser(arrayBuffer, 'UTF-8'); +let str1 = ''; +function func1(name, value){ + str1 += name+':'+value; + return true; +} +let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func1} +that.parse(options); +console.log(str1) //'note:company:title:title:lens:lens:a:b:h:table:h:tr:h:td:h:td:' ``` @@ -341,7 +446,7 @@ let strXml = let arrayBuffer = new ArrayBuffer(strXml.length); let bufView = new Uint8Array(arrayBuffer); let strLen = strXml.length; -for (var tmp = 0; tmp < strLen; ++tmp) { +for (let tmp = 0; tmp < strLen; ++tmp) { bufView[tmp] = strXml.charCodeAt(tmp); } let that = new xml.XmlPullParser(arrayBuffer); @@ -399,6 +504,38 @@ Obtains the column line number, starting from 1. | ------ | -------------- | | number | Column number obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getColumnNumber(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:1key:2 value:77key:10 value:81key:2 value:88key:4 value:93key:3 value:101key:10 value:105key:2 value:111key:4 value:115key:3 value:122key:10 value:126key:2 value:132key:4 value:136key:3 value:143key:3 value:150key:1 value:299 +``` ### getDepth @@ -414,6 +551,41 @@ Obtains the depth of this element. | ------ | -------------------- | | number | Depth obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:0key:2 value:1key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:3 value:1key:1 value:0 +// Note: +// key indicates the event type, and value indicates the parsing depth. You can learn the specific parsed event based on EVENTTYPE. In this example, key: value means: +// 0(START_DOCUMENT):0 (START_DOCUMENT is being parsed, and the depth is 0), 2(START_TAG):1 (START_TAG is being parsed, and the depth is 1), 10(WHITESPACE):1 (WHITESPACE is being parsed, and the depth is 1), 2(START_TAG):2 (START_TAG is being parsed, and the depth is 2), ... +``` ### getLineNumber @@ -429,6 +601,38 @@ Obtains the current line number, starting from 1. | ------ | -------------- | | number | Line number obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getLineNumber(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:1key:2 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:3 value:1key:1 value:1 +``` ### getName @@ -444,7 +648,38 @@ Obtains the name of this element. | ------ | ------------------ | | string | Element name obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getName(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:notekey:10 value:key:2 value:titlekey:4 value:key:3 value:titlekey:10 value:key:2 value:todokey:4 value:key:3 value:todokey:10 value:key:2 value:todokey:4 value:key:3 value:todokey:3 value:notekey:1 value: +``` ### getNamespace getNamespace(): string @@ -459,7 +694,38 @@ Obtains the namespace of this element. | ------ | ------------------------ | | string | Namespace obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getNamespace(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:3 value:key:1 value: +``` ### getPrefix getPrefix(): string @@ -474,6 +740,38 @@ Obtains the prefix of this element. | ------ | ------------------ | | string | Element prefix obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getPrefix(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:3 value:key:1 value: +``` ### getText @@ -489,7 +787,38 @@ Obtains the text of the current event. | ------ | ------------------------ | | string | Text content obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getText(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value: key:2 value:key:4 value:Happykey:3 value:key:10 value: key:2 value:key:4 value:Workkey:3 value:key:10 value: key:2 value:key:4 value:Playkey:3 value:key:3 value:key:1 value: +``` ### isEmptyElementTag isEmptyElementTag(): boolean @@ -504,7 +833,38 @@ Checks whether the current element is empty. | ------- | ---------------------------- | | boolean | Returns **true** if the element is empty; returns **false** otherwise.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.isEmptyElementTag(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:falsekey:2 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:3 value:falsekey:1 value:false +``` ### isWhitespace isWhitespace(): boolean @@ -519,7 +879,38 @@ Checks whether the current text event contains only whitespace characters. | ------- | -------------------------------------- | | boolean | Returns **true** if the text event contains only whitespace characters; returns **false** otherwise.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.isWhitespace(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:truekey:2 value:falsekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:3 value:truekey:1 value:true +``` ### getAttributeCount getAttributeCount(): number @@ -533,6 +924,38 @@ Obtains the number of attributes for the current start tag. | ------ | ---------------------- | | number | Number of attributes obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' 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 arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getAttributeCount(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:0key:2 value:2key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:3 value:0key:1 value:0 +``` ## EventType diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index aa7d700534b09bb582ca96d61740fdd6ff9681b9..8ab71a62ddea41f2ffd92fd323fd46eada2614ad 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,6 +1,6 @@ -# @ohos.zlib +# @ohos.zlib (Zip) -The **zlib** module provides APIs for file compression and decompression. +The **Zip** module provides APIs for file compression and decompression. > **NOTE** > @@ -25,7 +25,7 @@ Zips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | | options | [Options](#options) | Yes | Optional parameters for the zip operation. | @@ -39,6 +39,7 @@ Zips a file. This API uses a promise to return the result. ```typescript // Zip a file. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -59,6 +60,7 @@ zlib.zipFile(inFile, outFile, options).then((data) => { ```typescript // Zip a folder. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/xxx'; let outFile = '/xxx/xxx.zip'; @@ -89,7 +91,7 @@ Unzips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to unzip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the unzipped file. | | options | [Options](#options) | Yes | Optional parameters for the unzip operation. | @@ -103,6 +105,7 @@ Unzips a file. This API uses a promise to return the result. ```typescript // Unzip a file. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; @@ -131,7 +134,7 @@ Compresses a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -141,14 +144,14 @@ Compresses a file. This API uses an asynchronous callback to return the result. For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). | ID| Error Message | | -------- | --------------------------------------| -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | **Example** ```typescript // Compress a file. -// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -179,7 +182,7 @@ Compresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | @@ -189,12 +192,12 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod | ID| Error Message | | -------- | ------------------------------------- | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | ```typescript // Compress a file. -// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -229,7 +232,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -240,14 +243,14 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod | ID| Error Message | -------- | --------------------------------------| -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | **Example** ```typescript // Decompress a file. -// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; @@ -270,7 +273,7 @@ try { decompressFile(inFile: string, outFile: string, options: Options): Promise\; -Decompress a file. This API uses a promise to return the result. +Decompresses a file. This API uses a promise to return the result. **System capability**: SystemCapability.BundleManager.Zlib @@ -278,7 +281,7 @@ Decompress a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | @@ -288,12 +291,12 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod | ID| Error Message | | ------ | ------------------------------------- | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | ```typescript // Decompress a file. -// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; diff --git a/en/application-dev/reference/arkui-ts/ts-container-flex.md b/en/application-dev/reference/arkui-ts/ts-container-flex.md index 5b8c2e1044dc7bc5dcf45e95386adb1d7f30651c..a2de237b09f26589ff262ea1cabe89273bec72d9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/en/application-dev/reference/arkui-ts/ts-container-flex.md @@ -4,7 +4,7 @@ The **\** component allows for flexible layout of child components. > **NOTE** > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -> - The **\** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[Column](ts-container-column.md)** or **[Row](ts-container-row.md)** instead under scenarios where consistently high performance is required. +> - The **\** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[\](ts-container-column.md)** or **[\](ts-container-row.md)** instead under scenarios where consistently high performance is required. ## Required Permissions @@ -30,7 +30,7 @@ Creates a standard **\** component. | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\** component has a single line or multiple lines. | | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\** component along the main axis. | | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\** component along the cross axis. | - | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.| + | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **\** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index dc3c3e9859a27813299a3ccb9e1ddaff47b88cea..849218cf45e69fd423b020dd8dd26381933c1fe3 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -54,7 +54,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## SwiperController -Controller of the **\** component. You can bind this object to the **** component and use it to control page switching. +Controller of the **\** component. You can bind this object to the **\** component and use it to control page switching. ### showNext diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 8425cf29444183671c4fd8e3389bd0ffa28840f9..a603c54bc5f16e877420e80c1714ac16f70e2123 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -17,7 +17,7 @@ The location attributes set the alignment mode, layout direction, and position o | position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| | markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
} | | offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
} | -| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| +| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container. This attribute is valid only when the container is [\](ts-container-relativecontainer.md).
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| ## Example diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index b286cbf232d6d334444b164117fa289b79f9a6c4..28669ef9f2e4955e785462d935468bd519fd2931 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -33,8 +33,11 @@ - Security - [Ability Access Control Error Codes](errorcode-access-token.md) - [HUKS Error Codes](errorcode-huks.md) + - [User Authentication Error Codes](errorcode-useriam.md) - Data Management - [RDB Error Codes](errorcode-data-rdb.md) + - [DataShare Error Codes](errorcode-datashare.md) + - [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md) - [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) - [Preferences Error Codes](errorcode-preferences.md) - File Management diff --git a/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md new file mode 100644 index 0000000000000000000000000000000000000000..0ebad934ac37ea27b349fa9e2b0c0d4941f83ca3 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md @@ -0,0 +1,19 @@ +# Distributed Data Object Error Codes + +## 15400001 Failed to Create the In-Memory Database + +**Error Message** + +Create table failed. + +**Description** + +The in-memory database fails to be created. + +**Possible Causes** + +An object with the same session ID already exists. + +**Solution** + +Check for the object has been added to the same session. diff --git a/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md b/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md index da3088db9008d5077568765065e62efa5e1bbd11..5d1c22ab4c978474af0f12f896d0159857e271a8 100644 --- a/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md +++ b/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @@ -66,20 +66,20 @@ Not found. **Description** -Related data is found when **deleteKVStore()**, **delete()**, **deleteBatch()**, or **get()** is called. +Related data is not found when **deleteKVStore()**, **sync()**, or **get()** is called. **Possible Causes** The possible causes are as follows: 1. The KV store to delete does not exist or has been deleted. 2. The data queried does not exist or has been deleted. -3. The data to delete does not exist or has been deleted. +3. The KV store specified for the data synchronization operation does not exist or has been deleted. **Solution** 1. Before deleting a KV store, check that the KV store exists. 2. When querying data in a KV store, check whether the query keywords are correct. -3. When deleting data from a KV store, check that the keyword for the deletion is correct and the data to delete exists. +3. Before synchronizing data, check that the related KV store is available. ## 15100005 KV Store or Result Set Closed diff --git a/en/application-dev/reference/errorcodes/errorcode-i18n.md b/en/application-dev/reference/errorcodes/errorcode-i18n.md index 71555203e62a93f1c8cdfcfaf5f46ed04832c681..8a1392286491b7e7173d26a2e62c740de4abdbdf 100644 --- a/en/application-dev/reference/errorcodes/errorcode-i18n.md +++ b/en/application-dev/reference/errorcodes/errorcode-i18n.md @@ -1,4 +1,4 @@ -# I18N Error Codes +# i18n Error Codes ## 890001 Incorrect Parameter Type diff --git a/en/application-dev/reference/errorcodes/errorcode-useriam.md b/en/application-dev/reference/errorcodes/errorcode-useriam.md new file mode 100644 index 0000000000000000000000000000000000000000..2e84641a549af91c9101e94da86b54cf0db9d712 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-useriam.md @@ -0,0 +1,163 @@ +# User Authentication Error Codes + +## 201 Permission Verification Failed + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 202 Invoker Is Not a System Application + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 401 Parameter Check Failed. + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 12500001 Authentication Failed + +**Error Message** + +Authentication failed. + +**Possible Causes** + +The credential does not match the credential enrolled. + +**Solution** + +Initiate authentication again. + +## 12500002 General Operation Error + +**Error Message** + +General operation error. + +**Possible Causes** + +1. An error occurs when the NAPI layer parses parameters. +2. The process of the user authentication service is not started. +3. The proxy client fails to write data over IPC. +4. The stub server fails to parse data over IPC. +5. The driver service is not obtained. + +**Solution** + +Call the API again later or restart the device. + +## 12500003 Authentication Canceled + +**Error Message** + +Authentication canceled. + +**Possible Causes** + +The authentication operation has been canceled. + +**Solution** + +Initiate the authentication again. + +## 12500004 Authentication Timed Out + +**Error Message** + +Authentication timeout. + +**Possible Causes** + +The authentication is not complete within the specified time. + +**Solution** + +Initiate the authentication again. + +## 12500005 Unsupported Authentication Type + +**Error Message** + +The authentication type is not supported. + +**Possible Causes** + +1. The input authentication type parameter is not supported. For example, if the authentication type passed in **getAvailableStatus** of the **userAuth** module is not **FACE** or **FINGERPRINT**, error code 12500005 is returned. +2. The device does not support the authentication type. For example, if fingerprint authentication is initiated on a device that has no fingerprint sensor, error code 12500005 is returned. + +**Solution** + +Check the authentication type parameter and call the API again. + +## 12500006 Unsupported Authentication Trust Level + +**Error Message** + +The authentication trust level is not supported. + +**Possible Causes** + +1. The **authTrustLevel** value in **getAvailableStatus** or **getAuthInstance** of the **userAuth** module is not in the range [ATL1, ATL2, ATL3, ATL4]. +2. The device does not support the authentication trust level. For example, if facial authentication for payment is initiated on a device that has only 2D cameras, error code 12500006 is returned. + +**Solution** + +Check that the **authTrustLevel** passed in is within the value range, and the device supports the specified authentication trust level. + +## 12500007 Authentication Service Unavailable + +**Error Message** + +Authentication service is busy. + +**Possible Causes** + +Another authentication is initiated when the current authentication has not been finished yet. + +**Solution** + +Initiate authentication again later. + +## 12500009 Authentication Locked + +**Error Message** + +Authentication is lockout. + +**Possible Causes** + +The number of authentication failures exceeds the limit. + +**Solution** + +Initiate authentication later. + +## 12500010 Credential Not Enrolled + +**Error Message** + +The type of credential has not been enrolled. + +**Possible Causes** + +The **authType** parameter set in **getAvailableStatus** of the **userAuth** module is **FACE**, but no facial credential is enrolled in the device. +**start()** is called to initiate facial authentication, but no facial credential is enrolled in the device. + +**Solution** + +Check that the related type of credential has been enrolled in the device. + +## 12700001 Failed to Enroll Faces + +**Error Message** + +The operation is failed. + +**Possible Causes** + +1. The facial authentication service is not started when **setSurfaceId()** of the **userAuth** module is called. +2. The proxy client fails to write data over IPC. +3. The stub server fails to parse data over IPC. +4. An error occurs when the facial authentication driver is invoked. + +**Solution** + +Call the API again later or restart the device. diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md index 6c8e02e6dfa0779fd378dc04b81f090f258338dd..a05bdaa4c6bb6c20f7a886dfe6b2495e1674c814 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md @@ -173,7 +173,7 @@ The following examples are not intended as copy-paste-ready. Further customizati "clickOneDay": { "action": "router", "bundleName": "com.example.calendar", - "abilityName": "com.example.calendar.MainAbility", + "abilityName": "EntryAbility", "params": { "action": "click_month_view_event", "day": "$event.day", diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md index cbf1f5fcb5aee5d2b80ff0ef22e9e38acbde16e9..31b25496a065cba484199dac044282cbd8d50b15 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md @@ -55,5 +55,5 @@ You can set universal styles for components in the **style** attribute or **.css | image-fill | <color> | - | Fill color for SVG images. The following components (and attributes) are supported: **button** (**icon** attribute) and **image** (**src** attribute).
The **fill** color value in the SVG image file is replaced with the value of **image-fill** during rendering, and is valid only for the fill attribute that is declared in the SVG image.| | clip-path | [ <geometry-box> \|<basic-shape> ] \| none | - | Clip area of the component. Only the content within this area is displayed.
**\**: applicable scope of the clip area's width and height. The default value is **border-box**. Available values are as follows:
- **margin-box**: The width and height includes the margin.
- **border-box**: The width and height includes the border.
- **padding-box**: The width and height includes the padding.
- **content-box**: The width and height does not include any margin, border, or padding.
**\**: shape of the clip area. Available values include:
- **inset**, in the format of inset( <percentage>{1,4} [ round <'border-radius'> ]? )
- **circle**, in the format of circle( [ <percentage> ]? [ at <percentage> <percentage> ]? )
- **ellipse**, in the format of ellipse( [ <percentage>{2} ]? [ at <percentage> <percentage> ]? )
- **polygon**, in the format of polygon( [ <percentage> <percentage> ]\# )
- **path**, in the format of path( <string> )| | mask-image | - <linear-gradient>
- string | - | Image used for the mask of the component:
Gradient color mask, for example, **linear-gradient(to left, black, white)**.
Solid color mask, for example, **linear-gradient(to right, grey , grey)**.
Mask filled by a local SVG image, for example, **url(common/mask.svg)**| -| mask-size | - string
- <length><length>
- <percentage> <percentage> | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.
The **string** values are as follows:
- **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: retains the original aspect ratio of the image.
The two **\** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
The two **** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.| +| mask-size | - string
- <length><length>
- <percentage> <percentage> | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.
The **string** values are as follows:
- **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: retains the original aspect ratio of the image.
The two **\** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
The two **\** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default. | | mask-position | - string string
- <length> <length>
- <percentage> <percentage> | 0px 0px | Display position of the mask image. The setting is valid only when **mask-image** is set to an image source. Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.
The **string** values are as follows:
- **left**: leftmost in the horizontal direction.
- **right**: rightmost in the horizontal direction.
- **top**: top in the vertical direction.
- **bottom**: bottom in the vertical direction.
- **center**: center position.
Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0 0 in px (**0px 0px**). If only one value is specified, the other one is **50%**.
Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0% 0%. For the lower right corner, the value is **100% 100%**. If only one value is specified, the other one is **50%**.
Using both **\** and **\**.| diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md index 9dbecd2d9174138b5df9d49da3caeecb07e5d76f..1622e3755d7670e70d3792c9cf2ac0c65f22cf08 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md @@ -24,7 +24,7 @@ Custom components are existing components encapsulated based on service requirem | Name| Type| Description| | -------- | -------- | -------- | | data | Object | Data model of the page. The name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).| -| props | Array/Object | Used for communication between components. This attribute can be transferred to components via ****. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.| +| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions. | ## Adding a Custom Event diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md index 2ebbe2b66d3bc4feac7fb0d090e2833e761f88c9..403d80f0efc046048662a17f19ea7de51b5aa402 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md @@ -112,7 +112,7 @@ You can also implement redirection to the target application using a **want**, w "action": "router", "want": { "bundleName": "com.example.myapplication", - "abilityName": "com.example.entry.MainAbility" + "abilityName": "EntryAbility" } }, "routerEventName2": { diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md index 20396da04e28f5c408b971d717f4af7bcbc3ca58..1d52a333239bdb0b273b21b6a6dbe6bc6c49140f 100644 --- a/en/application-dev/security/accesstoken-guidelines.md +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -220,7 +220,7 @@ onWindowStageCreate() { By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed apps, you can pre-authroize the permissions, for example, the **ohos.permission.MICROPHONE** permission, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file to prevent the user authorization dialog box from being displayed. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device. When the device is started, the **install_list_permissions.json** file is loaded. When the application is installed, the **user_grant** permissions in the file are granted. The **install_list_permissions.json** file contains the following fields: - **bundleName**: bundle name of the application. -- `app_signature`: fingerprint information of the application. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install-list-capabilityjson). +- `app_signature`: fingerprint information of the application. For details, see **Configuration in install_list_capability.json** in [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). - **permissions**: **name** specifies the name of the **user_grant** permission to pre-authorize. **userCancellable** specifies whether the user can revoke the pre-authorization. The value **true** means the user can revoke the pre-authorization; the vaue **false** means the opposite. > **NOTE**
This file is available only for preinstalled applications. @@ -244,4 +244,3 @@ By default, the **user_grant** permissions must be dynamically authorized by the } ] ``` - \ No newline at end of file diff --git a/en/application-dev/security/cert-guidelines.md b/en/application-dev/security/cert-guidelines.md index 9ba67b26752c374e35296dda9e428267f1195595..ed0e3e39a791b5c60055e9e200d764940ecfc12d 100644 --- a/en/application-dev/security/cert-guidelines.md +++ b/en/application-dev/security/cert-guidelines.md @@ -19,21 +19,20 @@ Typical operations involve the following: **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. | Instance | API | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------- | -| cryptoCert | createX509Cert(inStream : EncodingBlob, callback : AsyncCallback) : void | Parses certificate data to create an **X509Cert** instance. This API uses an asynchronous callback to return the result.| -| cryptoCert | createX509Cert(inStream : EncodingBlob) : Promise | Parses certificate data to create an **X509Cert** instance. This API uses a promise to return the result. | -| X509Cert | verify(key : cryptoFramework.PubKey, callback : AsyncCallback) : void | Verifies the certificate signature. This API uses an asynchronous callback to return the result. | -| X509Cert | verify(key : cryptoFramework.PubKey) : Promise | Verifies the certificate signature. This API uses a promise to return the result. | -| X509Cert | getEncoded(callback : AsyncCallback) : void | Obtains serialized certificate data. This API uses an asynchronous callback to return the result. | -| X509Cert | getEncoded() : Promise | Obtains serialized certificate data. This API uses a promise to return the result. | -| X509Cert | getPublicKey(callback : AsyncCallback) : void | Obtains the certificate public key. This API uses an asynchronous callback to return the result. | -| X509Cert | getPublicKey() : Promise | Obtains the certificate public key. This API uses a promise to return the result. | -| X509Cert | checkValidityWithDate(date: string, callback : AsyncCallback) : void | Verifies the certificate validity period. This API uses an asynchronous callback to return the result. | -| X509Cert | checkValidityWithDate(date: string) : Promise | Verifies the certificate validity period. This API uses a promise to return the result. | +| cryptoCert | createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void | Parses certificate data to create an **X509Cert** instance. This API uses an asynchronous callback to return the result.| +| cryptoCert | createX509Cert(inStream : EncodingBlob) : Promise\ | Parses certificate data to create an **X509Cert** instance. This API uses a promise to return the result. | +| X509Cert | verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void | Verifies the certificate signature. This API uses an asynchronous callback to return the result. | +| X509Cert | verify(key : cryptoFramework.PubKey) : Promise\ | Verifies the certificate signature. This API uses a promise to return the result. | +| X509Cert | getEncoded(callback : AsyncCallback\) : void | Obtains serialized certificate data. This API uses an asynchronous callback to return the result. | +| X509Cert | getEncoded() : Promise\ | Obtains serialized certificate data. This API uses a promise to return the result. | +| X509Cert | getPublicKey() : cryptoFramework.PubKey | Obtains the certificate public key. | +| X509Cert | checkValidityWithDate(date: string) : void | Checks the certificate validity period. | | X509Cert | getVersion() : number | Obtains the certificate version. | | X509Cert | getSerialNumber() : number | Obtains the certificate serial number. | | X509Cert | getIssuerName() : DataBlob | Obtains the certificate issuer. | @@ -72,7 +71,7 @@ let certData = "-----BEGIN CERTIFICATE-----\n" + "I1Lwu6in1ruflZhzseWulXwcITf3bm/Y5X1g1XFWQUH\n" + "-----END CERTIFICATE-----\n"; -// Convert the string into a Uint8Array. +// Convert the certificate data form a string to a Uint8Array.. function stringToUint8Array(str) { var arr = []; for (var i = 0, j = str.length; i < j; i++) { @@ -94,11 +93,11 @@ function certSample() { cryptoCert.createX509Cert(encodingBlob, function (err, x509Cert) { if (err != null) { // Failed to create the X509Cert instance. - Console.log("createX509Cert failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("createX509Cert failed, errCode: " + err.code + ", errMsg: " + err.message); return; } // The X509Cert instance is successfully created. - Console.log("createX509Cert success"); + console.log("createX509Cert success"); // Obtain the certificate version. let version = x509Cert.getVersion(); @@ -107,51 +106,41 @@ function certSample() { x509Cert.getEncoded(function (err, data) { if (err != null) { // Failed to obtain the serialized data of the certificate. - Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); } else { // The serialized data of the certificate is successfully obtained. - Console.log("getEncoded success"); + console.log("getEncoded success"); } }); - - // Obtain the certificate public key. - x509Cert.getPublicKey(function (err, pubKey) { - if (err != null) { - // Failed to obtain the certificate public key. - Console.log("getPublicKey failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The certificate public key is successfully obtained. - Console.log("getPublicKey success"); - } - }); - + // Obtain the public key object using the getPublicKey() of the upper-level certificate object or this (self-signed) certificate object. let pubKey = null; - + try { + pubKey = x509Cert.getPublicKey(); + } catch (error) { + console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message); + } + // Verify the certificate signature. x509Cert.verify(pubKey, function (err, data) { if (err == null) { // The signature verification is successful. - Console.log("verify success"); + console.log("verify success"); } else { // The signature verification failed. - Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); } }); - + // Time represented in a string. let date = "150527000001Z"; // Verify the certificate validity period. - x509Cert.checkValidityWithDate(date, function (err, data) { - if (err != null) { - // Failed to verify the certificate validity period. - Console.log("checkValidityWithDate failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The certificate validity period is verified successfully. - Console.log("checkValidityWithDate success"); - } - }); + try { + x509Cert.checkValidityWithDate(date); + } catch (error) { + console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } }); } ``` @@ -171,36 +160,33 @@ Typical operations involve the following: **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. | Instance | API | Description | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| cryptoCert | createX509Crl(inStream : EncodingBlob, callback : AsyncCallback) : void | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses an asynchronous callback to return the result.| -| cryptoCert | createX509Crl(inStream : EncodingBlob) : Promise | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses a promise to return the result. | -| X509Crl | isRevoked(cert : X509Cert, callback : AsyncCallback) : void | Checks whether the certificate is revoked. This API uses an asynchronous callback to return the result. | -| X509Crl | isRevoked(cert : X509Cert) : Promise | Checks whether the certificate is revoked. This API uses a promise to return the result. | -| X509Crl | getType() : string | Obtains the CRL type. | -| X509Crl | getEncoded(callback : AsyncCallback) : void | Obtains the serialized CRL data. This API uses an asynchronous callback to return the result. | -| X509Crl | getEncoded() : Promise | Obtains the serialized CRL data. This API uses a promise to return the result. | -| X509Crl | verify(key : cryptoFramework.PubKey, callback : AsyncCallback) : void | Verifies the CRL signature. This API uses an asynchronous callback to return the result. | -| X509Crl | verify(key : cryptoFramework.PubKey) : Promise | Verifies the CRL signature. This API uses a promise to return the result. | -| X509Crl | getVersion() : number | Obtains the CRL version. | +| cryptoCert | createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses an asynchronous callback to return the result.| +| cryptoCert | createX509Crl(inStream : EncodingBlob) : Promise\ | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses a promise to return the result. | +| X509Crl | isRevoked(cert : X509Cert) : boolean | Checks whether the certificate is revoked. | +| X509Crl | getType() : string | Obtains the CRL type. | +| X509Crl | getEncoded(callback : AsyncCallback\) : void | Obtains the serialized CRL data. This API uses an asynchronous callback to return the result. | +| X509Crl | getEncoded() : Promise\ | Obtains the serialized CRL data. This API uses a promise to return the result. | +| X509Crl | verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void | Verifies the CRL signature. This API uses an asynchronous callback to return the result. | +| X509Crl | verify(key : cryptoFramework.PubKey) : Promise\ | Verifies the CRL signature. This API uses a promise to return the result. | +| X509Crl | getVersion() : number | Obtains the CRL version. | | X509Crl | getIssuerName() : DataBlob | Obtains the CRL issuer. | | X509Crl | getLastUpdate() : string | Obtains the date when the CRL was last updated. | | X509Crl | getNextUpdate() : string | Obtains the next update date of the CRL. | -| X509Crl | getRevokedCert(serialNumber : number, callback : AsyncCallback) : void | Obtains the revoked certificate in the CRL based on the specified serial number. This API uses an asynchronous callback to return the result. | -| X509Crl | getRevokedCert(serialNumber : number) : Promise | Obtains the revoked certificate in the CRL based on the specified serial number. This API uses a promise to return the result. | -| X509Crl | getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback) : void | Obtains the specified X.509 certificate from the CRL. This API uses an asynchronous callback to return the result. | -| X509Crl | getRevokedCertWithCert(cert : X509Cert) : Promise | Obtains the specified X.509 certificate from the CRL. This API uses a promise to return the result. | -| X509Crl | getRevokedCerts(callback : AsyncCallback>) : void | Obtains all revoked certificates in the CRL. This API uses an asynchronous callback to return the result. | -| X509Crl | getRevokedCerts() : Promise> | Obtains all revoked certificates in the CRL. This API uses a promise to return the result. | -| X509Crl | getTbsInfo(callback : AsyncCallback) : void | Obtains the tbsCertList of the CRL. This API uses an asynchronous callback to return the result. | -| X509Crl | getTbsInfo() : Promise | Obtains the tbsCertList of the CRL. This API uses a promise to return the result. | +| X509Crl | getRevokedCert(serialNumber : number) : X509CrlEntry | Obtains the revoked certificate in the CRL based on the serial number. | +| X509Crl | getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry | Obtains the revoked certificate in the CRL based on the X.509 certificate. | +| X509Crl | getRevokedCerts(callback : AsyncCallback\>) : void | Obtains all revoked certificates in the CRL. This API uses an asynchronous callback to return the result. | +| X509Crl | getRevokedCerts() : Promise\> | Obtains all revoked certificates in the CRL. This API uses a promise to return the result. | +| X509Crl | getTbsInfo() : DataBlob | Obtains **tbsCertList** of the CRL. | | X509Crl | getSignature() : DataBlob | Obtains the CRL signature. | -| X509Crl | getSignatureAlgName() : string | Obtains the CRL signing algorithm. | -| X509Crl | getSignatureAlgOid() : string | Obtains the signing algorithm OID of the CRL. | -| X509Crl | getSignatureAlgParams() : DataBlob | Obtains the signing algorithm parameters of the CRL. | +| X509Crl | getSignatureAlgName() : string | Obtains the CRL signing algorithm. | +| X509Crl | getSignatureAlgOid() : string | Obtains the signing algorithm OID of the CRL. | +| X509Crl | getSignatureAlgParams() : DataBlob | Obtains the signing algorithm parameters of the CRL. | **How to Develop** @@ -223,7 +209,7 @@ let crlData = "-----BEGIN X509 CRL-----\n" + "DrAA7hErVgXhtURLbAI=\n" + "-----END X509 CRL-----\n"; -// Convert the string into a Uint8Array. +// Convert the certificate data form a string to a Uint8Array.. function stringToUint8Array(str) { var arr = []; for (var i = 0, j = str.length; i < j; i++) { @@ -245,11 +231,11 @@ function crlSample() { cryptoCert.createX509Crl(encodingBlob, function (err, x509Crl) { if (err != null) { // Failed to create the X509Crl instance. - Console.log("createX509Crl failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("createX509Crl failed, errCode: " + err.code + ", errMsg: " + err.message); return; } // The X509Crl instance is successfully created. - Console.log("createX509Crl success"); + console.log("createX509Crl success"); // Obtain the CRL version. let version = x509Crl.getVersion(); @@ -257,55 +243,46 @@ function crlSample() { // Obtain the serialized data of the CRL. x509Crl.getEncoded(function (err, data) { if (err != null) { - // Failed to obtain the serialized CRL data. - Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + // Failed to obtain the serialized data of the certificate. + console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); } else { - // The serialized CRL data is successfully obtained. - Console.log("getEncoded success"); + // The serialized data of the certificate is successfully obtained. + console.log("getEncoded success"); } }); - + // Create an X509Cert instance by using createX509Cert() of cryptoFramework. let x509Cert = null; - // Check whether the certificate is revoked. - x509Crl.isRevoked(x509Cert, function (err, isRevoked) { - if (err != null) { - // The operation fails. - Console.log("isRevoked failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The operation is successful. - Console.log("isRevoked success, isRevoked? " + isRevoked); - } - }); - + try { + let revokedFlag = x509Crl.isRevoked(x509Cert); + } catch (error) { + console.log("isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message); + } + // Obtain the PubKey instance by using generateKeyPair() or convertKey() of AsyKeyGenerator. The process is omitted here. let pubKey = null; // Verify the CRL signature. x509Crl.verify(pubKey, function (err, data) { if (err == null) { - // The operation is successful. - Console.log("verify success"); + // The signature verification is successful. + console.log("verify success"); } else { - // The operation fails. - Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); + // The signature verification failed. + console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); } }); - + // Certificate serial number, which must be set based on the service. let serialNumber = 1000; - + // Obtain the revoked certificate based on the serial number. - x509Crl.getRevokedCert(serialNumber, function (err, entry) { - if (err != null) { - // The operation fails. - Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The operation is successful. - Console.log("getRevokedCert success"); - } - }); + try { + let entry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } }); } ``` @@ -318,14 +295,15 @@ You need to use the certificate chain validator in certificate chain verificatio **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. | Instance | API | Description | | ------------------ | ------------------------------------------------------------ | -------------------------------- | | cryptoCert | createCertChainValidator(algorithm :string) : CertChainValidator | Creates a **CertChainValidator** instance.| -| CertChainValidator | validate(certChain : CertChainData, callback : AsyncCallback) : void | Verifies the certificate chain. This API uses an asynchronous callback to return the result. | -| CertChainValidator | validate(certChain : CertChainData) : Promise | Verifies the certificate chain. This API uses a promise to return the result. | +| CertChainValidator | validate(certChain : CertChainData, callback : AsyncCallback\) : void | Verifies the certificate chain. This API uses an asynchronous callback to return the result. | +| CertChainValidator | validate(certChain : CertChainData) : Promise\ | Verifies the certificate chain. This API uses a promise to return the result. | | CertChainValidator | algorithm : string | Obtains the certificate chain validator algorithm. | **How to Develop** @@ -349,7 +327,7 @@ let secondCaCertData = "-----BEGIN CERTIFICATE-----\n" + "...\n" + "-----END CERTIFICATE-----\n"; -// Convert the certificate data form a string to a Uint8Array. +// Convert the certificate data form a string to a Uint8Array.. function stringToUint8Array(str) { var arr = []; for (var i = 0, j = str.length; i < j; i++) { @@ -408,10 +386,10 @@ function certChainValidatorSample() { validator.validate(certChainData, function (err, data) { if (err != null) { // The operation fails. - Console.log("validate failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("validate failed, errCode: " + err.code + ", errMsg: " + err.message); } else { // The operation is successful. - Console.log("validate success"); + console.log("validate success"); } }); } @@ -429,18 +407,17 @@ Typical operations involve the following: **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. -| Instance | API | Description | -| ------------ | ----------------------------------------------------------- | ------------------------------------------ | -| X509CrlEntry | getEncoded(callback : AsyncCallback) : void; | Obtains the serialized data of the revoked certificate. This API uses an asynchronous callback to return the result.| -| X509CrlEntry | getEncoded() : Promise; | Obtains the serialized data of the revoked certificate. This API uses a promise to return the result. | -| X509CrlEntry | getSerialNumber() : number; | Obtains the serial number of the revoked certificate. | -| X509CrlEntry | getCertIssuer(callback : AsyncCallback) : void; | Obtains the issuer of the revoked certificate. This API uses an asynchronous callback to return the result. | -| X509CrlEntry | getCertIssuer() : Promise; | Obtains the issuer of the revoked certificate. This API uses a promise to return the result. | -| X509CrlEntry | getRevocationDate(callback : AsyncCallback) : void; | Obtains the revocation date of the certificate. This API uses an asynchronous callback to return the result. | -| X509CrlEntry | getRevocationDate() : Promise; | Obtains the issuer of the revoked certificate. This API uses a promise to return the result. | +| Instance | API | Description | +| ------------ | ----------------------------------------------------------- | ---------------------------------------- | +| X509CrlEntry | getEncoded(callback : AsyncCallback\) : void; | Obtains the serialized data of the revoked certificate. This API uses an asynchronous callback to return the result.| +| X509CrlEntry | getEncoded() : Promise\; | Obtains the serialized data of the revoked certificate. This API uses a promise to return the result. | +| X509CrlEntry | getSerialNumber() : number; | Obtains the serial number of the revoked certificate. | +| X509CrlEntry | getCertIssuer() : DataBlob; | Obtains the issuer of the revoked certificate. | +| X509CrlEntry | getRevocationDate() : string; | Obtains the revocation date of the revoked certificate. | **How to Develop** @@ -456,39 +433,32 @@ function crlEntrySample() { // Obtain a revoked certificate instance. In this example, the instance is obtained by using getRevokedCert(). let serialNumber = 1000; - x509Crl.getRevokedCert(serialNumber, function (err, crlEntry) { + let crlEntry = null; + try { + crlEntry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + + // Obtain the serial number of the revoked certificate. + let serialNumber = crlEntry.getSerialNumber(); + + // Obtain the revocation date of the revoked certificate. + try { + crlEntry.getRevocationDate(); + } catch (error) { + console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } + + // Obtain the serialized data of the revoked certificate instance. + crlEntry.getEncoded(function (err, data) { if (err != null) { - // Failed to obtain the revoked certificate instance. - Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message); - return; + // Failed to obtain the serialized data of the certificate. + console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // The serialized data of the certificate is successfully obtained. + console.log("getEncoded success"); } - // The revoked certificate instance is successfully obtained. - Console.log("getRevokedCert success"); - - // Obtain the serial number of the revoked certificate. - let serialNumber = crlEntry.getSerialNumber(); - - // Obtain the revocation date of the revoked certificate. - crlEntry.getRevocationDate(function (err, date) { - if (err != null) { - // Failed to obtain the revocation date. - Console.log("getRevocationDate failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The revocation date is successfully obtained. - Console.log("getRevocationDate success, date is: " + date); - } - }); - - // Obtain the serialized data of the revoked certificate instance. - crlEntry.getEncoded(function (err, data) { - if (err != null) { - // Failed to obtain the serialized data. - Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The serialized data is successfully obtained. - Console.log("getEncoded success"); - } - }); }); } ``` diff --git a/en/application-dev/security/cryptoFramework-guidelines.md b/en/application-dev/security/cryptoFramework-guidelines.md index 35784280547f6f5064fc13f15d651801ea0d0b02..0ed590fbf850cfbbcac7e0c64ddcb0872d9d9353 100644 --- a/en/application-dev/security/cryptoFramework-guidelines.md +++ b/en/application-dev/security/cryptoFramework-guidelines.md @@ -32,10 +32,10 @@ The table below describes the APIs used in this guide. |AsyKeyGenerator|generateKeyPair() : Promise\|Generates an asymmetric key pair randomly. This API uses a promise to return the result.| |SymKeyGenerator|generateSymKey(callback : AsyncCallback\) : void|Generates a symmetric key randomly. This API uses an asynchronous callback to return the result.| |SymKeyGenerator|generateSymKey() : Promise\|Generates a symmetric key randomly. This API uses a promise to return the result.| -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) | -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary public key and private key data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) | -| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts binary data into a symmetric key. This API uses an asynchronous callback to return the result.| -| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts binary data into a symmetric key. This API uses a promise to return the result.| +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts the binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) | +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) | +| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts the binary data into a symmetric key. This API uses an asynchronous callback to return the result. | +| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts the binary data into a symmetric key. This API uses a promise to return the result. | | Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)| **How to Develop** @@ -121,11 +121,11 @@ function convertAsyKey() { } ``` -**NOTE** - -The public key returned by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key must be in the DER format complying with PKCS #8 specifications. +> **NOTE** +> +> The public key returned by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key must be in the DER format complying with PKCS #8 specifications. -Example 4: Generate an asymmetric key pair from the binary ECC key data. + Example 4: Generate an asymmetric key pair from the binary ECC key data. 1. Obtain the ECC binary key data and encapsulate it into a **DataBlob** instance. 2. Call **convertKey()** to convert the key binary data (data of the private or public key, or both) passed in to a **KeyPair** instance. @@ -264,14 +264,14 @@ function stringToUint8Array(str) { return new Uint8Array(arr); } -// Convert byte streams into strings in plaintext. +// Output the byte streams in hexadecimal format. function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -// Output the byte streams in hexadecimal format. +// Convert byte streams into strings in plaintext. function uint8ArrayToString(array) { let arrayString = ''; for (let i = 0; i < array.length; i++) { @@ -383,14 +383,14 @@ function stringToUint8Array(str) { return new Uint8Array(arr); } -// Convert byte streams into strings in plaintext. +// Output the byte streams in hexadecimal format. function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -// Output the byte streams in hexadecimal format. +// Convert byte streams into strings in plaintext. function uint8ArrayToString(array) { let arrayString = ''; for (let i = 0; i < array.length; i++) { @@ -492,17 +492,9 @@ function test3DesEcb() { Example 2: Encrypt and decrypt data using an asymmetric key pair. -1. Generate an RSA key pair. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. - -2. Create a **Cipher** instance. - - Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. - -3. Perform encryption and decryption operations. - - Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. +3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -548,19 +540,19 @@ function encryptMessageCallback() { } ``` -**NOTE** - -- In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each of encryption and decryption. -- The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Crypto Framework Overview](cryptoFramework-overview.md). -- In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8. +> **NOTE** +> +> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each of encryption and decryption. +> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Crypto Framework Overview](cryptoFramework-overview.md). +> - In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8. ## Signing Data and Verifying Signatures **When to Use** A digital signature can be used to verify the authenticity of a message. Typical signing and signature verification operations involve the following: -1. Use RSA to sign data and verify the signature. -2. Use ECC to sign data and verify the signature. +- Use RSA to sign data and verify the signature. +- Use ECC to sign data and verify the signature. **Available APIs** @@ -573,38 +565,24 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry |Sign|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Sign** instance. This API uses a promise to return the result.| |Sign|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signing. This API uses an asynchronous callback to return the result.| |Sign|update(data : DataBlob) : Promise\|Updates the data for signing. This API uses a promise to return the result.| -|Sign|sign(data : DataBlob, callback : AsyncCallback) : void|Signs the data. This API uses an asynchronous callback to return the result.| -|Sign|sign(data : DataBlob) : Promise|Signs the data. This API uses a promise to return the result.| +|Sign|sign(data : DataBlob, callback : AsyncCallback\) : void|Signs the data. This API uses an asynchronous callback to return the result.| +|Sign|sign(data : DataBlob) : Promise\|Signs the data. This API uses a promise to return the result.| |cryptoFramework|function createVerify(algName : string) : Verify|Creates a **Verify** instance.| |Verify|init(priKey : PriKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.| |Verify|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.| |Verify|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signature verification. This API uses an asynchronous callback to return the result.| |Verify|update(data : DataBlob) : Promise\|Updates the data for signature verification. This API uses a promise to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise|Verifies the signature. This API uses a promise to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies the signature. This API uses a promise to return the result.| **How to Develop** Example 1: Use RSA to sign data and verify the signature. -1. Generate an RSA key pair. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. - -2. Create a **Sign** instance. - - Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. - -3. Generate a signature. - - Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. - -4. Create a **Verify** instance. - - Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. - -5. Verify the signature. - - Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -684,25 +662,11 @@ function verifyMessageCallback() { ``` Example 2: Using ECC to sign data and verify the signature. -1. Generate an ECC key. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. - -2. Create a **Sign** instance. - - Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. - -3. Generate a signature. - - Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. - -4. Create a **Verify** instance. - - Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. - -5. Verify the signature. - - Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -802,10 +766,10 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------------- | | cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance. | -| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| -| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | -| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | -| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. | +| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| +| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | +| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | +| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. | | Md | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. | | Md | readonly algName : string; | Obtains the digest algorithm. | @@ -907,10 +871,7 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry **How to Develop** -1. Generate an ECC key. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. - +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. 2. Generate a shared secret by using the private and public ECC keys. ```javascript @@ -966,15 +927,15 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | --------------------------------------------------- | -| cryptoFramework | function createMac(algName : string) : Md; | Creates a **Mac** instance. | -| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| -| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | -| Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | -| Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | -| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | -| Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | +| cryptoFramework | function createMac(algName : string) : Mac; | Creates a **Mac** instance. | +| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| +| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | +| Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | +| Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | +| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | +| Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | | Mac | getMacLength() : number; | Obtains the length of the MAC based on the specified algorithm. | -| Mac | readonly algName : string; | Obtains the algorithm. | +| Mac | readonly algName : string; | Obtains the digest algorithm. | **How to Develop** @@ -1099,10 +1060,9 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | ---------------------------------------------- | | cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. | -| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | -| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | -| Random | setSeed(seed : DataBlob, callback : AsyncCallback\) : void; | Sets a seed. This API uses an asynchronous callback to return the result.| -| Random | setSeed(seed : DataBlob) : Promise\; | Sets a seed. This API uses a promise to return the result. | +| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | +| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | +| Random | setSeed(seed : DataBlob) : void; | Sets a seed. | **How to Develop** @@ -1124,10 +1084,11 @@ function doRandByPromise(len) { var promiseGenerateRand = rand.generateRandom(len); promiseGenerateRand.then(randData => { console.error("[Promise]: rand result: " + randData.data); - var promiseSetSeed = rand.setSeed(randData); - return promiseSetSeed; - }).then(() => { - console.error("[Promise]: setSeed success"); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -1146,13 +1107,11 @@ function doRandByCallback(len) { console.error("[Callback]: err: " + err.code); } else { console.error("[Callback]: generate random result: " + randData.data); - rand.setSeed(randData, (err1,) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: setSeed success"); - } - }); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } } }); } diff --git a/en/application-dev/security/cryptoFramework-overview.md b/en/application-dev/security/cryptoFramework-overview.md index afaa9658f3b9bd55754f3d830090ff3eece4e26a..9b0248563b33df85f26ff10b33432465ba6cf367 100644 --- a/en/application-dev/security/cryptoFramework-overview.md +++ b/en/application-dev/security/cryptoFramework-overview.md @@ -1,14 +1,14 @@ # Crypto Framework Overview -The crypto framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hash, and secure random number. You can use the APIs provided by this framework to implement cipher development quickly. +The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hashes, and secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. ## Working Principles -The crypto framework provides components in the following layers: +The crypto framework provides components in the following layers: - Interface layer: provides unified JS interface externally. - Plugin layer: implements third-party algorithm libraries. -- Framework layer: flexibly loads the plugins in the plugin layer to adapt to third-party algorithm libraries and shields the implement differences between the third-party algorithm libraries. +- Framework layer: flexibly loads the plugins in the plugin layer to adapt to third-party algorithm libraries and shields the implementation differences between these libraries. ## Basic Concepts -### Symmetric Key +**Symmetric Key** A symmetric key is a key used both to encrypt and decrypt data. In symmetric encryption, the sender converts information in plaintext into ciphertext using a key and certain algorithm for security purposes. The receiver converts the ciphertext into plaintext using the same key and algorithm. @@ -19,7 +19,7 @@ A symmetric key is a key used both to encrypt and decrypt data. In symmetric enc Triple Data Encryption Standard (3DES), also called 3DESede or Triple DES, applies the DES cipher three times to each data block. It uses three 64-bit keys to encrypt a data block three times. Compared with DES, 3DES provides higher security due to longer key length, but its processing speed is lower. The AES is faster and more secure than 3DES. -### Asymmetric Key +**Asymmetric Key** In the asymmetric cryptography, a private and public key pair is required. The private key is used to encrypt the plaintext, and the public key is used to decrypt the ciphertext. The public key is public and open to anyone in the system, while the private key is private. For signing and signature verification, the private key is used to sign the plaintext, and the public key is used to verify the signature data. @@ -27,7 +27,7 @@ In the asymmetric cryptography, a private and public key pair is required. The p The security of RSA relies on the factoring problem, that is, the difficulty of factoring the product of two large prime numbers. The keys for the RSA algorithm are generated as follows: - 1. Generate two large prime numbers **p** and **q**. + 1. Generate two large prime numbers **p** and **q**. 2. Compute **n** = **p** x **q**. @@ -41,44 +41,37 @@ In the asymmetric cryptography, a private and public key pair is required. The p The public key consists of the modulus **n** and the public exponent **e**. The private key consists of **n** and the private exponent **d**. - In addition to the default RSA key generation from two primes, the crypto framework provides key generation from multiple primes. You can set the **primes** parameter (PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5) to specify the number of primes during key generation. The keys generated from multiple primes help reduce the computation workload in decryption and signing (Chinese remainder theorem). However, such keys are weak. The algorithm library defines specifications based on the rules for using OpenSSL prime numbers. For details, see **Constraints**. + In addition to the default RSA key generation from two primes, the crypto framework provides key generation from multiple primes. You can set the **primes** parameter (PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5) to specify the number of primes during key generation. The keys generated from multiple primes help reduce the computation workload in decryption and signing (Chinese remainder theorem). However, such keys are weak. The algorithm library defines specifications based on the rules for using OpenSSL prime numbers. For details, see [**Constraints**](#constraints). - ECC key Elliptic-Curve Cryptography (ECC) is a public-key encryption based on the algebraic structure of elliptic curve over finite fields. The crypto framework provides a variety of ECC key generation capabilities. -### Encryption and Decryption +**Encryption and Decryption** - Symmetric AES encryption and decryption - The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM. - - AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows: - + The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM. AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows: - **NoPadding**: no padding. - - **PKCS5**: pads a block cipher with a block size of 8 bytes. - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - - > **NOTE** - > - > In ECB and CBC modes, the plaintext length is not an integer multiple of 128 bits and must be padded. - -- Symmetric 3DES encryption and decryption - - 3DES encryption and decryption apply the DES cipher three times to each data block obtain the ciphertext or plaintext. - The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB. + > **NOTE** + > + > In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 128 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. + +- Symmetric 3DES encryption and decryption - DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows: + 3DES encryption and decryption apply the DES cipher three times to each data block to obtain the ciphertext or plaintext. + The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB. DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows: - **NoPadding**: no padding. - **PKCS5**: pads a block cipher with a block size of 8 bytes. - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - > **NOTE** + > **NOTE** > - > In ECB and CBC, the plaintext length is not an integer multiple of 64 bits and must be padded. + > In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 64 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 8 bytes in 3DES encryption. - Asymmetric RSA encryption and decryption @@ -90,21 +83,17 @@ In the asymmetric cryptography, a private and public key pair is required. The p Plaintext = Ciphertext ^ **d** mod **n** - The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**. - - RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows: + The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**. RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows: - **NoPadding**: No padding is required. The length of the input or output data must be the same as that of the RSA key modulus. - - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. The length of the input data must be less than or equal to the RSA key modulus minus 11, and the length of the output data must be the same as that of the RSA key modulus. + - **PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus the **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus. - - **PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus. - - **NOTE** - - Length of the RSA key modulus = (Number of RSA bits + 7)/8 + > **NOTE** + > + > Length of the RSA key modulus = (Number of RSA bits + 7)/8 -### Signing and Signature Verification +**Signing and Signature Verification** - RSA signing and signature verification @@ -116,41 +105,41 @@ In the asymmetric cryptography, a private and public key pair is required. The p Message = Signature ^ **d** mod **n** - The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest and then sign the message. The crypto framework provides the following padding modes for signing and signature verification: + The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest before signing the message. The crypto framework provides the following padding modes for signing and signature verification: - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. When this mode is used, the digest (**md**) must be set. - **PSS**: The PSS mode is a padding algorithm based on the RSA algorithm. When it is used, the digest (**md**) and mask function (**mgf1_md**) are required. - ECDSA - The Elliptic Curve Digital Signature Algorithm (ECDSA) is a Digital Signature Algorithm (DSA) that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the unit bit strength of ECC is higher than that of other public-key cryptographic systems. The crypto framework provides the ECDSA that combines multiple elliptic curve and digest algorithms. + The Elliptic Curve Digital Signature Algorithm (ECDSA) is a Digital Signature Algorithm (DSA) that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the ECC provides a higher unit bit strength than other public-key cryptographic systems. The crypto framework provides the ECDSA that combines multiple elliptic curve and digest algorithms. -### Key Agreement +**Key Agreement** -**ECDH** +- **ECDH** -Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The crypto framework provides a variety of ECDH capabilities based on the open-source algorithm library. + Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The crypto framework provides a variety of ECDH capabilities based on the open-source algorithm library. -### Digest +**Digest** -The message digest algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. The message digest algorithm is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. +The message digest algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. It is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. When the same digest algorithm is used, the generated digest (hash value) has the following features: - The same message always results in the same hash value. - The digest generated is of the fixed length no matter the length of messages. (The digest length is determined by the algorithm used). -- It is almost impossible to find two different messages with the same hash value (the probability still exists, depending on the length of the digest). +- It is almost impossible to find two different messages with the same hash value. (The probability still exists, depending on the length of the digest.) -There are three types of message digest algorithms: MD, SHA, and MAC. For details, see section "**HMAC**". +There are three types of message digest algorithms: MD, SHA, and MAC. For details, see section **HMAC**. MD algorithms include MD2, MD4, and MD5. Major SHA algorithms include SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. -### HMAC +**HMAC** -Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. HMAC provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify both the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. +Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. HMAC provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. Compared with MAC, HMAC introduces the shared secret, which ensures data correctness. -### Random Number +**Random Number** -Random numbers are mainly used to generate temporary session keys or keys in asymmetric encryption. Random numbers can be generated by a hardware random number generator or software-based pseudo-random number generator. In encryption and decryption, a secure random number generator must feature randomness, repeatability, and unpredictability. The random numbers generated by the Cryptography Secure Random Number Generator (CSPRNG) meet the requirements of cryptography security pseudo-randomness. +Random numbers are mainly used to generate temporary session keys or keys in asymmetric encryption. They are generated by a hardware random number generator or software-based pseudo-random number generator. In encryption and decryption, a secure random number generator must feature randomness, unrepeatability, and unpredictability. The random numbers generated by the Cryptography Secure Random Number Generator (CSPRNG) meet the requirements of cryptography security pseudo-randomness. - Internal state @@ -163,7 +152,7 @@ Random numbers are mainly used to generate temporary session keys or keys in asy ## Constraints -- The crypto framework does not support concurrent operations of multiple threads. +The crypto framework does not support concurrent operations of multiple threads. ### Key Generation Specifications @@ -171,19 +160,24 @@ Random numbers are mainly used to generate temporary session keys or keys in asy The following parameters are supported: -|Symmetric Key Algorithm|Key Length|String for Generating a Key| +|Symmetric Key Algorithm|Key Length (Bit)|String Parameter| |---|---|---| |3DES|192|3DES192| |AES|128|AES128| |AES|192|AES192| |AES|256|AES256| + > **NOTE** + > + > **String Parameter** is a combination of **Symmetric Key Algorithm** and **Key Length**. It specifies the key specifications when a symmetric key generator is created. + **Asymmetric Key Generation Specifications** + - **RSA key generation** The following parameters are supported: - |Asymmetric Key Algorithm|Key Length|Number of Primes|String for Generating a Key| + |Asymmetric Key Algorithm|Key Length (Bit)|Number of Primes|String Parameter| |---|---|---|---| |RSA|512|2|RSA512\|PRIMES_2| |RSA|768|2|RSA768\|PRIMES_2| @@ -203,7 +197,7 @@ The following parameters are supported: > **NOTE** > - > When the RSA asymmetric key is generated, the default number of primes is 2 and the **PRIMES_2** parameter can be omitted. + > When an RSA asymmetric key is generated, the default prime number is 2, and **PRIMES_2** is optional. - **ECC key generation** @@ -214,7 +208,7 @@ The following parameters are supported: |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| - |ECC|ECC512| + |ECC|ECC521| ### Encryption and Decryption Specifications @@ -222,7 +216,7 @@ The following parameters are supported: The following symmetric encryption algorithms are supported: -|Algorithm|Block Cipher Mode|Algorithm String| +|Algorithm|Block Cipher Mode| String Parameter | |---|---|---| |3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]| |3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]| @@ -237,56 +231,56 @@ The following symmetric encryption algorithms are supported: |AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]| > **NOTE** -> -> The options included in the square brackets ([]) are mutually exclusive. +> - The options included in the square brackets ([]) are mutually exclusive. +> - **String Parameter** is a combination of **Algorithm** (including the key length), **Block Cipher Mode**, and padding mode. It specifies the symmetric encryption/decryption algorithm specifications when a symmetric encryption/decryption instance is created. **Asymmetric RSA Encryption and Decryption** -The following padding modes are involved in RSA encryption and decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. -- When **NoPadding** is used, you can specify the following parameters: +The crypto framework provides three padding modes for RSA encryption/decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. +- If **NoPadding** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|NoPadding -- When **PKCS1** is used, you can specify the following parameters: +- If **PKCS1** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1 -- When **PKCS1_OAEP** is used, you can specify the following parameters: +- If **PKCS1_OAEP** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1_OAEP|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512] > **NOTE** > -> The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. +> The options included in the square brackets ([]) are mutually exclusive, and the options outside [] are fixed values. ### Signing and Signature Verification Specifications **RSA Signing and Signature Verification** -The following padding modes are involved in RSA encryption and decryption: **PKCS1** and **PSS**. -- When **PKCS1** is used, you can specify the following parameters: +The crypto framework provides two padding modes for RSA signing and signature verification: **PKCS1** and **PSS**. +- If **PKCS1** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512] -- When **PSS** is used, you can specify the following parameters: +- If **PSS** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PSS|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512] > **NOTE** > -> The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. +> The options included in the square brackets ([]) are mutually exclusive, and the options outside [] are fixed values. **ECDSA Signing and Signature Verification** The following ECDSA parameters are supported: -|Asymmetric Key Algorithm|Supported Types| +|Asymmetric Key Algorithm|Supported Type| |---|---| |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| -|ECC|ECC512| +|ECC|ECC521| -|Digest Algorithm|Supported Types| +|Digest Algorithm|Supported Type| |---|---| |HASH|SHA-1| |HASH|SHA-224| @@ -300,12 +294,12 @@ The following ECDSA parameters are supported: The following ECDH parameters are supported: -|Asymmetric Key Algorithm|Supported Types| +|Asymmetric Key Algorithm|Supported Type| |---|---| |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| -|ECC|ECC512| +|ECC|ECC521| ### MD Algorithm Specifications The crypto framework supports only MD5. diff --git a/en/application-dev/security/hapsigntool-overview.md b/en/application-dev/security/hapsigntool-overview.md index bb91ed70b2cd9edeef18cc29348bb59d1908e559..24901bd3b2df1bcc9f0e14fc53a845171854c631 100644 --- a/en/application-dev/security/hapsigntool-overview.md +++ b/en/application-dev/security/hapsigntool-overview.md @@ -26,7 +26,7 @@ The hapsigner tool is implemented based on the Public Key Infrastructure (PKI). - Profile - [HarmonyAppProvision configuration file](../quick-start/app-provision-structure.md) provides information such as the authorized application permissions and device ID. + [HarmonyAppProvision configuration file](app-provision-structure.md) provides information such as the authorized application permissions and device ID. ## Constraints diff --git a/en/application-dev/security/huks-guidelines.md b/en/application-dev/security/huks-guidelines.md index cfeb93d8d766b4c8b791db43a7be18e95583c575..b72be28c24888642d1220779104477d28a170176 100644 --- a/en/application-dev/security/huks-guidelines.md +++ b/en/application-dev/security/huks-guidelines.md @@ -2,7 +2,7 @@ OpenHarmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys. -> **NOTE**
+> **NOTE** > > This document is based on API version 9 and applies only to ArkTS development. @@ -20,9 +20,9 @@ Generate a key for an application by specifying the alias and key parameters. > **NOTE** > -> 1. When a key is used if the parameters passed in does not comply with the parameters passed in during the key generation, the parameter verification will fail. +> - When a key is used if the parameters passed in does not comply with the parameters passed in during the key generation, the parameter verification will fail. > -> 2. If an optional parameter required by the algorithm is not passed in during the key generation process, it must be passed in when the key is used. +> - If an optional parameter required by the algorithm is not passed in during the key generation process, it must be passed in when the key is used. **Supported Key Types** diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index 7f84d9cd058732ee490428034d90338bfaf7ea9c..073b31fc651ced76f80b95ed796ca452ca4c62d2 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -1,165 +1,1605 @@ -# App Permission List - -Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine whether the app can apply for the target permissions based on the table below. - -For details about permission usage examples, see [Permission Application Guide](accesstoken-guidelines.md). - -| Permission | APL | Authorization Mode | Enable ACL| Description | -| -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------- | -| ohos.permission.USE_BLUETOOTH | normal | system_grant | TRUE | Allows an app to access to Bluetooth configuration. | -| ohos.permission.DISCOVER_BLUETOOTH | normal | system_grant | TRUE | Allows an app to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. | -| ohos.permission.MANAGE_BLUETOOTH | system_basic | system_grant | TRUE | Allows an app to pair with a Bluetooth device and access the contacts or messages of the device. | -| ohos.permission.INTERNET | normal | system_grant | TRUE | Allows an app to access the Internet. | -| ohos.permission.
MODIFY_AUDIO_SETTINGS | normal | system_grant | TRUE | Allows an app to modify audio settings. | -| ohos.permission.
ACCESS_NOTIFICATION_POLICY | normal | system_grant | FALSE | Allows an app to access the notification policy on the device. | -| ohos.permission.GET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to read telephony information. | -| ohos.permission.REQUIRE_FORM | system_basic | system_grant | TRUE | Allows an app to obtain the Ability Form. | -| ohos.permission.GET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to obtain network information. | -| ohos.permission.PLACE_CALL | system_basic | system_grant | TRUE | Allows an app to make calls without starting the dialer. | -| ohos.permission.SET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to set data network information. | -| ohos.permission.REMOVE_CACHE_FILES | system_basic | system_grant | TRUE | Allows the cache of the specified app to be cleared. | -| ohos.permission.REBOOT | system_basic | system_grant | TRUE | Allows an app to restart the device. | -| ohos.permission.RUNNING_LOCK | normal | system_grant | TRUE | Allows an app to obtain a running lock. | -| ohos.permission.SET_TIME | system_basic | system_grant | TRUE | Allows an app to set the system time. | -| ohos.permission.SET_TIME_ZONE | system_basic | system_grant | TRUE | Allows an app to set the system time zone. | -| ohos.permission.
DOWNLOAD_SESSION_MANAGER | system_core | system_grant | TRUE | Allows an app to manage the download sessions. | -| ohos.permission.COMMONEVENT_STICKY | normal | system_grant | TRUE | Allows an app to publish sticky common events. | -| ohos.permission.SYSTEM_FLOAT_WINDOW | system_basic | system_grant | TRUE | Allows an app to be displayed in a floating window on top of other apps. | -| ohos.permission.PRIVACY_WINDOW | system_basic | system_grant | TRUE | Allows an app to set screens that cannot be captured or recorded. | -| ohos.permission.POWER_MANAGER | system_core | system_grant | TRUE | Allows an app to hibernate or wake up the device by calling APIs. | -| ohos.permission.REFRESH_USER_ACTION | system_basic | system_grant | TRUE | Allows an app to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen. | -| ohos.permission.POWER_OPTIMIZATION | system_basic | system_grant | TRUE | Allows an app to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes.| -| ohos.permission.REBOOT_RECOVERY | system_basic | system_grant | TRUE | Allows an app to restart the device and enter Recovery mode. | -| ohos.permission.
MANAGE_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows an app to manage local user accounts. | -| ohos.permission.
INTERACT_ACROSS_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows access between multiple OS accounts. | -| ohos.permission.VIBRATE | normal | system_grant | TRUE | Allows an app to control vibration. | -| ohos.permission.CONNECT_IME_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind to the **InputMethodAbility**. | -| ohos.permission.
CONNECT_SCREEN_SAVER_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind to the **ScreenSaverAbility**. | -| ohos.permission.
READ_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to read the screen saver information, such as the list of screen savers that have been installed and the activated one. | -| ohos.permission.
WRITE_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to modify the screen saver information, such as activating and previewing a screen saver. | -| ohos.permission.SET_WALLPAPER | normal | system_grant | TRUE | Allows an app to set a static wallpaper. | -| ohos.permission.GET_WALLPAPER | system_basic | system_grant | TRUE | Allows an app to read wallpaper files. | -| ohos.permission.
CHANGE_ABILITY_ENABLED_STATE | system_basic | system_grant | TRUE | Allows an app to enable or disable an app or component. | -| ohos.permission.ACCESS_MISSIONS | system_basic | system_grant | TRUE | Allows an app to obtain information about running processes and mission in a mission stack. | -| ohos.permission.
CLEAN_BACKGROUND_PROCESSES | normal | system_grant | TRUE | Allows an app to clear background processes based on their bundle names. | -| ohos.permission.
KEEP_BACKGROUND_RUNNING | normal | system_grant | TRUE | Allows a Service ability to keep running in the background. | -| ohos.permission.
UPDATE_CONFIGURATION | system_basic | system_grant | TRUE | Allows an app to modify system settings. | -| ohos.permission.UPDATE_SYSTEM | system_basic | system_grant | TRUE | Allows an app to call the update APIs. | -| ohos.permission.FACTORY_RESET | system_basic | system_grant | TRUE | Allows an app to call the APIs for restoring factory settings. | -| ohos.permission.
GRANT_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to grant sensitive permissions to other apps. | -| ohos.permission.
REVOKE_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to revoke sensitive permissions granted to other apps. | -| ohos.permission.
GET_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to obtain the sensitive permissions that have been granted to other apps. | -| ohos.permission.INTERACT_
ACROSS_LOCAL_ACCOUNTS_EXTENSION | system_core | system_grant | TRUE | Allows an app to set the attributes of apps of other users. | -| ohos.permission.LISTEN_BUNDLE_CHANGE | system_basic | system_grant | TRUE | Allows an app to listen for changes in other apps, when they are installed, updated, or uninstalled. | -| ohos.permission.GET_BUNDLE_INFO | normal | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | -| ohos.permission.ACCELEROMETER | normal | system_grant | TRUE | Allows an app to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. | -| ohos.permission.GYROSCOPE | normal | system_grant | TRUE | Allows an app to read data from a gyroscope sensor or uncalibrated gyroscope sensor. | -| ohos.permission.
GET_BUNDLE_INFO_PRIVILEGED | system_basic | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | -| ohos.permission.INSTALL_BUNDLE | system_core | system_grant | TRUE | Allows an app to install and uninstall other apps. | -| ohos.permission.MANAGE_SHORTCUTS | system_core | system_grant | TRUE | Allows an app to query and start shortcuts of other apps.| -| ohos.permission.radio.ACCESS_FM_AM | system_core | system_grant | TRUE | Allows an app to access radio services. | -| ohos.permission.SET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to change the telephone state. | -| ohos.permission.
START_ABILITIES_FROM_BACKGROUND | system_basic | system_grant | TRUE | Allows an app to start Feature abilities in the background. | -| ohos.permission.BUNDLE_ACTIVE_INFO | system_basic | system_grant | TRUE | Allows an app to obtain how long other apps have been running in the foreground or background. | -| ohos.permission.
START_INVISIBLE_ABILITY | system_core | system_grant | TRUE | Allows an app to start an invisible ability. | -| ohos.permission.sec.ACCESS_UDID | system_basic | system_grant | TRUE | Allows an app to obtain the Unified Device ID (UDID). | -| ohos.permission.
LAUNCH_DATA_PRIVACY_CENTER | system_basic | system_grant | TRUE | Allows an app to switch from its privacy statement page to the Data & privacy page. | -| ohos.permission.MANAGE_MEDIA_RESOURCES | system_basic | system_grant | TRUE | Allows an app to obtain and manage the media resources that are being played on the device.| -| ohos.permission.PUBLISH_AGENT_REMINDER | normal | system_grant | TRUE | Allows an app to use agent-powered reminders. | -| ohos.permission.
CONTROL_TASK_SYNC_ANIMATOR | system_core | system_grant | TRUE | Allows apps to use sync task animations. | -| ohos.permission.INPUT_MONITORING | system_core | system_grant | TRUE | Allows an app to listen for input events. Only the system signature apps can apply for this permission. | -| ohos.permission.MANAGE_MISSIONS | system_core | system_grant | TRUE | Allows an app to manage ability mission stacks. | -| ohos.permission.
NOTIFICATION_CONTROLLER | system_core | system_grant | TRUE | Allows an app to manage and subscribe to notifications. | -| ohos.permission.CONNECTIVITY_INTERNAL | system_basic | system_grant | TRUE | Allows an app to obtain network information or modify network settings. | -| ohos.permission.SET_ABILITY_CONTROLLER | system_basic | system_grant | TRUE | Allows an app to set the start and stop of an ability. | -| ohos.permission.USE_USER_IDM | system_basic | system_grant | FALSE | Allows an app to access the system identity credential information. | -| ohos.permission.MANAGE_USER_IDM | system_basic | system_grant | FALSE | Allows an app to use the system identity credential management capability to enroll, modify, and delete PINs, face images, and fingerprints.| -| ohos.permission.ACCESS_BIOMETRIC | normal | system_grant | TRUE | Allows an app to use biometric recognition for identity authentication. | -| ohos.permission.
ACCESS_USER_AUTH_INTERNAL | system_basic | system_grant | FALSE | Allows an app to use the system identity authentication capability to authenticate or identify users. | -| ohos.permission.ACCESS_PIN_AUTH | system_basic | system_grant | FALSE | Allows a system app to call the PIN input APIs to present a password input dialog box for users.| -| ohos.permission.GET_RUNNING_INFO | system_basic | system_grant | TRUE | Allows an app to obtain running status information. | -| ohos.permission.CLEAN_APPLICATION_DATA | system_basic | system_grant | TRUE | Allows an app to clear app data. | -| ohos.permission.RUNNING_STATE_OBSERVER | system_basic | system_grant | TRUE | Allows an app to observe the app status. | -| ohos.permission.CAPTURE_SCREEN | system_core | system_grant | TRUE | Allows an app to take screenshots. | -| ohos.permission.GET_WIFI_INFO | normal | system_grant | TRUE | Allows an app to obtain WLAN information. | -| ohos.permission.GET_WIFI_INFO_INTERNAL | system_core | system_grant | TRUE | Allows an app to obtain WLAN information. | -| ohos.permission.SET_WIFI_INFO | normal | system_grant | TRUE | Allows an app to set WLAN devices. | -| ohos.permission.GET_WIFI_PEERS_MAC | system_core | system_grant | TRUE | Allows an app to obtain the MAC address of the peer WLAN or Bluetooth device. | -| ohos.permission.GET_WIFI_LOCAL_MAC | system_basic | system_grant | TRUE | Allows an app to obtain the MAC address of the local WLAN or Bluetooth device. | -| ohos.permission.GET_WIFI_CONFIG | system_basic | system_grant | TRUE | Allows an app to obtain the WLAN configuration. | -| ohos.permission.SET_WIFI_CONFIG | system_basic | system_grant | TRUE | Allows an app to set WLAN information. | -| ohos.permission.
MANAGE_WIFI_CONNECTION | system_core | system_grant | TRUE | Allows an app to manage WLAN connections. | -| ohos.permission.MANAGE_WIFI_HOTSPOT | system_core | system_grant | TRUE | Allows an app to enable or disable Wi-Fi hotspots. | -| ohos.permission.GET_ALL_APP_ACCOUNTS | system_core | system_grant | FALSE | Allows an app to obtain all app account information. | -| ohos.permission.MANAGE_SECURE_SETTINGS | system_basic | system_grant | TRUE | Allows an app to modify security settings. | -| ohos.permission.READ_DFX_SYSEVENT | system_basic | system_grant | FALSE | Allows an app to obtain all app account information. | -| ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN | system_core | system_grant | TRUE | Allows an app to activate the device administrator app. | -| ohos.permission.SET_ENTERPRISE_INFO | system_basic | system_grant | TRUE | Allows the device administrator app to set enterprise information. | -| ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT | system_basic | system_grant | TRUE | Allows the device administrator app to subscribe to management events. | -| ohos.permission.ENTERPRISE_SET_DATETIME | system_basic | system_grant | TRUE | Allows the device administrator app to set the system time. | -| ohos.permission.ENTERPRISE_GET_DEVICE_INFO | system_basic | system_grant | TRUE | Allows the device administrator app to obtain device information. | -| ohos.permission.NFC_TAG | normal | system_grant | FALSE | Allows an app to read NFC tag information. | -| ohos.permission.NFC_CARD_EMULATION | normal | system_grant | FALSE | Allows an app to implement card emulation. | -| ohos.permission.PERMISSION_USED_STATS | system_basic | system_grant | TRUE | Allows a system application to access the permission usage records. | -| ohos.permission.
NOTIFICATION_AGENT_CONTROLLER | system_core | system_grant | TRUE | Allows an app to send agent-powered notifications. | -| ohos.permission.ANSWER_CALL | system_basic | user_grant | TRUE | Allows an app to answer incoming calls. | -| ohos.permission.READ_CALENDAR | normal | user_grant | TRUE | Allows an app to read calendar data. | -| ohos.permission.READ_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to read call logs. | -| ohos.permission.READ_CELL_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read cell broadcast messages received by the device. | -| ohos.permission.READ_CONTACTS | system_basic | user_grant | TRUE | Allows an app to read contacts. | -| ohos.permission.READ_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read messages. | -| ohos.permission.RECEIVE_MMS | system_basic | user_grant | TRUE | Allows an app to receive and process MMS messages. | -| ohos.permission.RECEIVE_SMS | system_basic | user_grant | TRUE | Allows an app to receive and process SMS messages. | -| ohos.permission.RECEIVE_WAP_MESSAGES | system_basic | user_grant | TRUE | Allows an app to receive and process WAP messages. | -| ohos.permission.MICROPHONE | normal | user_grant | TRUE | Allows an app to access the microphone. | -| ohos.permission.SEND_MESSAGES | system_basic | user_grant | TRUE | Allows an app to send messages. | -| ohos.permission.WRITE_CALENDAR | normal | user_grant | TRUE | Allows an app to add, remove, and modify calendar events. | -| ohos.permission.WRITE_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify call logs. | -| ohos.permission.WRITE_CONTACTS | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify contacts. | -| ohos.permission.DISTRIBUTED_DATASYNC | normal | user_grant | TRUE | Allows an app to exchange data with other devices. | -| ohos.permission.MANAGE_VOICEMAIL | system_basic | user_grant | TRUE | Allows an app to leave messages in the voice mailbox. | -| ohos.permission.
LOCATION_IN_BACKGROUND | normal | user_grant | FALSE | Allows an app running in the background to obtain the device location. | -| ohos.permission.LOCATION | normal | user_grant | TRUE | Allows an app to obtain the device location. | -| ohos.permission.APPROXIMATELY_LOCATION | normal | user_grant | FALSE | Allows an app to obtain the approximate location information of a device. | -| ohos.permission.MEDIA_LOCATION | normal | user_grant | TRUE | Allows an app to access geographical locations in the user's media file. | -| ohos.permission.CAMERA | normal | user_grant | TRUE | Allows an app to use the camera to take photos and record videos. | -| ohos.permission.READ_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from the user's external storage. | -| ohos.permission.WRITE_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from and write media files into the user's external storage. | -| ohos.permission.ACTIVITY_MOTION | normal | user_grant | TRUE | Allows an app to read the current workout status of the user. | -| ohos.permission.READ_HEALTH_DATA | normal | user_grant | TRUE | Allows an app to read the health data of the user. | -| ohos.permission.GET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | Allows an app to query default apps. | -| ohos.permission.SET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | Allows an app to set and reset default apps. | -| ohos.permission.
MANAGE_DISPOSED_APP_STATUS | system_core | system_grant | TRUE | Allows an app to set and query the app handling state. | -| ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | Allows an app to query the unique identifier of a device. | -| ohos.permission.DUMP | system_core | system_grant | TRUE | Allows the basic system information and SA service information to be exported. | -| ohos.permission.
DISTRIBUTED_SOFTBUS_CENTER | system_basic | system_grant | FALSE | Allows networking between different devices. | -| ohos.permission.ACCESS_DLP_FILE | system_core | system_grant | TRUE | Allows configuration and management of the permissions on .dlp files. | -| ohos.permission.PROVISIONING_MESSAGE | system_core | system_grant | TRUE | Allows the Super Device Manager application to be activated. | -| ohos.permission.
ACCESS_SYSTEM_SETTINGS | system_basic | system_grant | TRUE | Allows an app to access or start system **Settings**. | -| ohos.permission.READ_IMAGEVIDEO | system_basic | user_grant | TRUE | Allows access to the images or video files in a user's directory. | -| ohos.permission.READ_AUDIO | system_basic | user_grant | TRUE | Allows access to the audio files in a user's directory. | -| ohos.permission.READ_DOCUMENT | system_basic | user_grant | TRUE | Allows access to the files in a user's directory. | -| ohos.permission.WRITE_IMAGEVIDEO | system_basic | user_grant | TRUE | Allows modification to the images or video files in a user's directory. | -| ohos.permission.WRITE_AUDIO | system_basic | user_grant | TRUE | Audio modification to the audio files in a user's directory. | -| ohos.permission.WRITE_DOCUMENT | system_basic | user_grant | TRUE | Allows modification to the files in a user's directory. | -| ohos.permission.
ABILITY_BACKGROUND_COMMUNICATION | system_basic | system_grant | TRUE | Allows an app to start the Ability component in the background and establish a connection with it. | -| ohos.permission.
securityguard.REPORT_SECURITY_INFO | system_basic | system_grant | FALSE | Allows an app to report risk data for security guard. | -| ohos.permission.
securityguard.REQUEST_SECURITY_MODEL_RESULT | system_basic | system_grant | TRUE | Allows an app to obtain the device risk status. | -| ohos.permission.
securityguard.REQUEST_SECURITY_EVENT_INFO | system_core | system_grant | FALSE | Allows an app to obtain detailed risk data. | -| ohos.permission.
READ_ACCESSIBILITY_CONFIG | system_basic | system_grant | FALSE | Allows an app to read the accessibility configuration. | -| ohos.permission.
WRITE_ACCESSIBILITY_CONFIG | system_basic | system_grant | FALSE | Allows an app to set the accessibility configuration. | -| ohos.permission.
ACCESS_CERT_MANAGER_INTERNAL | system_basic | system_grant | FALSE | Allows an app to install, uninstall, enable, and disable certificates and credentials. | -| ohos.permission.
ACCESS_CERT_MANAGER | normal | system_grant | FALSE | Allows an app to manage private credentials and query certificate status. | -| ohos.permission.
ACCESS_PUSH_SERVICE | system_basic | system_grant | TRUE | Allows an app to to access the Ability of the push service. | -| ohos.permission.
RECEIVER_STARTUP_COMPLETED | system_basic | system_grant | FALSE | Allows an app to subscribe to the startup broadcast. | -| ohos.permission.
MANAGE_CAMERA_CONFIG | system_basic | system_grant | FALSE | Allows an app to enable or disable cameras globally. | -| ohos.permission.READ_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | Allows an app to read all calendar information. | -| ohos.permission.WRITE_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | Allows an app to add, remove, or change all calendar events. | -| ohos.permission.ENFORCE_USER_IAM | system_core | system_grant | TRUE | Allows an SA to delete user information from the IAM subsystem without a token. | -| ohos.permission.ACCESS_AUTH_RESPOOL | system_core | system_grant | TRUE | Allows an SA to register the executor. | -| ohos.permission.MOUNT_UNMOUNT_MANAGER | system_basic | system_grant | FALSE | Allows an app to mount and unmount external cards. | -| ohos.permission.MOUNT_FORMAT_MANAGER | system_basic | system_grant | FALSE | Allows an app to format external cards. | -| ohos.permission.STORAGE_MANAGER | system_basic | system_grant | TRUE | Allows an app to call the interfaces of the Storage Manager service to query space statistics and volume information. | -| ohos.permission.BACKUP | system_basic | system_grant | TRUE | Allows an app to have backup and restore capabilities. | -| ohos.permission.FILE_ACCESS_MANAGER | system_basic | system_grant | TRUE | Allows a file management app to access user data files through the FAF. | -| ohos.permission.MANAGE_AUDIO_CONFIG | system_basic | system_grant | TRUE | Allows an app to to mute microphones globally. | +# Application Permission List + +Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine the permissions required for your application. + +For details about how to apply for required permissions, see [Permission Application Guide](accesstoken-guidelines.md). + +## ohos.permission.USE_BLUETOOTH + +Allows an application to access Bluetooth configurations. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISCOVER_BLUETOOTH + +Allows an application to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_BLUETOOTH + +Allows an application to pair with a Bluetooth device and access the contacts or messages of the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERNET + +Allows an application to access the Internet. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MODIFY_AUDIO_SETTINGS + +Allows an application to modify audio settings. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_NOTIFICATION_POLICY + +Allows an application to access the notification policy on the device. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.GET_TELEPHONY_STATE + +Allows an application to read telephony information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REQUIRE_FORM + +Allows an application to obtain widgets. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_NETWORK_INFO + +Allows an application to obtain network information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PLACE_CALL + +Allows an application to make calls without starting the dialer. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_NETWORK_INFO + +Allows an application to set data network information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REMOVE_CACHE_FILES + +Allows the cache of the specified application to be cleared. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REBOOT + +Allows an application to restart the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUNNING_LOCK + +Allows an application to obtain a running lock. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TIME + +Allows an application to set the system time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TIME_ZONE + +Allows an application to set the system time zone. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DOWNLOAD_SESSION_MANAGER + +Allows an application to manage download sessions. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.COMMONEVENT_STICKY + +Allows an application to publish sticky common events. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SYSTEM_FLOAT_WINDOW + +Allows an application to be displayed in a floating window on top of other applications. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PRIVACY_WINDOW + +Allows an application to set screens that cannot be captured or recorded. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.POWER_MANAGER + +Allows an application to hibernate or wake up the device by calling an API. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REFRESH_USER_ACTION + +Allows an application to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.POWER_OPTIMIZATION + +Allows an application to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REBOOT_RECOVERY + +Allows an application to restart the device and enter Recovery mode. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_LOCAL_ACCOUNTS + +Allows an application to manage local user accounts. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +Allows access between multiple OS accounts. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.VIBRATE + +Allows an application to control vibration. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECT_IME_ABILITY + +Allows an application to bind the InputMethodAbility. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECT_SCREEN_SAVER_ABILITY + +Allows an application to bind the ScreenSaverAbility. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_SCREEN_SAVER + +Allows an application to read the screen saver information, such as the list of screen savers that have been installed and the activated one. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_SCREEN_SAVER + +Allows an application to modify the screen saver information, such as activating and previewing a screen saver. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WALLPAPER + +Allows an application to set a static wallpaper. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WALLPAPER + +Allows an application to read wallpaper files. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +Allows an application to enable or disable an application or component. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_MISSIONS + +Allows an application to obtain information about running processes and mission in a mission stack. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CLEAN_BACKGROUND_PROCESSES + +Allows an application to clear background processes based on their bundle names. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.KEEP_BACKGROUND_RUNNING + +Allows a Service ability to keep running in the background. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.UPDATE_CONFIGURATION + +Allows an application to modify system settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.UPDATE_SYSTEM + +Allows an application to call the update APIs. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.FACTORY_RESET + +Allows an application to call the API for restoring factory settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GRANT_SENSITIVE_PERMISSIONS + +Allows an application to grant sensitive permissions to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REVOKE_SENSITIVE_PERMISSIONS + +Allows an application to revoke sensitive permissions granted to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_SENSITIVE_PERMISSIONS + +Allows an application to obtain the sensitive permissions that have been granted to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + +Allows an application to set the attributes of applications of other users. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.LISTEN_BUNDLE_CHANGE + +Allows an application to listen for changes in other applications, when they are installed, updated, or uninstalled. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_BUNDLE_INFO + +Allows an application to query information about another application. This permission applies only to third-party applications. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +Allows an application to query information about other applications at the same time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCELEROMETER + +Allows an application to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GYROSCOPE + +Allows an application to read data from a gyroscope sensor or uncalibrated gyroscope sensor. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INSTALL_BUNDLE + +Allows an application to install and uninstall other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_SHORTCUTS + +Allows an application to query and start shortcuts of other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.radio.ACCESS_FM_AM + +Allows an application to access radio services. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TELEPHONY_STATE + +Allows an application to change the telephone state. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.START_ABILIIES_FROM_BACKGROUND + +Allows an application to start Feature abilities in the background. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.BUNDLE_ACTIVE_INFO + +Allows an application to obtain how long other applications have been running in the foreground or background. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.START_INVISIBLE_ABILITY + +Allows an application to start an invisible ability. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.sec.ACCESS_UDID + +Allows an application to obtain the Unified Device ID (UDID). + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.LAUNCH_DATA_PRIVACY_CENTER + +Allows an application to switch from its privacy statement page to the Data & privacy page. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_MEDIA_RESOURCES + +Allows an application to obtain and manage the media resources that are being played on the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PUBLISH_AGENT_REMINDER + +Allows an application to use agent-powered reminders. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONTROL_TASK_SYNC_ANIMATOR + +Allows applications to use sync task animations. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INPUT_MONITORING + +Allows an application to listen for input events. Only the system signed applications can apply for this permission. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_MISSIONS + +Allows an application to manage ability mission stacks. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NOTIFICATION_CONTROLLER + +Allows an application to manage and subscribe to notifications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECTIVITY_INTERNAL + +Allows an application to obtain network information or modify network settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_ABILITY_CONTROLLER + +Allows an application to set the start and stop of an ability. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.USE_USER_IDM + +Allows an application to access the system identity credential information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_USER_IDM + +Allows an application to use the system identity credential management capability to enroll, modify, and delete PINs, face images, and fingerprints. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_BIOMETRIC + +Allows an application to use biometric recognition for identity authentication. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_USER_AUTH_INTERNAL + +Allows an application to use the system identity authentication capability to authenticate or identify users. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_PIN_AUTH + +Allows a system application to call the PIN input APIs to present a password input dialog box for users. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.GET_RUNNING_INFO + +Allows an application to obtain running status information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CLEAN_APPLICATION_DATA + +Allows an application to clear application data. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUNNING_STATE_OBSERVER + +Allows an application to observe the application status. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CAPTURE_SCREEN + +Allows an application to take screenshots. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_INFO + +Allows an application to obtain WLAN information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_INFO_INTERNAL + +Allows an application to obtain WLAN information. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WIFI_INFO + +Allows an application to set WLAN devices. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_PEERS_MAC + +Allows an application to obtain the MAC address of the peer WLAN or Bluetooth device. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_LOCAL_MAC + +Allows an application to obtain the MAC address of the local WLAN or Bluetooth device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_CONFIG + +Allows an application to obtain the WLAN configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WIFI_CONFIG + +Allows an application to set WLAN information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_WIFI_CONNECTION + +Allows an application to manage WLAN connections. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_WIFI_HOTSPOT + +Allows an application to enable or disable Wi-Fi hotspots. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_ALL_APP_ACCOUNTS + +Allows an application to obtain all application account information. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_SECURE_SETTINGS + +Allows an application to modify security settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_DFX_SYSEVENT + +Allows an application to access system event logging data. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +Allows an application to activate the device administrator app. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_ENTERPRISE_INFO + +Allows the device administrator application to set enterprise information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT + +Allows the device administrator application to subscribe to management events. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_SET_DATETIME + +Allows the device administrator application to set the system time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_GET_DEVICE_INFO + +Allows the device administrator application to obtain device information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NFC_TAG + +Allows an application to read NFC tag information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.NFC_CARD_EMULATION + +Allows an application to implement card emulation. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.PERMISSION_USED_STATS + +Allows a system application to access the permission usage records. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +Allows an application to send agent-powered notifications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ANSWER_CALL + +Allows an application to answer incoming calls. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CALENDAR + +Allows an application to read calendar data. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CALL_LOG + +Allows an application to read call logs. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CELL_MESSAGES + +Allows an application to read cell broadcast messages received by the device. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CONTACTS + +Allows an application to read contacts. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_MESSAGES + +Allows an application to read messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_MMS + +Allows an application to receive and process MMS messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_SMS + +Allows an application to receive and process SMS messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_WAP_MESSAGES + +Allows an application to receive and process WAP messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.MICROPHONE + +Allows an application to access the microphone. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.SEND_MESSAGES + +Allows an application to send messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CALENDAR + +Allows an application to add, remove, and modify calendar events. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CALL_LOG + +Allows an application to add, remove, and modify call logs. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CONTACTS + +Allows an application to add, remove, and modify contacts. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISTRIBUTED_DATASYNC + +Allows an application to exchange data with other devices. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_VOICEMAIL + +Allows an application to leave messages in the voice mailbox. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.LOCATION_IN_BACKGROUND + +Allows an application running in the background to obtain the device location. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: FALSE + +## ohos.permission.LOCATION + +Allows an application to obtain the device location. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.APPROXIMATELY_LOCATION + +Allows an application to obtain the approximate location information of a device. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: FALSE + +## ohos.permission.MEDIA_LOCATION + +Allow an application to access geographical locations in the user's media file. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.CAMERA + +Allows an application to use the camera to take photos and record videos. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_MEDIA + +Allows an application to read media files from the user's external storage. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_MEDIA + +Allows an application to read media files from and write media files into the user's external storage. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACTIVITY_MOTION + +Allows an application to read the current workout status of the user. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_HEALTH_DATA + +Allows an application to read the health data of the user. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_DEFAULT_APPLICATION + +Allows an application to query default applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_DEFAULT_APPLICATION + +Allows an application to set and reset default applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_DISPOSED_APP_STATUS + +Allows an application to set and query the application handling state. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_IDS + +Allows an application to query the unique identifier of a device. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DUMP + +Allows the basic system information and SA service information to be exported. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISTRIBUTED_SOFTBUS_CENTER + +Allows networking between different devices. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_DLP_FILE + +Allows configuration and management of the permissions on .dlp files. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PROVISIONING_MESSAGE + +Allows the Super Device Manager application to be activated. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_SYSTEM_SETTINGS + +Allows an application to access or start system **Settings**. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_IMAGEVIDEO + +Allows access to the images or video files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_AUDIO + +Allows access to the audio files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_DOCUMENT + +Allows access to the files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_IMAGEVIDEO + +Allows modification to the images or video files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_AUDIO + +Audio modification to the audio files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_DOCUMENT + +Allows modification to the files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ABILITY_BACKGROUND_COMMUNICATION + +Allows an application to start the Ability component in the background and establish a connection with it. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.securityguard.REPORT_SECURITY_INFO + +Allows an application to report risk data for security guard. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.securityguard.REQUEST_SECURITY_MODEL_RESULT + +Allows an application to obtain the device risk status. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO + +Allows an application to obtain detailed risk data. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.READ_ACCESSIBILITY_CONFIG + +Allows an application to read the accessibility configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.WRITE_ACCESSIBILITY_CONFIG + +Allows an application to set the accessibility configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_CERT_MANAGER_INTERNAL + +Allows an application to install, uninstall, enable, and disable certificates and credentials. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_CERT_MANAGER + +Allows an application to manage private credentials and query certificate status. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_PUSH_SERVICE + +Allows an application to to access the Ability of the push service. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVER_STARTUP_COMPLETED + +Allows an application to subscribe to the startup broadcast. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_CAMERA_CONFIG + +Allows an application to enable or disable cameras globally. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.READ_WHOLE_CALENDAR + +Allows an application to read all calendar information. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_WHOLE_CALENDAR + +Allows an application to add, remove, or change all calendar events. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENFORCE_USER_IAM + +Allows an SA to delete user information from the IAM subsystem without a token. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_AUTH_RESPOOL + +Allows an SA to register the executor. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MOUNT_UNMOUNT_MANAGER + +Allows an application to mount and unmount external cards. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MOUNT_FORMAT_MANAGER + +Allows an application to format external cards. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.STORAGE_MANAGER + +Allows an application to call the interfaces of the Storage Manager service to query space statistics and volume information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.BACKUP + +Allows an application to have backup and restore capabilities. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.FILE_ACCESS_MANAGER + +Allows a file management application to access user data files through the FAF. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_AUDIO_CONFIG + +Allows an application to to mute microphones globally. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_SERVICE_DM + +Allows a system application to obtain the authentication and networking capability of distributed devices. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUN_ANY_CODE + +Allows an application to run unsigned code. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PUBLISH_SYSTEM_COMMON_EVENT + +Allows an application to publish system common events. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE diff --git a/en/application-dev/security/userauth-overview.md b/en/application-dev/security/userauth-overview.md index f3e6a9a9042ad36f0111f3679f0084be4c6fc352..d7082741a06601e4b8009fd2f4388c4c64446643 100644 --- a/en/application-dev/security/userauth-overview.md +++ b/en/application-dev/security/userauth-overview.md @@ -16,7 +16,7 @@ Facial recognition establishes a secure channel between a camera and a trusted e Facial characteristics are stored in the TEE, which uses strong cryptographic algorithms to encrypt and protect the integrity of facial characteristics. The collected and stored facial characteristics will not be transferred out of the TEE without user authorization. This ensures that system or third-party applications cannot obtain facial characteristics, or send or back them up to any external storage medium. -## Limitations and Constraints +## Constraints - OpenHarmony only supports facial recognition and local authentication, and does not support an authentication UI. - To use biometric recognition, a device must have a camera with a face image pixel greater than 100x100. diff --git a/en/device-dev/device-test/Readme.md b/en/device-dev/device-test/Readme-EN.md similarity index 100% rename from en/device-dev/device-test/Readme.md rename to en/device-dev/device-test/Readme-EN.md diff --git a/en/device-dev/security/security-guidelines-overall.md b/en/device-dev/security/security-guidelines-overall.md index e3c6685ab0b5052b7e15780e0c1f45381e9479cc..d7d9d7009d76d0b1a12111f72ede57ce945a52c9 100644 --- a/en/device-dev/security/security-guidelines-overall.md +++ b/en/device-dev/security/security-guidelines-overall.md @@ -37,7 +37,7 @@ This environment combines chip security and system security features with upper- Since some dedicated hardware resources are used for data encryption/decryption, the CPU can concurrently execute other computing tasks, which greatly improves performance and reduces the CPU load. In addition, a well-designed hardware key engine protects keys from leak even if the software is cracked and even defends against electromagnetic and radiation attacks from physical channels. - OpenHarmony devices support the hardware key engine, which allows OpenHarmony to perform computing tasks such as data encryption and decryption, certificate signature verification, and hash value calculation. The hardware key engine supports popular algorithms such as Advanced Encryption Standard (AES) and Rivest-Shamir-Adleman (RSA). + OpenHarmony devices support the hardware key engine, which allows OpenHarmony to perform computing tasks such as data encryption and decryption, certificate signature verification, and hash value calculation. The hardware key engine supports popular algorithms such as Advanced Encryption Standard (AES) and Rivest-Shamir-Adleman (RSA). ### Recommended Practices @@ -101,7 +101,7 @@ For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recom OpenHarmony Universal KeyStore (HUKS) provides key and certificate management. For OpenHarmony, it mainly provides key management for HiChain (device identity authentication platform). The figure below shows the HUKS functions. -**Figure 3** HUKS functions +**Figure 3** HUKS functions ![](figure/huks-functions.png) @@ -141,7 +141,7 @@ To use the device certification function, it is recommended that you use HiChain ## Device Interconnection Security -To ensure secure transmit of user data between devices, a trust relationship and a secure data transmission channel must be established between the devices. The figure below illustrates how an IoT controller and an IoT device establish a trust relationship. +To ensure secure transmit of user data between devices, a trust relationship and a secure data transmission channel must be established between the devices. The following figure shows how an IoT controller and an IoT device establish a trust relationship. **Figure 4** Process of establishing a trust relationship between devices @@ -169,7 +169,7 @@ To ensure secure transmit of user data between devices, a trust relationship and When an IoT controller and an IoT device establish a trust relationship, they exchange identifiers. - During this process, the user needs to enter or scan the PIN provided by the IoT device on the IoT controller. PIN is either dynamically generated if the IoT device has a screen, or preset by the manufacturer if it does not have a screen. A PIN can be a number or a QR code. Then the IoT controller and IoT device perform authentication and session key exchange based on password authenticated key exchange (PAKE), and use the session key to encrypt the channel for exchanging identity public keys. + During this process, the user needs to enter or scan the PIN provided by the IoT device on the IoT controller. PIN is either dynamically generated if the IoT device has a screen, or preset by the manufacturer if it does not have a screen. A PIN can be a number or a QR code. Then the IoT controller and IoT device perform authentication and session key exchange based on password authenticated key exchange (PAKE), and use the session key to encrypt the channel for exchanging identity public keys. - Secure communication between the IoT controller and IoT device @@ -186,13 +186,16 @@ To ensure secure transmit of user data between devices, a trust relationship and After developing and debugging an OpenHarmony application, sign the application installation package using a private key, which matches a public key. Generally, the OEM generates a public/private key pair, presets the public key in the device, and stores the private key on a local server that is not connected to the Internet to prevent private key leakage. After you finish developing an application, you can use an external device (such as a USB flash drive) to upload the installation package to the server where the private key is stored, calculate the signature, and download the signature to the external device. During application installation, the hash value of the bundle is calculated using the SHA-256 algorithm. The hash value, together with the signature and preset public key, is used for authentication. The application can be installed only after the authentication is successful. - In addition, the application source must be verified to ensure that the application is from a valid developer. As a developer, you must apply for a development certificate and use it to sign the application you have developed. During application installation, the upper-level certificate stored on the device is used to verify the signature to ensure validity of the developer. + In addition, the application source must be verified to ensure that the application is from a valid developer. As a developer, you must apply for a development certificate and use it to sign the application you have developed. During application installation, the upper-level certificate stored on the device is used to verify the signature to ensure validity of the developer. + - Application permission control - OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an application, you need to declare the sensitive permissions that the application may require in the **profile.json** file. The permissions can be static or dynamic. Static permissions need to be registered during application installation, and dynamic permissions can be obtained only upon user authorization. Authorization modes include system settings, manual authorization by applications, and others. In addition, application signature control is used to ensure that the application installation package has been confirmed by the device vendor. + OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an application, you need to declare the sensitive permissions that the application may require in the application configuration file. The permissions can be static or dynamic. Static permissions need to be registered during application installation, and dynamic permissions can be obtained only upon user authorization. Authorization modes include system settings, manual authorization by applications, and others. In addition, application signature control is used to ensure that the application installation package has been confirmed by the device vendor. + + - **Table 1** OpenHarmony system permissions +**Table 1** OpenHarmony system permissions | Permission| **Authorization Mode**| **Description**| | -------- | -------- | -------- | @@ -207,7 +210,11 @@ To ensure secure transmit of user data between devices, a trust relationship and | ohos.permission.DISTRIBUTED_DATASYNC | user_grant (dynamic permission)| Allows an application to manage distributed data transmission.| | ohos.permission.DISTRIBUTED_VIRTUALDEVICE | user_grant (dynamic permission)| Allows an application to use distributed virtualization features.| - ### Recommended Practices -When developing an application, determine the permissions required by your application and register the permissions in the **profile.json** file. Sign the application to ensure that the devices on which the application will be installed can verify its integrity and source. +When developing an application, determine the permissions required by your application and register the permissions in the application configuration file. Sign the application to ensure that the devices on which the application will be installed can verify its integrity and source. + +> **NOTE** +> +> The application configuration file varies depending on the application model. It is **config.json** for the application based on the FA model and **module.json5** for the application based on the stage mode. For details about the application models, see [Interpretation of the Application Model](../../application-dev/application-models/application-model-description.md). + diff --git a/en/device-dev/subsystems/subsys-app-privilege-config-guide.md b/en/device-dev/subsystems/subsys-app-privilege-config-guide.md index c795eb7d773cc6b37fed2dbf01582247e52e92be..665652b23e1832716680e14d5552c66aec744062 100644 --- a/en/device-dev/subsystems/subsys-app-privilege-config-guide.md +++ b/en/device-dev/subsystems/subsys-app-privilege-config-guide.md @@ -24,7 +24,7 @@ General application privileges are privileges available to applications on all t ### Configuration -1. In the [HarmonyAppProvision file](https://gitee.com/openharmony/docs/blob/master/en/application-dev/quick-start/app-provision-structure.md), configure the general privileges in the **app-privilege-capabilities** field. +1. In the [HarmonyAppProvision file](../../application-dev/security/app-provision-structure.md), configure the general privileges in the **app-privilege-capabilities** field. 2. Use the signing tool hapsigner to sign the HarmonyAppProvision file and generate a **.p7b** file. 3. Use the **.p7b** file to sign the HAP. diff --git a/en/device-dev/subsystems/subsys-security-overview.md b/en/device-dev/subsystems/subsys-security-overview.md index 2ed46817e0066bed27c8f3be692451efb43a20b6..68570ac7f682e351efd15d280c652bdc0ae2890b 100644 --- a/en/device-dev/subsystems/subsys-security-overview.md +++ b/en/device-dev/subsystems/subsys-security-overview.md @@ -10,7 +10,7 @@ The OpenHarmony security subsystem provides security capabilities that make your - Application permission management - Application permissions determine what system resources and capabilities an application can access. During application development, you need to declare the permissions that the application may require in the profile.json file. Static permissions need to be registered during application installation, while dynamic permissions usually involve sensitive information and need users' dynamic authorization. + Application permissions determine what system resources and capabilities an application can access. During application development, you need to declare the permissions required by the application in the application configuration file. Static permissions need to be registered during application installation, while dynamic permissions usually involve sensitive information and need users' dynamic authorization. - Inter-process communication (IPC) authentication diff --git a/en/device-dev/subsystems/subsys-security-rightmanagement.md b/en/device-dev/subsystems/subsys-security-rightmanagement.md index 81c85a0c41d0feeceb069e88177185f79e7c28a8..2b7624cb3ba96e532252e5353770991b27b883b3 100644 --- a/en/device-dev/subsystems/subsys-security-rightmanagement.md +++ b/en/device-dev/subsystems/subsys-security-rightmanagement.md @@ -3,56 +3,56 @@ ## Working Principles -OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an app, you need to declare the sensitive permissions that the app requires in the **profile.json** file. The permissions can be static or dynamic. Static permissions are registered during app installation, and dynamic permissions must be authorized by users. Authorization modes include system settings, manual authorization, and others. In addition, app signatures are used to ensure that the app installation packages have been confirmed by device vendors. +OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an application, you need to declare the sensitive permissions required by the application in the application configuration file. The permissions can be static or dynamic. Static permissions are registered during application installation, and dynamic permissions must be authorized by users. Authorization modes include system settings, manual authorization, and others. In addition, application signatures are used to ensure that the application installation packages have been confirmed by device vendors. **Table 1** OpenHarmony permission list - -| OpenHarmony Permission| Authorization Mode| Permission Description| -| -------- | -------- | -------- | -| ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant (static permission)| Allows an app to listen for app changes.| -| ohos.permission.GET_BUNDLE_INFO | system_grant (static permission)| Allows an app to obtain information about other apps.| -| ohos.permission.INSTALL_BUNDLE | system_grant (static permission)| Allows an app to install other apps.| -| ohos.permission.CAMERA | user_grant (dynamic permission)| Allows an app to use the camera to take photos and record videos at any time.| -| ohos.permission.MODIFY_AUDIO_SETTINGS | system_grant (static permission)| Allows an app to modify global audio settings, such as the volume and speaker.| -| ohos.permission.READ_MEDIA | user_grant (dynamic permission)| Allows an app to read users' favorite videos.| -| ohos.permission.MICROPHONE | user_grant (dynamic permission)| Allows an app to use the microphone for audio recording at any time.| -| ohos.permission.WRITE_MEDIA | user_grant (dynamic permission)| Allows an app to write users' favorite music.| -| ohos.permission.DISTRIBUTED_DATASYNC | user_grant (dynamic permission)| Allows an app to manage distributed data transmission.| -| ohos.permission.DISTRIBUTED_VIRTUALDEVICE | user_grant (dynamic permission)| Allows an app to use distributed virtualization features.| + + | **Permission**| **Authorization Mode**| **Description**| + | -------- | -------- | -------- | + | ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant (static permission)| Allows an application to listen for application changes.| + | ohos.permission.GET_BUNDLE_INFO | system_grant (static permission)| Allows an application to obtain information about other applications.| + | ohos.permission.INSTALL_BUNDLE | system_grant (static permission)| Allows an application to install other applications.| + | ohos.permission.CAMERA | user_grant (dynamic permission)| Allows an application to use the camera to take photos and record videos at any time.| + | ohos.permission.MODIFY_AUDIO_SETTINGS | system_grant (static permission)| Allows an application to modify global audio settings, such as the volume and speaker.| + | ohos.permission.READ_MEDIA | user_grant (dynamic permission)| Allows an application to read users' favorite videos.| + | ohos.permission.MICROPHONE | user_grant (dynamic permission)| Allows an application to use the microphone for audio recording at any time.| + | ohos.permission.WRITE_MEDIA | user_grant (dynamic permission)| Allows an application to write users' favorite music.| + | ohos.permission.DISTRIBUTED_DATASYNC | user_grant (dynamic permission)| Allows an application to manage distributed data transmission.| + | ohos.permission.DISTRIBUTED_VIRTUALDEVICE | user_grant (dynamic permission)| Allows an application to use distributed virtualization features.| > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> Static permission: a permission granted by the system during app installation. The sensitivity level of this type of permission is **system_grant**. > -> Dynamic permission: a permission granted by users during app running. The sensitivity level of this type of permission is **user_grant**. - +> 1. Static permission is a permission granted by the system during application installation. The sensitivity level of this type of permission is **system_grant**. Dynamic permission is a permission granted by users during application running. The sensitivity level of this type of permission is **user_grant**. +> +> 2. The application configuration file varies depending on the application model. It is **config.json** for the application based on the FA model and **module.json5** for the application based on the stage mode. For details about the application models, see [Interpretation of the Application Model](../../application-dev/application-models/application-model-description.md). ## When to Use -App permissions are required for software to access system resources and use system capabilities. When the functions and data related to user privacy are used, for example, when personal devices, such as cameras and microphones, are used or media files are read or written, OpenHarmony uses the app permission management component to protect the data and capabilities. +App permissions are required for software to access system resources and use system capabilities. When the functions and data related to user privacy are used, for example, when personal devices, such as cameras and microphones, are used or media files are read or written, OpenHarmony uses the application permission management component to protect the data and capabilities. -When developing a system application that requires a sensitive permission, you can call the corresponding API of the app permission management component to check whether the required permission is granted. If the permission is not granted, the app cannot use it. +When developing a system application that requires a sensitive permission, you can call the corresponding API of the application permission management component to check whether the required permission is granted. If the permission is not granted, the application cannot use it. ## Available APIs -The table below lists the APIs available for app permission management. These APIs can be called only by system applications and services. +The table below lists the APIs available for application permission management. These APIs can be called only by system applications and services. **Table 2** App permission management APIs | API| Description| | -------- | -------- | -| int CheckPermission(int uid, const char \*permissionName) | Checks whether the app with the specified UID has the permission to access system service APIs.| -| int CheckSelfPermission(const char \*permissionName) | Checks whether the caller has the permission to access system service APIs.| -| int QueryPermission(const char \*identifier, PermissionSaved \*\*permissions, int \*permNum) | Queries all permissions requested by the app and checks whether the requested permissions have been granted.| -| int GrantPermission(const char \*identifier, const char \*permName) | Grants a permission to the app.| -| int RevokePermission(const char \*identifier, const char \*permName) | Revokes a permission from the app.| -| int GrantRuntimePermission(int uid, const char \*permissionName) | Grants a runtime permission to the app.| -| int RevokeRuntimePermission(int uid, const char \*permissionName) | Revokes a runtime permission from the app.| +| int CheckPermission(int uid, const char \*permissionName) | Checks whether the application with the specified UID has the permission to access system service APIs.| +| int CheckSelfPermission(const char \*permissionName) | Checks whether the caller has the permission to access system service APIs.| +| int QueryPermission(const char \*identifier, PermissionSaved \*\*permissions, int \*permNum) | Queries all permissions requested by the application and checks whether the requested permissions have been granted.| +| int GrantPermission(const char \*identifier, const char \*permName) | Grants a permission to the app.| +| int RevokePermission(const char \*identifier, const char \*permName) | Revokes a permission from the app.| +| int GrantRuntimePermission(int uid, const char \*permissionName) | Grants a runtime permission to the app.| +| int RevokeRuntimePermission(int uid, const char \*permissionName) | Revokes a runtime permission from the app.| ## How to Develop -The following uses the BMS as an example to describe the app permission development. Before you start, declare the required sensitive permissions in the **config.json** file. During app installation, the BMS calls APIs of the app permission management component to check whether the required permissions are available. If yes, the installation proceeds; otherwise, the installation fails. +The following uses the BMS as an example to describe the application permission development. Before you start, declare the required sensitive permissions in the **config.json** file. During application installation, the BMS calls APIs of the application permission management component to check whether the required permissions are available. If yes, the installation proceeds; otherwise, the installation fails. 1. Declare the required permission (**ohos.permission.INSTALL_BUNDLE**) in the **config.json** file. If the FA model is used, declare the permission in the **config.json** file. The following is an example: @@ -135,7 +135,7 @@ The following uses the BMS as an example to describe the app permission developm } ``` -2. When an app is to be installed, the BMS checks whether it has the permission to install the app. For example, the BMS calls **CheckPermission** with **ohos.permission.INSTALL_BUNDLE** as an input parameter. If it has the permission, the installation proceeds; otherwise, the installation fails. +2. When an application is to be installed, the BMS checks whether it has the permission to install the app. For example, the BMS calls **CheckPermission** with **ohos.permission.INSTALL_BUNDLE** as an input parameter. If it has the permission, the installation proceeds; otherwise, the installation fails. ```c++ constexpr static char PERMISSION_INSTALL_BUNDLE[] = "ohos.permission.INSTALL_BUNDLE"; diff --git a/zh-cn/application-dev/ability-deprecated/ability-delegator.md b/zh-cn/application-dev/ability-deprecated/ability-delegator.md index d96a2db2a8c0b7c859f3cf964b4762c4af766299..81a2ed58b77bfb1b7e9d449a81c19f632e879120 100644 --- a/zh-cn/application-dev/ability-deprecated/ability-delegator.md +++ b/zh-cn/application-dev/ability-deprecated/ability-delegator.md @@ -63,7 +63,7 @@ AbilityMonitor是测试框架提供用来绑定并监听Ability类。开发者 **示例** ```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); @@ -87,11 +87,11 @@ AbilityDelegator是测试框架主要功能类,提供了启动Ability、获取 **导入模块** ```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; ``` ```javascript -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ### 启动Ability并监听Ability状态变化 diff --git a/zh-cn/application-dev/ability-deprecated/context-userguide.md b/zh-cn/application-dev/ability-deprecated/context-userguide.md index 52303aa9e40b37ec05fc906f9bd260ca026baef9..d0f51a6da81241bdea8715cb14d642825e9a12f3 100644 --- a/zh-cn/application-dev/ability-deprecated/context-userguide.md +++ b/zh-cn/application-dev/ability-deprecated/context-userguide.md @@ -283,7 +283,7 @@ export default class EntryAbility extends UIAbility { ```ts // pages/index.ets -import context from '@ohos.application.context' +import context from '@ohos.app.ability.context' type Context = context.Context diff --git a/zh-cn/application-dev/ability-deprecated/fa-formability.md b/zh-cn/application-dev/ability-deprecated/fa-formability.md index aa9ed5685453f37aa341fd507f30848f1c3eed91..68a4773419c0527a4263f2ad5271d923df8fc6ae 100644 --- a/zh-cn/application-dev/ability-deprecated/fa-formability.md +++ b/zh-cn/application-dev/ability-deprecated/fa-formability.md @@ -62,9 +62,9 @@ FormProvider类具体的API详见[接口文档](../reference/apis/js-apis-applic 1. 导入相关模块。 ```javascript - import formBindingData from '@ohos.application.formBindingData' - import formInfo from '@ohos.application.formInfo' - import formProvider from '@ohos.application.formProvider' + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; ``` 2. 实现LifecycleForm生命周期接口。 diff --git a/zh-cn/application-dev/ability-deprecated/stage-ability-continuation.md b/zh-cn/application-dev/ability-deprecated/stage-ability-continuation.md index 456df515077e11d703a80a0186d52bbf214187d8..ff0ef98bb40fc9196bf1ee8444277ee368030797 100644 --- a/zh-cn/application-dev/ability-deprecated/stage-ability-continuation.md +++ b/zh-cn/application-dev/ability-deprecated/stage-ability-continuation.md @@ -148,7 +148,7 @@ ```javascript import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.application.AbilityConstant'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ``` 要实现迁移,此接口必须实现并返回AGREE,否则默认为拒绝迁移。 diff --git a/zh-cn/application-dev/ability-deprecated/stage-ability.md b/zh-cn/application-dev/ability-deprecated/stage-ability.md index d3c241ee0a98cfb51e90e463edbeb9b7b66d30b6..9d46fe84685e67a9426e1f90f3fa2ae906765fe7 100644 --- a/zh-cn/application-dev/ability-deprecated/stage-ability.md +++ b/zh-cn/application-dev/ability-deprecated/stage-ability.md @@ -56,8 +56,8 @@ Ability功能如下(Ability类,具体的API详见[接口文档](../reference ### 实现AbilityStage及Ability生命周期 创建Stage模型的Page Ability应用,需实现AbilityStage接口及Ability生命周期接口,并使用窗口提供的方法设置页面。具体示例代码如下: 1. 导入AbilityStage模块。 - ``` - import AbilityStage from "@ohos.application.AbilityStage" + ```ts + import AbilityStage from "@ohos.app.ability.AbilityStage"; ``` 2. 实现AbilityStage接口,接口生成的默认相对路径:entry\src\main\ets\Application\AbilityStage.ts。 ```ts @@ -113,7 +113,8 @@ AbilityStage类及Ability类均拥有context属性,应用可以通过`this.con 如下示例展示了AbilityStage通过context属性获取包代码路径、HAP名称、Ability名称以及系统语言的方法。具体示例代码如下: ```ts -import AbilityStage from "@ohos.application.AbilityStage" +import AbilityStage from "@ohos.app.ability.AbilityStage"; + export default class MyAbilityStage extends AbilityStage { onCreate() { console.log("MyAbilityStage onCreate") @@ -156,8 +157,8 @@ export default class EntryAbility extends UIAbility { 如下示例展示了AbilityStage的`onConfigurationUpdated`回调实现,系统语言和颜色模式发生变化时触发该回调。具体示例代码如下: ```ts -import AbilityStage from '@ohos.application.AbilityStage' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' +import AbilityStage from '@ohos.app.ability.AbilityStage'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; export default class MyAbilityStage extends AbilityStage { onConfigurationUpdated(config) { @@ -171,7 +172,7 @@ export default class MyAbilityStage extends AbilityStage { 如下示例展示了Ability的`onConfigurationUpdated`回调实现,系统语言、颜色模式以及Display相关的参数,比如方向、Density,发生变化时触发该回调。具体示例代码如下: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; export default class EntryAbility extends UIAbility { direction : number; diff --git a/zh-cn/application-dev/ability-deprecated/stage-formextension.md b/zh-cn/application-dev/ability-deprecated/stage-formextension.md index 9559978c2f7a45648e3ebb4dbfac7beea31dfbac..26634f206cb4c3d35a0ce6db0743554f12244ae1 100644 --- a/zh-cn/application-dev/ability-deprecated/stage-formextension.md +++ b/zh-cn/application-dev/ability-deprecated/stage-formextension.md @@ -73,10 +73,10 @@ FormProvider类具体的API介绍详见[接口文档](../reference/apis/js-apis- 1. 导入相关模块 ```javascript - import FormExtension from '@ohos.application.FormExtension' - import formBindingData from '@ohos.application.formBindingData' - import formInfo from '@ohos.application.formInfo' - import formProvider from '@ohos.application.formProvider' + import FormExtension from '@ohos.app.ability.FormExtension'; + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; ``` 2. 实现FormExtension生命周期接口 diff --git a/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md b/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md index f52701d88dfd1d9bca4be663ff8652c44e480a0b..fd8691f841abfa4d3ce4407b9f849875eb2bda0d 100644 --- a/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md +++ b/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md @@ -42,9 +42,9 @@ OpenHarmony当前不支持三方应用创建ServiceExtensionAbility。 2. 开发者在定义Service的目录下创建TS文件,自定义类继承ServiceExtensionAbility,重写基类回调函数,接口生成的默认相对路径:entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts,示例如下: ```js - import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility' - import rpc from '@ohos.rpc' - + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + class StubTest extends rpc.RemoteObject { constructor(des) { super(des); @@ -52,7 +52,7 @@ OpenHarmony当前不支持三方应用创建ServiceExtensionAbility。 onRemoteRequest(code, data, reply, option) { } } - + class ServiceExtAbility extends ServiceExtensionAbility { onCreate(want) { console.log('onCreate, want:' + want.abilityName); diff --git a/zh-cn/application-dev/ability-deprecated/wantagent.md b/zh-cn/application-dev/ability-deprecated/wantagent.md index 1d3609f8193b90ccef6c028200321bdacb035229..10a59ef84fdad31a771a78980cb599b1a9d90f27 100644 --- a/zh-cn/application-dev/ability-deprecated/wantagent.md +++ b/zh-cn/application-dev/ability-deprecated/wantagent.md @@ -15,7 +15,7 @@ WantAgent封装了一个行为意图信息,可以通过WantAgent.trigger接口 1. 导入WantAgent模块。 ```ts - import wantAgent from '@ohos.wantAgent'; + import wantAgent from '@ohos.app.ability.wantAgent'; ``` 2. 创建拉起Ability的WantAgentInfo信息。详细的WantAgentInfo信息数据类型及包含的参数请见[WantAgentInfo文档](../reference/apis/js-apis-wantAgent.md#wantagentinfo)介绍。 diff --git a/zh-cn/application-dev/application-test/arkxtest-guidelines.md b/zh-cn/application-dev/application-test/arkxtest-guidelines.md index 9fc6e8864a31802bb31b0e7a71c39a6aee27d931..8d31275f5d196b82a936c82c11baa53a17eefa9d 100644 --- a/zh-cn/application-dev/application-test/arkxtest-guidelines.md +++ b/zh-cn/application-dev/application-test/arkxtest-guidelines.md @@ -63,8 +63,8 @@ DevEco Studio可参考其官网介绍进行[下载](https://developer.harmonyos. ## 编写单元测试脚本 ```TS -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' -import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; const delegator = abilityDelegatorRegistry.getAbilityDelegator() export default function abilityTest() { diff --git a/zh-cn/application-dev/database/database-datashare-guidelines.md b/zh-cn/application-dev/database/database-datashare-guidelines.md index b089b78b35a563a822060ce9f0b9acb73e624542..10987777f6da1e92b0cf1975441dfe40afa3625a 100644 --- a/zh-cn/application-dev/database/database-datashare-guidelines.md +++ b/zh-cn/application-dev/database/database-datashare-guidelines.md @@ -38,7 +38,50 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 ### 数据提供方应用的开发(仅限系统应用) -1. 导入基础依赖包。 +[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md)提供以下API,根据需要重写对应回调方法。 + +- **onCreate** + + DataShare客户端连接DataShareExtensionAbility服务端时,服务端回调此接口,执行初始化业务逻辑操作。该方法可以选择性重写。 + +- **insert** + + 业务函数,客户端请求插入数据时回调此接口,服务端需要在此回调中实现插入数据功能,该方法可以选择性重写。 + +- **update** + + 业务函数,客户端请求插入数据时回调此接口,服务端需要在此回调中实现更新数据功能,该方法可以选择性重写。 + +- **delete** + + 业务函数,客户端请求插入数据时回调此接口,服务端需要在此回调中实现删除数据功能,该方法可以选择性重写。 + +- **query** + + 业务函数,客户端请求插入数据时回调此接口,服务端需要在此回调中实现查询数据功能,该方法可以选择性重写。 + +- **batchInsert** + + 业务函数,客户端请求插入数据时回调此接口,服务端需要在此回调中实现批量插入数据数据功能,该方法可以选择性重写。 + +- **normalizeUri** + + 业务函数,客户端给定的URI转换为服务端使用的URI时回调此接口,该方法可以选择性重写。 + +- **denormalizeUri** + + 业务函数,服务端使用的URI转换为客户端传入的初始URI时服务端回调此接口,该方法可以选择性重写。 + +开发者在实现一个数据共享服务时,需要在DevEco Studio工程中手动新建一个DataShareExtensionAbility,具体步骤如下。 + +1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为DataShareAbility。 + +2. 在DataShareAbility目录,右键选择“New > TypeScript File”,新建一个TypeScript文件并命名为DataShareAbility.ts。 + +3. 在DataShareAbility.ts文件中,增加导入DataShareExtensionAbility的依赖包,开发者可根据应用需求选择性重写其业务实现。例如数据提供方只提供插入、删除和查询服务,则可只重写这些接口。 + + +4. 导入基础依赖包。 ```ts import Extension from '@ohos.application.DataShareExtensionAbility'; @@ -47,9 +90,9 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` -2. 数据提供方(也称服务端)继承于DataShareExtensionAbility,开发者可根据应用需求选择性重写其业务实现。例如数据提供方只提供查询服务,则可只重写查询接口。 +5. 数据提供方(也称服务端)继承于DataShareExtensionAbility,开发者可根据应用需求选择性重写其业务实现。例如数据提供方只提供查询服务,则可只重写查询接口。 -3. 数据提供方的业务实现由开发者自定义。例如可以通过数据库、读写文件或访问网络等各方式实现数据提供方的数据存储。 +6. 数据提供方的业务实现由开发者自定义。例如可以通过数据库、读写文件或访问网络等各方式实现数据提供方的数据存储。 ```ts const DB_NAME = "DB00.db"; @@ -57,13 +100,13 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + TBL_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; - + let rdbStore; let result; - + export default class DataShareExtAbility extends Extension { private rdbStore_; - + // 重写onCreate接口 onCreate(want, callback) { result = this.context.cacheDir + '/datashare.txt' @@ -78,7 +121,7 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 callback(); }); } - + // 重写query接口 query(uri, predicates, columns, callback) { if (predicates == null || predicates == undefined) { @@ -102,7 +145,7 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 }; ``` -4. 在module.json5中定义DataShareExtensionAbility。 +7. 在module.json5中定义DataShareExtensionAbility。 | Json重要字段 | 备注说明 | | ------------ | ------------------------------------------------------------ | @@ -136,20 +179,20 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` - + 2. 定义与数据提供方通信的URI字符串。 ```ts // 作为参数传递的URI,与module.json5中定义的URI的区别是多了一个"/",是因为作为参数传递的URI中,在第二个与第三个"/"中间,存在一个DeviceID的参数 let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); ``` - + 3. 创建工具接口类对象。 ```ts let dsHelper; let abilityContext; - + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { abilityContext = this.context; @@ -159,7 +202,7 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 } } ``` - + 4. 获取到接口类对象后,便可利用其提供的接口访问提供方提供的服务,如进行数据的增删改查等。 ```ts @@ -182,6 +225,12 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其 }); // 删除指定的数据 dsHelper.delete(dseUri, predicates, (err, data) => { - console.log("dsHelper delete result: " + data); + console.log("dsHelper delete result: " + data); }); ``` + +## 相关示例 + +针对DataShareExtensionAbility开发,有以下相关示例可供参考: + +[DataShareExtensionAbility:跨应用数据共享(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/CrossAppDataShare) diff --git a/zh-cn/application-dev/database/database-datashare-overview.md b/zh-cn/application-dev/database/database-datashare-overview.md index e7941b27edf42c6c474c9e1513c27730408b1890..179f92808ed31c5a93419a8aeb91f26067317111 100644 --- a/zh-cn/application-dev/database/database-datashare-overview.md +++ b/zh-cn/application-dev/database/database-datashare-overview.md @@ -4,6 +4,8 @@ DataShare即数据共享模块,用于应用管理其自身数据,也提供了向其他应用共享以及管理其数据的方法。目前仅支持同个设备上应用之间的数据共享。 +DataShare需要与[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md)配合使用。 + 在许多应用场景中都需要用到数据共享,比如将电话簿、短信、媒体库中的数据共享给其他应用等。当然,不是所有的数据都允许其他应用访问,比如帐号、密码等;有些数据也只允许其他应用查询而不允许其删改,比如短信等。所以对于各种数据共享场景,DataShare这样一个安全、便捷的可以跨应用的数据共享机制是十分必需的。 对于数据提供者来说,无需进行繁琐的封装,可直接使用DataShare框架实现向其他应用共享数据;对于数据访问方来说,因DataShare的访问方式不会因数据提供的方式而不同,所以只需要学习和使用一套接口即可,大大减少了学习时间和开发难度。 @@ -16,22 +18,22 @@ DataShare即数据共享模块,用于应用管理其自身数据,也提供 - **数据提供方** - 提供数据及实现相关业务的应用程序,也称为生产者或服务端。 + DataShareExtensionAbility,基于Stage模型,选择性实现对数据的增、删、改、查以及文件打开等功能,并对外共享这些数据。实现跨应用数据共享的相关业务。 - **数据访问方** - 访问数据提供方所提供的数据或业务的应用程序,也称为消费者或客户端。 + DataShareHelper,由[createDataShareHelper()](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper)方法所创建的工具类,数据访问方利用工具类,便可访问数据提供方提供的数据。 - **数据集** 用户要插入的数据集合,可以是一条或多条数据。数据集以键值对的形式存在,键为字符串类型,值支持数字、字符串、布尔值、无符号整型数组等多种数据类型。 - **结果集** - + 用户查询之后的结果集合,其提供了灵活的数据访问方式,以便用户获取各项数据。 - + - **谓词** - + 用户访问数据库中的数据所使用的筛选条件,经常被应用在更新数据、删除数据和查询数据等场景。 ## 运作机制 @@ -41,7 +43,7 @@ DataShare即数据共享模块,用于应用管理其自身数据,也提供 ![](figures/zh-cn_DataShare.png) -- DataShareExtAbility模块为数据提供方,实现跨应用数据共享的相关业务。 +- DataShareExtensionAbility模块为数据提供方,实现跨应用数据共享的相关业务。 - DataShareHelper模块为数据访问方,提供各种访问数据的接口,包括增删改查等。 - 数据访问方与提供方通过IPC进行通信,数据提供方可以通过数据库实现,也可以通过其他数据存储方式实现。 @@ -51,4 +53,4 @@ DataShare即数据共享模块,用于应用管理其自身数据,也提供 - DataShare受到数据提供方所使用数据库的一些限制。例如支持的数据模型、Key的长度、Value的长度、每个应用程序支持同时打开数据库的最大数量等,都会受到使用的数据库的限制。 -- 因DataShare内部实现依赖于IPC通信,所以数据集、谓词、结果集等的载荷受到IPC通信的约束与限制。 \ No newline at end of file +- 因DataShare内部实现依赖于IPC通信,所以数据集、谓词、结果集等的载荷受到IPC通信的约束与限制。 diff --git a/zh-cn/application-dev/database/database-mdds-guidelines.md b/zh-cn/application-dev/database/database-mdds-guidelines.md index 3398928528cee7c40e9abb7f1431b3b519d85dac..8a6f3d538b52b380cc6b637f1f0c01b2a923d0ad 100644 --- a/zh-cn/application-dev/database/database-mdds-guidelines.md +++ b/zh-cn/application-dev/database/database-mdds-guidelines.md @@ -17,9 +17,9 @@ | getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | 指定`Options`和`storeId`,创建并获取指定类型`KVStore`数据库。 | | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | 插入和更新数据。 | | delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | 删除数据。 | -| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | 查询数据。 | +| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | 获取数据。 | | on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string,number]>>): void | 订阅数据库中数据的变化。 | -| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | 在手动模式下,触发数据库同步。 | +| sync(deviceIdList: string[], mode: SyncMode, delayMs?: number): void | 在手动模式下,触发数据库同步。 | ## 开发步骤 @@ -61,7 +61,7 @@ context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => { console.info('success: ${data}'); }).catch((error) => { - console.info('failed: ${error}'); + console.error('failed: ${error}'); }) } @@ -71,22 +71,22 @@ import UIAbility from '@ohos.app.ability.UIAbility'; let context = null; - - function grantPermission() { - class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { let context = this.context; - } + } } - - let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; - context.requestPermissionsFromUser(permissions).then((data) => { + + function grantPermission() { + let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { console.log('success: ${data}'); - }).catch((error) => { - console.log('failed: ${error}'); - }); + }).catch((error) => { + console.error('failed: ${error}'); + }); } - + grantPermission(); ``` diff --git a/zh-cn/application-dev/database/figures/zh-cn_DataShare.png b/zh-cn/application-dev/database/figures/zh-cn_DataShare.png index cbeee3191dc614ec21dbef2866dc3a1412628eee..b7ea19a7a70dd5aeefc31d59cbccf1fdab5a8200 100644 Binary files a/zh-cn/application-dev/database/figures/zh-cn_DataShare.png and b/zh-cn/application-dev/database/figures/zh-cn_DataShare.png differ diff --git a/zh-cn/application-dev/device/location-guidelines.md b/zh-cn/application-dev/device/location-guidelines.md index 47da8c123b8e47f3533f765f115cd3593606145c..46d12c9790f1d030bc928c8c55a3f88e636c43e2 100644 --- a/zh-cn/application-dev/device/location-guidelines.md +++ b/zh-cn/application-dev/device/location-guidelines.md @@ -147,7 +147,7 @@ 以导航场景为例,实例化方式如下: - + ```ts let requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` @@ -159,13 +159,13 @@ ***定位优先级策略类型说明*** - 定位精度优先策略:ACCURACY
- 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。 + 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。 - 快速定位优先策略:FIRST_FIX
- 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。 + 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。 - 低功耗定位优先策略:LOW_POWER
- 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。 + 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。 ```ts export enum LocationRequestPriority { @@ -177,7 +177,7 @@ ``` 以定位精度优先策略为例,实例化方式如下: - + ```ts let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` @@ -336,7 +336,7 @@ ```ts import geoLocationManager from '@ohos.geoLocationManager'; - import wantAgent from '@ohos.wantAgent'; + import wantAgent from '@ohos.app.ability.wantAgent'; ``` 3. 创建[WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md)信息。 diff --git a/zh-cn/application-dev/dfx/apprecovery-guidelines.md b/zh-cn/application-dev/dfx/apprecovery-guidelines.md index 314c81ca94a34e3e10a0171a99fe08a5815b6960..028b2d6cfcb17e6ff8079389db49abc3be7edf1d 100644 --- a/zh-cn/application-dev/dfx/apprecovery-guidelines.md +++ b/zh-cn/application-dev/dfx/apprecovery-guidelines.md @@ -87,9 +87,9 @@ export default class MyAbilityStage extends AbilityStage { #### 导包 ```ts -import errorManager from '@ohos.app.ability.errorManager' -import appRecovery from '@ohos.app.ability.appRecovery' -import AbilityConstant from '@ohos.app.ability.AbilityConstant' +import errorManager from '@ohos.app.ability.errorManager'; +import appRecovery from '@ohos.app.ability.appRecovery'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ``` #### 主动触发保存和恢复 diff --git a/zh-cn/application-dev/dfx/errormanager-guidelines.md b/zh-cn/application-dev/dfx/errormanager-guidelines.md index 8baf36b4d1b79e2925e9f6a6e0646abfd762469d..8a588efc18d0798d1b10a24ee43d730960309abb 100644 --- a/zh-cn/application-dev/dfx/errormanager-guidelines.md +++ b/zh-cn/application-dev/dfx/errormanager-guidelines.md @@ -37,7 +37,7 @@ ## 开发示例 ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import errorManager from '@ohos.application.errorManager'; +import errorManager from '@ohos.app.ability.errorManager'; var registerId = -1; var callback = { diff --git a/zh-cn/application-dev/dfx/hitracemeter-guidelines.md b/zh-cn/application-dev/dfx/hitracemeter-guidelines.md index 81b27aa3748dffefc249a67fe6ec1230a6bcdef5..9fe91ccc685f899a923443187c133233b00da4fb 100644 --- a/zh-cn/application-dev/dfx/hitracemeter-guidelines.md +++ b/zh-cn/application-dev/dfx/hitracemeter-guidelines.md @@ -25,11 +25,11 @@ hiTraceMeter为开发者提供系统性能打点接口。开发者通过在自 **性能打点跟踪接口功能介绍:** -| 接口名 | 返回值 | 描述 | -| ---------------------------------------------------------------------------- | --------- | ------------ | -| hiTraceMeter.startTrace(name: string, taskId: number) | void | 标记一个预跟踪耗时任务的开始。如果有多个相同name的任务需要跟踪或者对同一个任务要跟踪多次,并且任务同时被执行,则每次调用startTrace的taskId不相同。如果具有相同name的任务是串行执行的,则taskId可以相同。 | -| hiTraceMeter.finishTrace(name: string, taskId: number) | void | name和taskId必须与流程开始的hiTraceMeter.startTrace对应参数值保持一致。 | -| hiTraceMeter.traceByValue(name: string, value: number) | void | 用来标记一个预跟踪的数值变量,该变量的数值会不断变化。| +| 接口名 | 返回值 | 描述 | +| ------------------------------------------------------ | ---- | -------------------------------------------------------------------------------------------------------------------- | +| hiTraceMeter.startTrace(name: string, taskId: number) | void | 标记一个预跟踪耗时任务的开始。taskId是trace中用来表示关联的ID,如果有多个name相同的任务是并行执行的,则每次调用startTrace的taskId不同。如果具有相同name的任务是串行执行的,则taskId可以相同。 | +| hiTraceMeter.finishTrace(name: string, taskId: number) | void | name和taskId必须与流程开始的hiTraceMeter.startTrace对应参数值保持一致。 | +| hiTraceMeter.traceByValue(name: string, value: number) | void | 用来标记一个预跟踪的数值变量,该变量的数值会不断变化。 | ## 开发步骤 @@ -79,5 +79,95 @@ hiTraceMeter为开发者提供系统性能打点接口。开发者通过在自 } ``` -2. 运行项目,点击应用界面上的运行按钮,即可通过日志信息分析实际业务。 - +2. 新建一个ArkTs应用工程,在“Project”窗口点击“entry > src > main > ets > pages > index”,打开工程中的“index.ets”文件,在页面执行加载后,在自己的业务中调用hiTraceMeter的接口,进行性能打点跟踪,以任务名name为HITRACE_TAG_APP为例 示例代码如下: + + ```ts + import hitrace from '@ohos.hiTraceMeter'; + + @Entry + @Component + struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + this.message = 'Hello ArkUI'; + + // 跟踪并行执行的同名任务 + hitrace.startTrace("HITRACE_TAG_APP", 1001); + // 业务流程 + console.log(`HITRACE_TAG_APP running`); + + // 第二个跟踪任务开始,同时第一个跟踪的同名任务还没结束,出现了并行执行,对应接口的taskId需要不同。 + hitrace.startTrace("HITRACE_TAG_APP", 1002); + // 业务流程 + console.log(`HITRACE_TAG_APP running`); + + hitrace.finishTrace("HITRACE_TAG_APP", 1001); + hitrace.finishTrace("HITRACE_TAG_APP", 1002); + + // 跟踪串行执行的同名任务,taskId可以不同,也可以相同 + hitrace.startTrace("HITRACE_TAG_APP", 1003); + // 业务流程 + console.log(`HITRACE_TAG_APP running`); + //第一个跟踪的任务结束 + hitrace.finishTrace("HITRACE_TAG_APP", 1003); + + // 第二个跟踪任务开始,同名的待跟踪任务串行执行,且taskId不同 + hitrace.startTrace("HITRACE_TAG_APP", 1004); + // 业务流程 + console.log(`HITRACE_TAG_APP running`); + let traceCount = 3; + hitrace.traceByValue("myTestCount", traceCount); + hitrace.finishTrace("HITRACE_TAG_APP", 1004); + + // 第三个跟踪任务开始,同名的待跟踪任务串行执行,且taskId与上一个相同 + hitrace.startTrace("HITRACE_TAG_APP", 1004); + // 业务流程 + console.log(`HITRACE_TAG_APP running`); + //第三个跟踪的任务结束 + hitrace.finishTrace("HITRACE_TAG_APP", 1004); + + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +3. 运行项目,点击应用界面上的运行按钮,在shell中依次执行如下命令: + + ```shell + hdc shell + hitrace --trace_begin app + ``` + + 执行抓取trace命令后,先在设备中自己的业务里面调用接口,继续依次执行如下命令: + + ```shell + hitrace --trace_dump | grep tracing_mark_write + hitrace --trace_finish + ``` + + 抓取trace成功的数据如下所示 + + ``` + <...>-3310 (-------) [005] .... 351382.921936: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1001 + <...>-3310 (-------) [005] .... 351382.922138: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1002 + <...>-3310 (-------) [005] .... 351382.922165: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1001 + <...>-3310 (-------) [005] .... 351382.922175: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1002 + <...>-3310 (-------) [005] .... 351382.922182: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1003 + <...>-3310 (-------) [005] .... 351382.922203: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1003 + <...>-3310 (-------) [005] .... 351382.922210: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1004 + <...>-3310 (-------) [005] .... 351382.922233: tracing_mark_write: C|3310|H:myTestCount 3 + <...>-3310 (-------) [005] .... 351382.922240: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1004 + <...>-3310 (-------) [005] .... 351382.922247: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1004 + <...>-3310 (-------) [005] .... 351382.922266: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1004 + ``` diff --git a/zh-cn/application-dev/faqs/faqs-event-notification.md b/zh-cn/application-dev/faqs/faqs-event-notification.md index 9d9bfe04eb6b10b09d4618c26c4af5d40a7018b5..b507f8f85ca6013c75c5f0559e06b504419f52ef 100644 --- a/zh-cn/application-dev/faqs/faqs-event-notification.md +++ b/zh-cn/application-dev/faqs/faqs-event-notification.md @@ -17,7 +17,7 @@ emitter数据大小限制不超过10240。 示例: ```ts -import WantAgent from '@ohos.wantAgent'; +import WantAgent from '@ohos.app.ability.wantAgent'; async function publishNotification() { let wantAgentInfo = { diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md b/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md index c9b8fb74bf2aa4c649103837544e3a53ea9fbf5b..ba597dd6a8c060715b1606aba66d18f0965dc4e9 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/Readme-CN.md @@ -39,6 +39,7 @@ - 典型页面场景 - [应用市场首页](appgallery-home-page.md) - [音乐专辑页](music-album-page.md) + - [设置应用页面](settings-application-page.md) - [交互归一](interaction-event-normalization.md) - [多态组件](polymorphic-controls.md) - [资源使用](resource-usage.md) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md b/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md index 68a8b425f18f6c362bb3d264b52ed9e1d7d4981e..0ec02b55b7ab8c41e20374626b2c6360b1d263fb 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/faq.md @@ -6,18 +6,18 @@ 设备类型分为default(默认设备)、tablet、tv、wearable等,有多种查询设备类型的方式。 1. 通过命令行的方式查询设备类型。 - 通过命令行查询指定系统参数(const.build.characteristics)进而确定设备类型,详见[系统参数介绍](../../../device-dev/subsystems/subsys-boot-init-sysparam.md)。 + 通过命令行查询指定系统参数(const.product.devicetype)进而确定设备类型,详见[系统参数介绍](../../../device-dev/subsystems/subsys-boot-init-sysparam.md)。 ```shell # 方法一 - hdc shell param get "const.build.characteristics" + hdc shell param get "const.product.devicetype" # 方法二 - hdc shell cat /etc/param/ohos.para | grep const.build.characteristic + hdc shell cat /etc/param/ohos.para | grep const.product.devicetype ``` 2. 在应用开发过程中查询设备类型。 - - 通过js接口查询指定系统参数(const.build.characteristics)进而确定设备类型,详见[系统属性](../../reference/apis/js-apis-system-parameter.md)。 + - 通过js接口查询指定系统参数(const.product.devicetype)进而确定设备类型,详见[系统属性](../../reference/apis/js-apis-system-parameter.md)。 ```typescript import parameter from '@ohos.systemparameter' @@ -29,7 +29,7 @@ aboutToAppear() { try { - this.deviceType = parameter.getSync("const.build.characteristics") + this.deviceType = parameter.getSync("const.product.devicetype") } catch(e) { console.log("getSync unexpected error: " + e) } @@ -94,7 +94,7 @@ launchType字段配置为specified时,系统会根据AbilityStage的onAcceptWa ```typescript // MyAbilityStage.ts -import AbilityStage from "@ohos.application.AbilityStage" +import AbilityStage from "@ohos.app.ability.AbilityStage" import deviceInfo from'@ohos.deviceInfo' export default class MyAbilityStage extends AbilityStage { @@ -179,3 +179,57 @@ hdc shell reboot } } ``` + +## 如何获取组件的尺寸 + +实际开发过程中,开发者可能有获取页面中某个组件或某块区域的尺寸的诉求,以便通过手动计算等进行更精确的布局计算及优化。 + +开发者可以通过[组件区域变化事件](../../reference/arkui-ts/ts-universal-component-area-change-event.md)(即组件显示的尺寸、位置等发生变化时触发的事件)来获取指定组件的尺寸。 + +如下所示,通过onAreaChange事件获取Row组件(页面中白色区域)的尺寸。 + +![](figures/onAreaChange.gif) + +``` +@Entry +@Component +struct OnAreaChangeSample { + @State rate: number = 0.8 + @State info: string = '' + + // 底部滑块,可以通过拖拽滑块改变容器尺寸 + @Builder slider() { + Slider({ value: this.rate * 100, min: 30, max: 80, style: SliderStyle.OutSet }) + .blockColor(Color.White) + .width('60%') + .onChange((value: number) => { + this.rate = value / 100; + }) + .position({ x: '20%', y: '80%' }) + } + + build() { + Column() { + Column() { + Row() { + Text(this.info).fontSize(20).lineHeight(22) + } + .borderRadius(12) + .padding(24) + .backgroundColor('#FFFFFF') + .width(this.rate * 100 + '%') + .onAreaChange((oldValue: Area, newValue: Area) => { + this.info = JSON.stringify(newValue) + }) + } + + this.slider() + } + .width('100%') + .height('100%') + .backgroundColor('#F1F3F5') + .justifyContent(FlexAlign.Center) + } +} +``` + diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_lg.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_lg.png new file mode 100644 index 0000000000000000000000000000000000000000..229e99d6512875acf0b797810ff639a0cfb0d065 Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_lg.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_md.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_md.png new file mode 100644 index 0000000000000000000000000000000000000000..baf1fb7682261c67ab982b6ac50201686a120b83 Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_md.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_sm.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_sm.png new file mode 100644 index 0000000000000000000000000000000000000000..1cf3cff5e48e373d057bf4dca8f48cf2689d0dcc Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/custom_dialog_sm.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_lg.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_lg.png new file mode 100644 index 0000000000000000000000000000000000000000..8cb875bb61423aa2730a90c8340cd01c03f98331 Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_lg.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_md.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_md.png new file mode 100644 index 0000000000000000000000000000000000000000..e28ce75ca1dbce04ae45f52f85c0ad2e743fadec Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_md.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_sm.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_sm.png new file mode 100644 index 0000000000000000000000000000000000000000..5aa02574ae421df7863d16e5bc9f079528758b4f Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/navigation_sm.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/onAreaChange.gif b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/onAreaChange.gif new file mode 100644 index 0000000000000000000000000000000000000000..2feeb6876971012bda131c04b86729b64af1774c Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/onAreaChange.gif differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navdestination_title.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navdestination_title.png new file mode 100644 index 0000000000000000000000000000000000000000..b51a2945bd99874d99eda880fafcad4b41b7d16b Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navdestination_title.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_split.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_split.png new file mode 100644 index 0000000000000000000000000000000000000000..b7b3826afc5434239d8be306e5fffd7b1d495816 Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_split.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_stack.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_stack.png new file mode 100644 index 0000000000000000000000000000000000000000..fb0e41a3e386c1378ffa9e9c96be72f5db550b83 Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_stack.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_structure.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_structure.png new file mode 100644 index 0000000000000000000000000000000000000000..c3b356eef3652a667410e06a8dea13c814f8628a Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navigation_structure.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navrouter.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navrouter.png new file mode 100644 index 0000000000000000000000000000000000000000..d9cd28814111cc7f3790215e6149911122bb6678 Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_navrouter.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_primary.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_primary.png new file mode 100644 index 0000000000000000000000000000000000000000..6a6a8329b4338ffc42a4f095ef69d634839cab5e Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_primary.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_secondary.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_secondary.png new file mode 100644 index 0000000000000000000000000000000000000000..5e5e8626e3a2597dc1a396d50568fb711998e56a Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_secondary.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_ux.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_ux.png new file mode 100644 index 0000000000000000000000000000000000000000..b73f4700d55fe66598ca3297ab7110cdc3cf4bbb Binary files /dev/null and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/settings_ux.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001266965046.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001266965046.png deleted file mode 100644 index afbba0ab9855e27fe8b354bbd83dcdbf803dd398..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001266965046.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400300617.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400300617.png deleted file mode 100644 index 0f193d141fe370441c9c5d66c2f5fb3eae122cbd..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001400300617.png and /dev/null differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/introduction.md b/zh-cn/application-dev/key-features/multi-device-app-dev/introduction.md index bebdaf58854ad5114941a569cf6c8c4d3d9ebdb2..9c590d43d1e95d86c0420789991976265dd5d7b7 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/introduction.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/introduction.md @@ -25,8 +25,9 @@ 从第4章开始将从UX设计、系统能力等角度,详尽的解答上述问题。 > **说明:** +> > - 应用开发不仅包含应用页面开发,还包括应用后端功能开发以及服务器端开发等。 -> +> > - 本文旨在指导开发者如何在OpenHarmony系统中开发“一多”应用,服务器端开发不在本文探讨范围内。 @@ -34,28 +35,9 @@ 为了更好的阅读后面的章节,本小节主要介绍了一些基础知识,方便读者理解内容。 - -### 应用程序包结构 - -OpenHarmony 的应用以APP Pack (Application Package) 形式发布,它是由一个或多个HAP以及描述每个HAP属性的pack.info文件组成。 - -HAP是OpenHarmony的安装包,一个HAP在工程目录中对应一个Module,由Module编译而来,可分为entry和feature两种类型的HAP。 - -- **entry**:应用的主模块包。一个APP中,对于同一设备类型,可以有一个或多个entry类型的HAP,来支持该设备类型中不同规格(如API版本、屏幕规格等)的具体设备。 - -- **feature**:应用的动态特性模块包。一个APP Pack可以包含零个、一个或多个feature类型的HAP。 - -![zh-cn_image_0000001266965046](figures/zh-cn_image_0000001266965046.png) - -> **说明:** -> - Module是开发者开发的相对独立的功能模块,由代码、资源、第三方库及应用配置文件组成,属于IDE开发视图的概念。Module分为entry、feature及har三种类型,相应的可以编译生成entry类型的HAP、feature类型的HAP,以及har包。 -> -> - 如果需要了解应用程序包结构更多详情,可以查看[包结构说明](../../quick-start/application-package-structure-stage.md)。 - - ### 方舟开发框架 -OpenHarmony提供了方舟开发框架(简称:ArkUI),提供开发者进行应用UI开发时所必须的能力。 +OpenHarmony提供了[方舟开发框架](../../ui/arkui-overview.md)(简称:ArkUI),提供开发者进行应用UI开发时所必须的能力。 方舟开发框架提供了两种开发范式,分别是基于JS扩展的类Web开发范式(后文中简称为“类Web开发范式”)和基于ArkTS的声明式开发范式(后文中简称为“声明式开发范式”)。 @@ -63,7 +45,6 @@ OpenHarmony提供了方舟开发框架(简称:ArkUI),提供开发者进 - **类Web开发范式**:采用经典的HML、CSS、JavaScript三段式开发方式。使用HML标签文件进行布局搭建,使用CSS文件进行样式描述,使用JavaScript文件进行逻辑处理。UI组件与数据之间通过单向数据绑定的方式建立关联,当数据发生变化时,UI界面自动触发更新。此种开发方式,更接近Web前端开发者的使用习惯,快速将已有的Web应用改造成方舟开发框架应用。主要适用于界面较为简单的中小型应用开发。 - 两种开发范式的对比如下。 | **开发范式名称** | **语言生态** | **UI更新方式** | **适用场景** | **适用人群** | @@ -72,10 +53,26 @@ OpenHarmony提供了方舟开发框架(简称:ArkUI),提供开发者进 | 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的中小型应用和卡片 | Web前端开发人员 | > **说明:** -> - 声明式开发范式占用内存更少,**更推荐开发者选用声明式开发范式来搭建应用UI界面**。 -> -> - 可以查看[方舟开发框架概述](../../ui/arkui-overview.md),了解方舟开发框架更多详情。 +> 声明式开发范式占用内存更少,**更推荐开发者选用声明式开发范式来搭建应用UI界面**。 + +### 应用程序包结构 + +在进行应用开发时,一个应用通常包含一个或多个Module。Module是OpenHarmony应用/服务的基本功能单元,包含了源代码、资源文件、第三方库及应用/服务配置文件,每一个Module都可以独立进行编译和运行。 + +Module分为“Ability”和“Library”两种类型: + +* “Ability”类型的Module编译后生成HAP包。 + +* “Library”类型的Module编译后生成HAR包。 + +OpenHarmony的应用以APP Pack形式发布,其包含一个或多个HAP包。HAP是OpenHarmony应用安装的基本单位,HAP可以分为Entry和Feature两种类型: +* Entry类型的HAP:应用的主模块。在同一个应用中,同一设备类型只支持一个Entry类型的HAP,通常用于实现应用的入口界面、入口图标、主特性功能等。 + +* Feature类型的HAP:应用的动态特性模块。Feature类型的HAP通常用于实现应用的特性功能,一个应用程序包可以包含一个或多个Feature类型的HAP,也可以不包含。 + +> **说明:** +> 关于Entry类型的HAP包、Feature类型的HAP包、HAR包以及APP Pack的详细介绍请参考[应用程序包结构说明](../../quick-start/application-package-structure-stage.md) 。 ### 部署模型 @@ -85,79 +82,65 @@ OpenHarmony提供了方舟开发框架(简称:ArkUI),提供开发者进 - **部署模型B**:不同类型的设备上按照一定的工程结构组织方式,通过一次编译生成**不同**的HAP(或HAP组合)。 -建议开发者从设备类型及应用功能两个维度,结合具体的业务场景,考虑选择哪种部署模型。但不管采用哪种部署模型,都应该采用一次编译。 +开发者可以从应用UX设计及应用功能两个维度,结合具体的业务场景,考虑选择哪种部署模型。当然,也可以借助设备类型分类,快速做出判断。 -**设备类型** - - 从屏幕尺寸、交互方式及使用距离三个维度考虑,我们将常用的设备分为三大泛类: +从屏幕尺寸、输入方式及交互距离三个维度考虑,可以将常用类型的设备分为不同泛类: - 默认设备、平板 - 车机、智慧屏 - 智能穿戴 -对于相同泛类的设备,优先选择部署模型A,对于不同泛类设备,优先选择部署模型B。 - -**应用功能** +- …… -- 方舟开发框架提供了丰富的多设备适配能力,相同泛类的设备通常总是可以使用部署模型A。部署模型A需要的开发和维护工作量更小,而且可以保证不同类型设备上体验的一致性。 - -- 仅当同一泛类不同类型设备上规划的功能差异非常大时,才推荐使用部署模型B,如默认设备和平板分别交给两个团队设计、开发和维护等。 - -一般应用在不同设备上选择部署模型的思路如下: - -![zh-cn_image_0000001400300617](figures/zh-cn_image_0000001400300617.png) +**对于相同泛类的设备,优先选择部署模型A,对于不同泛类设备,优先选择部署模型B。** > **说明:** -> 页面导航逻辑是指应用内页面之间的跳转关系。假设默认设备上页面A跳转到页面B,平板设备上也是页面A跳转到页面B。因为两种设备屏幕大小不同,默认设备上页面B是覆盖显示在页面A上的,平板设备上页面B是在页面A的右边并且同时显示,但因为都是页面A跳转到页面B,那么我们认为它们的页面导航逻辑相同。 +> +> * 应用在不同泛类设备上的UX设计或功能相似时,可以使用部署模型A。 +> * 应用在同一泛类不同类型设备上UX设计或功能差异非常大时,可以使用部署模型B,但同时也应审视应用的UX设计及功能规划是否合理。 +> +> * 本小节引入部署模型A和部署模型B的概念是为了方便开发者理解。实际上在开发多设备应用时,如果目标设备类型较多,往往是部署模型A和部署模型B混合使用。 +> +> * 不管采用哪种部署模型,都应该采用一次编译。 -**工程结构** +### 工程结构 “一多”推荐在应用开发过程中使用如下的“三层工程结构”。 -- common:公共特性目录,如工具类、公共配置等。 - -- features:功能模块目录,存放应用中相对独立的各个功能的实现(包括该功能相关的UI代码及业务逻辑代码),如帐户管理等。 +- common(公共能力层):用于存放公共基础能力集合(如工具库、公共配置等)。 -- product:产品层目录,通过引用common和feature目录中代码的方式做功能和特性的集成,同时也作为主入口。 + common层不可分割,需编译成一个HAR包,其只可以被products和features依赖,不可以反向依赖。 -> **说明:** -> features层可横向调用和依赖common层能力;product层不可横向调用,可依赖features层和common层,且不能有反向依赖。 +- features(基础特性层):用于存放基础特性集合(如应用中相对独立的各个功能的UI及业务逻辑实现等)。 -部署模型不同,相应的代码工程结构也有差异。部署模型A和部署模型B的主要差异点集中在product层: + 各个feature高内聚、低耦合、可定制,供产品灵活部署。不需要单独部署的feature通常编译为HAR包,供products或其它feature使用。需要单独部署的feature通常编译为Feature类型的HAP包,和products下Entry类型的HAP包进行[组合部署](../../quick-start/multi-hap-objective.md)。features层可以横向调用及依赖common层,同时可以被products层不同设备形态的HAP所依赖,但是不能反向依赖products层。 -- 部署模型A可以直接在product目录中做功能和特性集成。 +- products(产品定制层):用于针对不同设备形态进行功能和特性集成。 -- 部署模型B需要在product目录下再建一级子目录,在不同的子目录中对不同的产品做差异化的功能和特性集成。 + products层各个子目录各自编译为一个Entry类型的HAP包,作为应用主入口。products层不可以横向调用。 -部署模型A对应的代码工程结构抽象后一般如下所示: +代码工程结构抽象后一般如下所示: ``` /application -├── common # 可选。公共特性目录, har类型的module -├── features # 可选。功能模块目录 -│ ├── feature1 # 子功能1, har类型的module -│ ├── feature2 # 子功能2, har类型的module +├── common # 可选。公共能力层, 编译为HAR包 +├── features # 可选。基础特性层 +│ ├── feature1 # 子功能1, 编译为HAR包或Feature类型的HAP包 +│ ├── feature2 # 子功能2, 编译为HAR包或Feature类型的HAP包 │ └── ... -└── product # 必选。产品层目录, entry类型的module,编译后为HAP -``` - -部署模型B对应的代码工程结构抽象后一般如下所示: - - -``` -/application -├── common # 可选。公共特性目录, har类型的module -├── features # 可选。功能模块目录 -│ ├── feature1 # 子功能1, har类型的module -│ ├── feature2 # 子功能2, har类型的module -│ └── ... -└── product # 必选。产品层目录 - ├── wearable # 智能穿戴泛类目录, entry类型的module,编译后为HAP - ├── default # 默认设备泛类目录, entry类型的module,编译后为HAP +└── products # 必选。产品定制层 + ├── wearable # 智能穿戴泛类目录, 编译为Entry类型的HAP包 + ├── default # 默认设备泛类目录, 编译为Entry类型的HAP包 └── ... ``` > **说明:** -> 无论是用部署模型A还是部署模型B,在开发阶段,都应考虑**不同类型设备间最大程度的复用代码**,以减少开发及后续维护的工作量。 +> +> * 部署模型不同,相应的代码工程结构也有差异。部署模型A和部署模型B的主要差异点集中在product层:部署模型A在product目录下同一子目录中做功能和特性集成;部署模型B在product目录下不同子目录中对不同的产品做差异化的功能和特性集成。 +> +> +> * 开发阶段应考虑**不同类型设备间最大程度的复用代码**,以减少开发及后续维护的工作量。 +> * 整个代码工程最终构建出一个[APP包](#应用程序包结构),应用以APP包的形式发布到应用市场中。 + diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/layout-intro.md b/zh-cn/application-dev/key-features/multi-device-app-dev/layout-intro.md index df48b1506b22049fd7ce31e270ed3d5013390fe9..0ccdd7cb5bbc2680f4c691a112e19d3b4a348242 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/layout-intro.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/layout-intro.md @@ -9,6 +9,8 @@ | 自适应布局 | 当外部容器大小发生变化时,元素可以**根据相对关系自动变化**以适应外部容器变化的布局能力。相对关系如占比、固定宽高比、显示优先级等。当前自适应布局能力有7种:[拉伸能力](adaptive-layout.md#拉伸能力)、[均分能力](adaptive-layout.md#均分能力)、[占比能力](adaptive-layout.md#占比能力)、[缩放能力](adaptive-layout.md#缩放能力)、[延伸能力](adaptive-layout.md#延伸能力)、[隐藏能力](adaptive-layout.md#隐藏能力)、[折行能力](adaptive-layout.md#折行能力)。自适应布局能力可以实现界面显示随外部容器大小连续变化。 | | 响应式布局 | 当外部容器大小发生变化时,元素可以**根据断点、栅格或特定的特征(如屏幕方向、窗口宽高等)自动变化**以适应外部容器变化的布局能力。当前响应式布局能力有3种:[断点](responsive-layout.md#断点)、[媒体查询](responsive-layout.md#媒体查询)、[栅格布局](responsive-layout.md#栅格布局)。响应式布局可以实现界面随外部容器大小有级不连续变化,通常不同特征下的界面显示会有较大的差异。 | +> **说明:** +> 自适应布局多用于解决页面各区域内的布局差异,响应式布局多用于解决页面各区域间的布局差异。 自适应布局和响应式布局常常需要借助容器类组件实现,或与容器类组件搭配使用。 @@ -25,4 +27,3 @@ 接下来将依次介绍自适应布局和响应式布局,同时结合实际,通过典型布局场景以及典型页面场景详细介绍两种布局能力的用法。 - diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md b/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md index 0ea9287e72cb57e3213fe37976c53337b77cc65c..b07734807e721d3ee8b88d0c909f29f8777cfb2e 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/page-development-intro.md @@ -31,8 +31,8 @@ | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ | | [页面开发一多能力](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities) | 声明式开发范式 | 本章配套的示例代码,包括自适应布局、响应式布局、典型布局场景以及资源文件使用等。 | | [页面开发一多能力](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/JsAdaptiveCapabilities) | 类Web开发范式 | 本章配套的示例代码,包括自适应布局、响应式布局及资源文件使用等。 | +| [天气](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather) | 声明式开发范式 | 一多示例应用,以天气应用为例,演示如何使用一多能力实现包含多个页面的应用。 | | [应用市场首页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AppMarket) | 声明式开发范式 | 本章配套的示例代码,以应用市场首页为例,演示如何使用一多能力适配多设备(或多窗口尺寸)。 | | [音乐专辑页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/MusicAlbum) | 声明式开发范式 | 本章配套的示例代码,以音乐专辑页为例,演示如何使用一多能力适配多设备(或多窗口尺寸)。 | -| [蔬菜百科首页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Vegetable) | 声明式开发范式 | 一多示例页面,以蔬菜百科首页为例,演示如何使用一多能力适配多设备(或多窗口尺寸)。 | -| [天气](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather) | 声明式开发范式 | 一多示例应用,以天气应用为例,演示如何使用一多能力实现包含多个页面的应用。 | +| [设置应用页面](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Settings) | 声明式开发范式 | 本章配套的示例代码,以设置应用页面为例,演示如何使用一多能力适配多设备(或多窗口尺寸)。 | diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md index 3e3beb9373545f350855ca53f32e68b5e6e97c1d..f571a5f571ae4afc28bb28de4d27057fd9333690 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md @@ -29,9 +29,12 @@ | lg | [840, +∞) | > **说明:** +> > - 以设备屏幕宽度作为参照物,也可以实现类似的效果。考虑到应用可能以非全屏窗口的形式显示,以应用窗口宽度为参照物更为通用。 -> +> > - 开发者可以根据实际使用场景决定适配哪些断点。如xs断点对应的一般是智能穿戴类设备,如果确定某页面不会在智能穿戴设备上显示,则可以不适配xs断点。 +> +> - 可以根据实际需要在lg断点后面新增xl、xxl等断点,但注意新增断点会同时增加UX设计师及应用开发者的工作量,除非必要否则不建议盲目新增断点。 OpenHarmony提供了多种方法,判断应用当前处于何种断点,进而可以调整应用的布局。常见的监听断点变化的方法如下所示: @@ -45,69 +48,72 @@ OpenHarmony提供了多种方法,判断应用当前处于何种断点,进而 通过窗口对象监听断点变化的核心是获取窗口对象及注册窗口尺寸变化的回调函数。 -1. 在Ability的[onWindowStageCreate](../../application-models/uiability-lifecycle.md)生命周期回调中,获取并记录[窗口](../../reference/apis/js-apis-window.md)对象。 - +1. 在Ability的[onWindowStageCreate](../../application-models/uiability-lifecycle.md)生命周期回调中,通过[窗口](../../reference/apis/js-apis-window.md)对象获取启动时的应用窗口宽度并注册回调函数监听窗口尺寸变化。将窗口尺寸的长度单位[由px换算为vp](../../key-features/multi-device-app-dev/visual-basics.md#视觉基础)后,即可基于前文中介绍的规则得到当前断点值,此时可以使用[状态变量](../../quick-start/arkts-state-mgmt-application-level.md)记录当前的断点值方便后续使用。 + ```ts - // EntryAbility.ts - import Window from '@ohos.window'; - import UIAbility from '@ohos.app.ability.UIAbility'; - - export default class EntryAbility extends UIAbility { - // ... - onWindowStageCreate(windowStage) { - window.getTopWindow(this.context).then((windowObj) => { - AppStorage.SetOrCreate('windowObj', windowObj) - }) - } - // ... - } - ``` + // MainAbility.ts + import window from '@ohos.window' + import display from '@ohos.display' -2. 在页面中,通过窗口对象获取启动时的应用窗口宽度,同时注册回调函数监听窗口尺寸变化。 - - ```ts - @Entry - @Component - struct Index { - @State private currentBreakpoint: string = 'sm' - + export default class MainAbility extends Ability { + private windowObj: window.Window + private curBp: string + ... + // 根据当前窗口尺寸更新断点 private updateBreakpoint(windowWidth) { - if (windowWidth < 320) { - this.currentBreakpoint = 'xs' - return - } - if (windowWidth < 520) { - this.currentBreakpoint = 'sm' - return + // 将长度的单位由px换算为vp + let windowWidthVp = windowWidth / (display.getDefaultDisplaySync().densityDPI / 160) + let newBp: string = '' + if (windowWidthVp < 320) { + newBp = 'xs' + } else if (windowWidthVp < 520) { + newBp = 'sm' + } else if (windowWidthVp < 840) { + newBp = 'md' + } else { + newBp = 'lg' } - if (windowWidth < 840) { - this.currentBreakpoint = 'md' - return + if (this.curBp !== newBp) { + this.curBp = newBp + // 使用状态变量记录当前断点值 + AppStorage.SetOrCreate('currentBreakpoint', this.curBp) } - this.currentBreakpoint = 'lg' } - - aboutToAppear() { - let windowObj: window.Window = AppStorage.Get('windowObj') - // 获取应用启动时的窗口尺寸 - windowObj.getProperties().then((windowProperties) => { - this.updateBreakpoint(px2vp(windowProperties.windowRect.width)) - }) - - // 注册回调函数,监听窗口尺寸变化 - windowObj.on('windowSizeChange', (data) => { - this.updateBreakpoint(px2vp(data.width)) + + onWindowStageCreate(windowStage: window.WindowStage) { + windowStage.getMainWindow().then((windowObj) => { + this.windowObj = windowObj + // 获取应用启动时的窗口尺寸 + this.updateBreakpoint(windowObj.getWindowProperties().windowRect.width) + // 注册回调函数,监听窗口尺寸变化 + windowObj.on('windowSizeChange', (windowSize)=>{ + this.updateBreakpoint(windowSize.width) + }) }); + ... } - - aboutToDisappear() { - let windowObj: window.Window = AppStorage.Get('windowObj') - windowObj.off('windowSizeChange') + + // 窗口销毁时,取消窗口尺寸变化监听 + onWindowStageDestroy() { + if (this.windowObj) { + this.windowObj.off('windowSizeChange') + } } - + ... + } + ``` + +2. 在页面中,获取及使用当前的断点。 + + ```ts + @Entry + @Component + struct Index { + @StorageProp('currentBreakpoint') curBp: string = 'sm' + build() { Flex({justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center}) { - Text(this.currentBreakpoint).fontSize(50).fontWeight(FontWeight.Medium) + Text(this.curBp).fontSize(50).fontWeight(FontWeight.Medium) } .width('100%') .height('100%') @@ -116,7 +122,7 @@ OpenHarmony提供了多种方法,判断应用当前处于何种断点,进而 ``` 3. 运行及验证效果。 - | | | | + | | | | | -------- | -------- | -------- | | ![zh-cn_image_0000001336485520](figures/zh-cn_image_0000001336485520.jpg) | ![zh-cn_image_0000001386645965](figures/zh-cn_image_0000001386645965.jpg) | ![zh-cn_image_0000001386325621](figures/zh-cn_image_0000001386325621.jpg) | diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/settings-application-page.md b/zh-cn/application-dev/key-features/multi-device-app-dev/settings-application-page.md new file mode 100644 index 0000000000000000000000000000000000000000..aab0b9802480e7d4f07adbccd32df8a82f0bb761 --- /dev/null +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/settings-application-page.md @@ -0,0 +1,166 @@ +# 设置应用页面 + +本小节以“设置”应用页面为例,介绍如何使用自适应布局能力和响应式布局能力适配不同尺寸窗口。本示例已经在[OpenHarmony应用示例](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Settings)中开源,读者可以根据需要自行下载源码并运行及查看效果。 + +## 页面设计 + +为充分利用屏幕尺寸优势,应用常常有在小屏设备上单栏显示,大屏设备上左右分两栏显示的设计,设置应用页面设计如下。 + +![](figures/settings_ux.png) + +观察“设置”应用页面设计,不同断点下“设置主页”、“WLAN页面”和“更多WLAN设置页面”几乎完全一致,只是在sm断点下采用单栏显示,在md和lg断点下采用双栏显示。 + +在前面的典型页面场景中,已经介绍了如何分析及实现不同断点下设计相似的单个页面,本小节将展开介绍如何实现不同断点下存在单栏和双栏设计的场景。 + +为了方便读者理解,本小节将围绕以下三个问题进行介绍。 + +1. [如何实现单/双栏的显示效果](#如何实现单/双栏的显示效果) +2. [如何实现点击跳转或刷新](#如何实现点击跳转或刷新) +3. [如何实现多级跳转](#如何实现多级跳转) + +## 如何实现单/双栏的显示效果 + +开发者可以使用Row、Column、[RowSplit](../../reference/arkui-ts/ts-container-rowsplit.md)等基础的组件,实现分栏显示的效果,但是需要较多的开发工作量。方舟开发框架在API 9重构了[Navigation组件](../../reference/arkui-ts/ts-basic-components-navigation.md),开发者可以通过配置Navigation组件的属性,控制其按照单栏或双栏的效果进行显示。 + +Navigation组件由Navbar和Content两部分区域组成,Navigation组件支持Stack、Split以及Auto三种模式。Stack及Split模式下Navigation组件的表现如下图所示。 + +* Stack模式 + + ![](figures/settings_navigation_stack.png) + +* Split模式 + + ![](figures/settings_navigation_split.png) + +* Auto模式 + + Auto模式是指Navigation组件可以根据应用窗口尺寸,自动选择合适的模式:窗口宽度小于520vp时,采用Stack模式显示;窗口宽度大于等于520vp时,采用Split模式显示。当窗口尺寸发生改变时,Navigation组件也会自动在Stack模式和Split模式之间切换。 + +> **说明:** +> +> * Navigation组件提供的title、navBarWidth、navBarPosition等属性来调整其显示效果。Navigation组件样式的配置与其它组件类似,这里不做赘述。 +> * 首次加载Navigation组件所在的页面时,如果Navigation组件处于Split模式,Navigation组件会自动激活其第一个NavRouter孩子节点(后文会展开介绍NavRouter)来刷新Content区域的显示。 + +设置主页的核心代码如下所示。Navigation组件默认处于Auto模式,其样式会根据应用窗口尺寸在单栏和双栏之间自动切换。 + +```typescript +@Entry +@Component +struct Index { + build() { + Navigation() { + SettingList() + } + .title($r('app.string.settings')) + .navBarWidth('40%') + .width('100%') + .height('100%') + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + } +} +``` + + + +## 如何实现点击跳转或刷新 + +Navigation组件通常搭配[NavRouter组件](../../reference/arkui-ts/ts-basic-components-navrouter.md)以及[NavDestination组件](../../reference/arkui-ts/ts-basic-components-navdestination.md)一起使用: + +* NavRouter组件用于控制Navigation组件Content区域的显示和刷新逻辑。 +* NavDestination组件用于实际刷新Navigation组件Content区域的显示。 + +### 刷新控制 + +NavRouter组件用于控制Navigation组件中Content区域的刷新逻辑,其必须包含两个孩子节点。 + +| | 节点类型 | 节点功能 | +| -------------- | ------------------ | ----------------------------------- | +| 第一个孩子节点 | 容器类组件 | 直接控制NavRouter的显示效果 | +| 第二个孩子节点 | NavDestination组件 | 刷新Navigation组件Content区域的显示 | + +NavRouter组件默认提供了点击响应处理,不需要开发者自定义点击事件逻辑。另外,NavRouter组件还提供了onStateChange回调事件,用于通知开发者NavRouter的状态:用户点击NavRouter,激活NavRouter并加载对应的NavDestination子组件时,回调onStateChange(true);NavRouter对应的NavDestination子组件不再显示时,回调onStateChange(false)。 + +![img](figures/settings_navrouter.png) + +结合设置应用的具体场景来看,上图1号小红框是NavRouter的第一个孩子节点,2号红框是NavRouter的第二个孩子节点,相应的核心代码实现如下。 + +```typescript +@Component +export struct WlanSettingItem { + @LocalStorageLink('selectedLabel') selectedLabel: string = '' + + build() { + Column() { + NavRouter() { + MainItem({ + title: $r('app.string.wifiTab'), + tag: 'UX', + icon: $r('app.media.wlan'), + label: 'WLAN' + }) + + NavDestination() { + WlanSetting() + } + .title($r('app.string.wifiTab')) + .backgroundColor($r('sys.color.ohos_id_color_sub_background')) + } + } + } +} +``` + +### 显示刷新 + +NavDestination组件用于实际刷新Navigation组件Content区域的显示。激活后的NavRouter对应的NavDestination组件,会占满整个Content区域并刷新其显示。 + +开发者可以通过NavDestination组件提供的如下属性,调整其最终显示效果: + +- backgroundColor:设置NavDestination组件的背景色。 +- title:自定义NavDestination组件的标题。 +- hideTitleBar:隐藏NavDestination组件的标题栏。 + +特别的,Navigation组件会根据当前的状态决定是否在NavDestination组件标题栏起始部分自动添加返回键图标。当Navigation组件添加了返回键图标时,还可以自动响应及处理系统三键导航中的返回键事件。 + +![](figures/settings_navdestination_title.png) + +## 如何实现多级跳转 + +可以在NavDesination组件中,继续使用NavRouter组件,以实现多级跳转。多级跳转场景下,Navigation组件同样会根据当前的状态决定是否自动添加返回键图标及响应系统三键导航中的返回键事件。 + +| 一级页面 | 二级页面 | +| --------------------------------- | ----------------------------------- | +| ![](figures/settings_primary.png) | ![](figures/settings_secondary.png) | + + +结合具体场景,红框3是一个NavRouter组件,点击后可以控制Navigation组件中的Content区域刷新为红框4对应的NavDestination组件吗,其核心代码实现如下所示。 + +```typescript +@Component +export struct WlanMoreSettingItem { + @LocalStorageLink('selectedLabel') selectedLabel: string = '' + + build() { + NavRouter() { + SubItemArrow({ title: $r('app.string.moreWlanSettings') }) + + NavDestination() { + WlanMoreSetting() + } + .title($r('app.string.moreWlanSettings')) + .backgroundColor($r('sys.color.ohos_id_color_sub_background')) + } + } +} +``` + +## 总结 + +![](figures/settings_navigation_structure.png) + +本示例的基础导航结构上图所示: + +* 激活`SettingList`中的`WLANSettingItem`,可以加载及显示`WlanSetting`。 +* 激活`WlanSetting`中的`WlanMoreSettingItem`,可以加载及显示`WlanMoreSetting`。 + +Navigation组件支持自动切换单栏和双栏的显示效果,同时可以根据当前状态自动添加返回键及响应系统的返回键事件。借助Navigation组件,开发者不用关心单栏和双栏场景的差异而更关注于应用本身,极大的减少开发工作量及提高开发效率。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md index 21080e5e0227ed97d60beacf4bd47390e04e3ec0..4bb565e096bb61022c3f76f9256e0ed31054ed74 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md @@ -4,18 +4,20 @@ 虽然不同应用的页面千变万化,但对其进行拆分和分析,页面中的很多布局场景是相似的。本小节将介绍如何借助自适应布局、响应式布局以及常见的容器类组件,实现应用中的典型布局场景。 - | 布局场景 | 实现方案 | +| 布局场景 | 实现方案 | | -------- | -------- | -| [页签栏](#页签栏) | Tab组件 + 响应式布局 | -| [运营横幅(Banner)](#运营横幅banner) | Swiper组件 + 响应式布局 | -| [网格](#网格) | Grid组件 / List组件 + 响应式布局 | -| [侧边栏](#侧边栏) | SiderBar组件 + 响应式布局 | -| [大图浏览](#大图浏览) | Image组件 | -| [操作入口](#操作入口) | Scroll组件+Row组件横向均分 | -| [顶部](#顶部) | 栅格组件 | -| [缩进布局](#缩进布局) | 栅格组件 | -| [挪移布局](#挪移布局) | 栅格组件 | -| [重复布局](#重复布局) | 栅格组件 | +| [页签栏](#页签栏) | Tab组件 + 响应式布局 | +| [运营横幅(Banner)](#运营横幅banner) | Swiper组件 + 响应式布局 | +| [网格](#网格) | Grid组件 / List组件 + 响应式布局 | +| [侧边栏](#侧边栏) | SiderBar组件 + 响应式布局 | +| [单/双栏](#单/双栏) | Navigation组件 + 响应式布局 | +| [自定义弹窗](#自定义弹窗) | CustomDialogController组件 + 响应式布局 | +| [大图浏览](#大图浏览) | Image组件 | +| [操作入口](#操作入口) | Scroll组件+Row组件横向均分 | +| [顶部](#顶部) | 栅格组件 | +| [缩进布局](#缩进布局) | 栅格组件 | +| [挪移布局](#挪移布局) | 栅格组件 | +| [重复布局](#重复布局) | 栅格组件 | > **说明:** @@ -418,6 +420,239 @@ struct SideBarSample { } ``` +## 单/双栏 + +**布局效果** + +| sm | md | lg | +| ------------------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | +| 单栏显示,在首页中点击选项可以显示详情。
点击详情上方的返回键图标或使用系统返回键可以返回到主页。 | 双栏显示,点击左侧不同的选项可以刷新右侧的显示。 | 双栏显示,点击左侧不同的选项可以刷新右侧的显示。 | +| ![](figures/navigation_sm.png) | ![](figures/navigation_md.png) | ![](figures/navigation_lg.png) | + +**实现方案** + +单/双栏场景可以使用[Navigation组件](../../reference/arkui-ts/ts-basic-components-navigation.md)实现,Navigation组件可以根据窗口宽度自动切换单/双栏显示,减少开发工作量。 + +**参考代码** + +``` +@Component +struct Details { + private imageSrc: Resource + build() { + Column() { + Image(this.imageSrc) + .objectFit(ImageFit.Contain) + .height(300) + .width(300) + } + .justifyContent(FlexAlign.Center) + .width('100%') + .height('100%') + } +} + +@Component +struct Item { + private imageSrc: Resource + private label: string + + build() { + NavRouter() { + Text(this.label) + .fontSize(24) + .fontWeight(FontWeight.Bold) + .borderRadius(5) + .backgroundColor('#FFFFFF') + .textAlign(TextAlign.Center) + .width(180) + .height(36) + NavDestination() { + Details({imageSrc: this.imageSrc}) + }.title(this.label) + } + } +} + +@Entry +@Component +struct NavigationSample { + build() { + Navigation() { + Column({space: 30}) { + Item({label: 'moon', imageSrc: $r('app.media.my_image_moon')}) + Item({label: 'sun', imageSrc: $r('app.media.my_image')}) + } + .justifyContent(FlexAlign.Center) + .height('100%') + .width('100%') + } + .mode(NavigationMode.Auto) + .backgroundColor('#F1F3F5') + .height('100%') + .width('100%') + .navBarWidth('40%') + .hideToolBar(true) + .title('Sample') + } +} +``` + + + +## 自定义弹窗 + +**布局效果** + +| sm | md | lg | +| -------------------------------------------- | --------------------------------------- | --------------------------------------- | +| 弹窗居中显示,
与窗口左右两侧各间距24vp。 | 弹窗居中显示,其宽度约为窗口宽度的1/2。 | 弹窗居中显示,其宽度约为窗口宽度的1/3。 | +| ![](figures/custom_dialog_sm.png) | ![](figures/custom_dialog_md.png) | ![](figures/custom_dialog_lg.png) | + +**实现方案** + +自定义弹窗通常通过[CustomDialogController](../../reference/arkui-ts/ts-methods-custom-dialog-box.md)实现,有两种方式实现本场景的目标效果: + +* 通过gridCount属性配置自定义弹窗的宽度。 + + 系统默认对不同断点下的窗口进行了栅格化:sm断点下为4栅格,md断点下为8栅格,lg断点下为12栅格。通过gridCount属性可以配置弹窗占据栅格中的多少列,将该值配置为4即可实现目标效果。 + +* 将customStyle设置为true,即弹窗的样式完全由开发者自定义。 + + 开发者自定义弹窗样式时,开发者可以根据需要配置弹窗的宽高和背景色(非弹窗区域保持默认的半透明色)。自定义弹窗样式配合[栅格组件](../../reference/arkui-ts/ts-container-gridrow.md)同样可以实现目标效果。 + +**参考代码** + +``` +@Entry +@Component +struct CustomDialogSample { + // 通过gridCount配置弹窗的宽度 + dialogControllerA: CustomDialogController = new CustomDialogController({ + builder: CustomDialogA ({ + cancel: this.onCancel, + confirm: this.onConfirm + }), + cancel: this.onCancel, + autoCancel: true, + gridCount: 4, + customStyle: false + }) + // 自定义弹窗样式 + dialogControllerB: CustomDialogController = new CustomDialogController({ + builder: CustomDialogB ({ + cancel: this.onCancel, + confirm: this.onConfirm + }), + cancel: this.onCancel, + autoCancel: true, + customStyle: true + }) + + onCancel() { + console.info('callback when dialog is canceled') + } + + onConfirm() { + console.info('callback when dialog is confirmed') + } + + build() { + Column() { + Button('CustomDialogA').margin(12) + .onClick(() => { + this.dialogControllerA.open() + }) + Button('CustomDialogB').margin(12) + .onClick(() => { + this.dialogControllerB.open() + }) + }.width('100%').height('100%').justifyContent(FlexAlign.Center) + } +} + +@CustomDialog +struct CustomDialogA { + controller: CustomDialogController + cancel: () => void + confirm: () => void + + build() { + Column() { + Text('是否删除此联系人?') + .fontSize(16) + .fontColor('#E6000000') + .margin({bottom: 8, top: 24, left: 24, right: 24}) + Row() { + Text('取消') + .fontColor('#007DFF') + .fontSize(16) + .layoutWeight(1) + .textAlign(TextAlign.Center) + .onClick(()=>{ + this.controller.close() + this.cancel() + }) + Line().width(1).height(24).backgroundColor('#33000000').margin({left: 4, right: 4}) + Text('删除') + .fontColor('#FA2A2D') + .fontSize(16) + .layoutWeight(1) + .textAlign(TextAlign.Center) + .onClick(()=>{ + this.controller.close() + this.confirm() + }) + }.height(40) + .margin({left: 24, right: 24, bottom: 16}) + }.borderRadius(24) + } +} + +@CustomDialog +struct CustomDialogB { + controller: CustomDialogController + cancel: () => void + confirm: () => void + + build() { + GridRow({columns: {sm: 4, md: 8, lg: 12}}) { + GridCol({span: 4, offset: {sm: 0, md: 2, lg: 4}}) { + Column() { + Text('是否删除此联系人?') + .fontSize(16) + .fontColor('#E6000000') + .margin({bottom: 8, top: 24, left: 24, right: 24}) + Row() { + Text('取消') + .fontColor('#007DFF') + .fontSize(16) + .layoutWeight(1) + .textAlign(TextAlign.Center) + .onClick(()=>{ + this.controller.close() + this.cancel() + }) + Line().width(1).height(24).backgroundColor('#33000000').margin({left: 4, right: 4}) + Text('删除') + .fontColor('#FA2A2D') + .fontSize(16) + .layoutWeight(1) + .textAlign(TextAlign.Center) + .onClick(()=>{ + this.controller.close() + this.confirm() + }) + }.height(40) + .margin({left: 24, right: 24, bottom: 16}) + }.borderRadius(24).backgroundColor('#FFFFFF') + } + }.margin({left: 24, right: 24}) + } +} +``` + + ## 大图浏览 diff --git a/zh-cn/application-dev/media/avplayer-playback.md b/zh-cn/application-dev/media/avplayer-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..bf14c204cedc43a1d601462a5a31482e4fa741a8 --- /dev/null +++ b/zh-cn/application-dev/media/avplayer-playback.md @@ -0,0 +1,520 @@ +# AVPlayer播放器开发指导 + +## 简介 + +AVPlayer主要工作是将Audio/Video媒体资源转码为可供渲染的图像和可听见的音频模拟信号,并通过输出设备进行播放,同时对播放任务进行管理,包括开始播放、暂停播放、停止播放、释放资源、设置音量、跳转播放位置、获取轨道信息等功能控制。 + +## 运作机制 + +该模块提供了播放状态变化示意图[AVPlayerState](../reference/apis/js-apis-media.md#avplayerstate9)、音频播放外部模块交互图和视频播放外部模块交互图。 + +**图1** 播放状态变化示意图 + +![zh-ch_image_avplayer_state_machine](figures/zh-ch_image_avplayer_state_machine.png) + + +**图2** 音频播放外部模块交互图 + +![zh-ch_image_avplayer_audio](figures/zh-ch_image_avplayer_audio.png) + +**说明**:应用通过调用JS接口层提供的AVPlayer js接口实现相应功能时,框架层会通过Player Framework的播放服务解析成音频数据流,音频数据流经过软件解码后输出至Audio Framework的音频服务,由音频子系统输出至硬件接口层的音频HDI,实现音频播放功能。完整的音乐播放器工作需要:应用(应用适配)、Player Framework、Audio Framework、Audio HDI(驱动适配)共同实现。 + +*注意:音频播放需要音频子系统配合* + +1. 应用把url传递给AVPlayer JS。 +2. 播放服务把音频PCM数据流输出给音频服务,音频服务输出给Audio HDI。 + + +**图3** 视频播放外部模块交互图 + +![zh-ch_image_avplayer_video](figures/zh-ch_image_avplayer_video.png) + +**说明**:应用通过调用JS接口层提供的AVPlayer js接口实现相应功能时,框架层会通过Player Framework的播放服务解析成单独的音频数据流和视频数据流,音频数据流经过软件解码后输出至Audio Framework的音频服务,由音频子系统输出至硬件接口层的音频HDI,实现音频播放功能。视频数据流经过硬件(推荐)/软件解码后输出至Graphic Framework的渲染服务(Renderer Service),由RS子系统输出至硬件接口层的显示HDI。完整的视频播放器工作需要:应用(应用适配)、XCompomemt组件、Player Framework、Graphic Framework、Audio Framework、Display HDI(驱动适配)和Audio HDI(驱动适配)共同实现。 + +*注意:视频播放需要显示、音频、解码等多个子系统配合。* + +1. 应用从Xcomponent组件获取surfaceID,[获取方式](../reference/arkui-ts/ts-basic-components-xcomponent.md)。 +2. 应用把url、surfaceID传递给AVPlayer JS。 +3. 播放服务把视频ES数据流输出给Codec HDI,解码获得视频帧(NV12/NV21/RGBA)。 +4. 播放服务把音频PCM数据流输出给音频服务,音频服务输出给Audio HDI。 +5. 播放服务把视频帧(NV12/NV21/RGBA)输出给RS服务,RS服务输出给Display HDI。 + +## 兼容性说明 + +推荐使用主流的播放格式和主流分辨率,不建议开发者自制非常或者异常码流,以免产生无法播放、卡住、花屏等兼容性问题。若发生此类问题不会影响系统,退出码流播放即可。 + +主流的播放格式和主流分辨率如下: + +| 视频容器规格 | 规格描述 | 分辨率 | +| :----------: | :-----------------------------------------------: | :--------------------------------: | +| mp4 | 视频格式:H264/MPEG2/MPEG4/H263 音频格式:AAC/MP3 | 主流分辨率,如1080P/720P/480P/270P | +| mkv | 视频格式:H264/MPEG2/MPEG4/H263 音频格式:AAC/MP3 | 主流分辨率,如1080P/720P/480P/270P | +| ts | 视频格式:H264/MPEG2/MPEG4 音频格式:AAC/MP3 | 主流分辨率,如1080P/720P/480P/270P | +| webm | 视频格式:VP8 音频格式:VORBIS | 主流分辨率,如1080P/720P/480P/270P | + +| 音频容器规格 | 规格描述 | +| :----------: | :----------: | +| m4a | 音频格式:AAC | +| aac | 音频格式:AAC | +| mp3 | 音频格式:MP3 | +| ogg | 音频格式:VORBIS | +| wav | 音频格式:PCM | + +## 开发指导 + +详细API含义可参考:[媒体服务API文档AVPlayer](../reference/apis/js-apis-media.md#avplayer9) + +### 播放流程说明 + +播放的全流程场景包含:创建实例,设置资源,设置窗口(视频),准备播放(获取轨道信息/音量/倍速/焦点模式/缩放模式/设置bitrates),播控(播放/暂停/Seek/音量/停止),重置资源,销毁播放 + +1:创建实例[createAVPlayer()](../reference/apis/js-apis-media.md#mediacreateavplayer9),AVPlayer初始化[idle](#avplayer_state)状态 + +2:设置业务需要的监听事件,搭配全流程场景使用 + +3:设置资源 [url](../reference/apis/js-apis-media.md#avplayer_属性),AVPlayer进入[initialized](#avplayer_state)状态,此时可以设置视频窗口 [surfaceId](../reference/apis/js-apis-media.md#avplayer_属性),支持的规格可参考:[AVPlayer属性说明](../reference/apis/js-apis-media.md#avplayer_属性) + +4:准备播放 [prepare()](../reference/apis/js-apis-media.md#avplayer_prepare),AVPlayer进入[prepared](#avplayer_state)状态 + +5:视频播控:播放 [play()](../reference/apis/js-apis-media.md#avplayer_play),暂停 [pause()](../reference/apis/js-apis-media.md#avplayer_pause),跳转 [seek()](../reference/apis/js-apis-media.md#avplayer_seek),停止 [stop()](../reference/apis/js-apis-media.md#avplayer_stop) 等操作 + +6:重置资源 [reset()](../reference/apis/js-apis-media.md#avplayer_reset),AVPlayer重新进入[idle](#avplayer_state)状态,允许更换资源 [url](../reference/apis/js-apis-media.md#avplayer_属性) + +7:销毁播放 [release()](../reference/apis/js-apis-media.md#avplayer_release),AVPlayer进入[released](#avplayer_state)状态,退出播放 + +> **说明:** +> +> prepared/playing/paused/compeled 状态时,播放引擎处于工作状态,这需要占用系统较多的运行内存,当客户端暂时不使用播放器时,要求调用 reset() 或 release() 回收。 + +### 监听事件 + +| 事件类型 | 说明 | +| ------------------------------------------------- | ------------------------------------------------------------ | +| stateChange | 必要事件,监听播放器的状态机 | +| error | 必要事件,监听播放器的错误信息 | +| durationUpdate | 用于进度条,监听进度条长度,刷新资源时长 | +| timeUpdate | 用于进度条,监听进度条当前位置,刷新当前时间 | +| seekDone | 响应api调用,监听seek()请求完成情况 | +| speedDone | 响应api调用,监听setSpeed()请求完成情况 | +| volumeChange | 响应api调用,监听setVolume()请求完成情况 | +| bitrateDone | 响应api调用,用于HLS协议流,监听setBitrate()请求完成情况 | +| availableBitrates | 用于HLS协议流,监听HLS资源的可选bitrates,用于setBitrate() | +| bufferingUpdate | 用于网络播放,监听网络播放缓冲信息 | +| startRenderFrame | 用于视频播放,监听视频播放首帧渲染时间 | +| videoSizeChange | 用于视频播放,监听视频播放的宽高信息,可用于调整窗口大小、比例 | +| audioInterrupt | 用于视频播放,监听音频焦点切换信息,搭配属性audioInterruptMode使用 | + +### + +### 全量接口示例 + +```js +import media from '@ohos.multimedia.media' +import audio from '@ohos.multimedia.audio'; +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private count:number = 0 + private avPlayer + private surfaceID:string // surfaceID用于播放画面显示,具体的值需要通过Xcomponent接口获取,相关文档链接见上面Xcomponent创建方法 + + // 注册avplayer回调函数 + setAVPlayerCallback() { + // 状态机变化回调函数 + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // 成功调用reset接口后触发该状态机上报 + console.info(TAG + 'state idle called') + this.avPlayer.release() // 释放avplayer对象 + break; + case 'initialized': // avplayer 设置播放源后触发该状态上报 + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // 设置显示画面,当播放的资源为纯音频时无需设置 + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // prepare调用成功后上报该状态机 + console.info(TAG + 'state prepared called') + this.avPlayer.play() // 调用播放接口开始播放 + break; + case 'playing': // play成功调用后触发该状态机上报 + console.info(TAG + 'state playing called') + if (this.count == 0) { + this.avPlayer.pause() // 调用暂停播放接口 + } else { + this.avPlayer.seek(10000, media.SeekMode.SEEK_PREV_SYNC) // 前向seek置10秒处,触发seekDone回调函数 + } + break; + case 'paused': // pause成功调用后触发该状态机上报 + console.info(TAG + 'state paused called') + if (this.count == 0) { + this.count++ + this.avPlayer.play() // 继续调用播放接口开始播放 + } + break; + case 'completed': // 播放结束后触发该状态机上报 + console.info(TAG + 'state completed called') + this.avPlayer.stop() //调用播放结束接口 + break; + case 'stopped': // stop接口成功调用后触发该状态机上报 + console.info(TAG + 'state stopped called') + this.avPlayer.reset() // 调用reset接口初始化avplayer状态 + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + // 时间上报监听函数 + this.avPlayer.on('timeUpdate', (time:number) => { + console.info(TAG + 'timeUpdate success,and new time is :' + time) + }) + // 音量变化回调函数 + this.avPlayer.on('volumeChange', (vol:number) => { + console.info(TAG + 'volumeChange success,and new volume is :' + vol) + this.avPlayer.setSpeed(media.AVPlayerSpeed.SPEED_FORWARD_2_00_X) // 设置两倍速播放,并触发speedDone回调 + }) + // 视频播放结束触发回调 + this.avPlayer.on('endOfStream', () => { + console.info(TAG + 'endOfStream success') + }) + // seek操作回调函数 + this.avPlayer.on('seekDone', (seekDoneTime:number) => { + console.info(TAG + 'seekDone success,and seek time is:' + seekDoneTime) + this.avPlayer.setVolume(0.5) // 设置音量为0.5,并触发volumeChange回调函数 + }) + // 设置倍速播放回调函数 + this.avPlayer.on('speedDone', (speed:number) => { + console.info(TAG + 'speedDone success,and speed value is:' + speed) + }) + // bitrate设置成功回调函数 + this.avPlayer.on('bitrateDone', (bitrate:number) => { + console.info(TAG + 'bitrateDone success,and bitrate value is:' + bitrate) + }) + // 缓冲上报回调函数 + this.avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { + console.info(TAG + 'bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value) + }) + // 首帧上报回调函数 + this.avPlayer.on('startRenderFrame', () => { + console.info(TAG + 'startRenderFrame success') + }) + // 视频宽高上报回调函数 + this.avPlayer.on('videoSizeChange', (width: number, height: number) => { + console.info(TAG + 'videoSizeChange success,and width is:' + width + ', height is :' + height) + }) + // 焦点上报回调函数 + this.avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { + console.info(TAG + 'audioInterrupt success,and InterruptEvent info is:' + info) + }) + // HLS上报所有支持的比特率 + this.avPlayer.on('availableBitrates', (bitrates: Array) => { + console.info(TAG + 'availableBitrates success,and availableBitrates length is:' + bitrates.length) + }) + } + + async avPlayerDemo() { + // 创建avPlayer实例对象 + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 + // path路径的码流可通过"hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" 命令,将其推送到设备上 + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` + +### 正常播放场景 + +```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private avPlayer + private surfaceID:string // surfaceID用于播放画面显示,具体的值需要通过Xcomponent接口获取,相关文档链接见上面Xcomponent创建方法 + + // 注册avplayer回调函数 + setAVPlayerCallback() { + // 状态机变化回调函数 + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // 成功调用reset接口后触发该状态机上报 + console.info(TAG + 'state idle called') + break; + case 'initialized': // avplayer 设置播放源后触发该状态上报 + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // 设置显示画面,当播放的资源为纯音频时无需设置 + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // prepare调用成功后上报该状态机 + console.info(TAG + 'state prepared called') + this.avPlayer.play() // 调用播放接口开始播放 + break; + case 'playing': // play成功调用后触发该状态机上报 + console.info(TAG + 'state playing called') + break; + case 'paused': // pause成功调用后触发该状态机上报 + console.info(TAG + 'state paused called') + break; + case 'completed': // 播放结束后触发该状态机上报 + console.info(TAG + 'state completed called') + this.avPlayer.stop() //调用播放结束接口 + break; + case 'stopped': // stop接口成功调用后触发该状态机上报 + console.info(TAG + 'state stopped called') + this.avPlayer.release() // 调用reset接口初始化avplayer状态 + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + } + + async avPlayerDemo() { + // 创建avPlayer实例对象 + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 + // path路径的码流可通过"hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" 命令,将其推送到设备上 + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` + +### 视频切换场景 + +```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private count:number = 0 + private avPlayer + private surfaceID:string // surfaceID用于播放画面显示,具体的值需要通过Xcomponent接口获取,相关文档链接见上面Xcomponent创建方法 + + // 注册avplayer回调函数 + setAVPlayerCallback() { + // 状态机变化回调函数 + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // 成功调用reset接口后触发该状态机上报 + console.info(TAG + 'state idle called') + break; + case 'initialized': // avplayer 设置播放源后触发该状态上报 + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // 设置显示画面,当播放的资源为纯音频时无需设置 + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // prepare调用成功后上报该状态机 + console.info(TAG + 'state prepared called') + this.avPlayer.loop = true // 设置单曲循环播放,单曲循环播放至结尾后会触发endOfStream回调 + this.avPlayer.play() // 调用播放接口开始播放 + break; + case 'playing': // play成功调用后触发该状态机上报 + console.info(TAG + 'state playing called') + break; + case 'paused': // pause成功调用后触发该状态机上报 + console.info(TAG + 'state paused called') + break; + case 'completed': // 播放结束后触发该状态机上报 + console.info(TAG + 'state completed called') + // 当第二次触发endOfStream回调后取消循环播放,再次播放到结尾后触发completed状态机上报 + this.avPlayer.stop() //调用播放结束接口 + break; + case 'stopped': // stop接口成功调用后触发该状态机上报 + console.info(TAG + 'state stopped called') + this.avPlayer.release() // 调用reset接口初始化avplayer状态 + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + // 视频播放结束触发回调 + this.avPlayer.on('endOfStream', () => { + console.info(TAG + 'endOfStream success') + if (this.count == 1) { + this.avPlayer.loop = false // 取消循环播放 + } else { + this.count++ + } + }) + } + + async avPlayerDemo() { + // 创建avPlayer实例对象 + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 + // path路径的码流可通过"hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" 命令,将其推送到设备上 + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` +### 单曲循环场景 + +```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private count:number = 0 + private avPlayer + private surfaceID:string // surfaceID用于播放画面显示,具体的值需要通过Xcomponent接口获取,相关文档链接见上面Xcomponent创建方法 + + async nextVideo() { + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 + // path路径的码流可通过"hdc file send D:\xxx\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" 命令,将其推送到设备上 + let path = pathDir + '/H264_MP3.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath // 再次触发initialized状态机上报 + } + + // 注册avplayer回调函数 + setAVPlayerCallback() { + // 状态机变化回调函数 + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // 成功调用reset接口后触发该状态机上报 + console.info(TAG + 'state idle called') + await this.nextVideo() // 切换下一个视频播放 + break; + case 'initialized': // avplayer 设置播放源后触发该状态上报 + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // 设置显示画面,当播放的资源为纯音频时无需设置 + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // prepare调用成功后上报该状态机 + console.info(TAG + 'state prepared called') + this.avPlayer.play() // 调用播放接口开始播放 + break; + case 'playing': // play成功调用后触发该状态机上报 + console.info(TAG + 'state playing called') + break; + case 'paused': // pause成功调用后触发该状态机上报 + console.info(TAG + 'state paused called') + break; + case 'completed': // 播放结束后触发该状态机上报 + console.info(TAG + 'state completed called') + if (this.count == 0) { + this.count++ + this.avPlayer.reset() //调用重置接口准备切换下一个视频 + } else { + this.avPlayer.release() //切换视频后播放至结尾释放avplayer对象 + } + break; + case 'stopped': // stop接口成功调用后触发该状态机上报 + console.info(TAG + 'state stopped called') + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + } + + async avPlayerDemo() { + // 创建avPlayer实例对象 + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 + // path路径的码流可通过"hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" 命令,将其推送到设备上 + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` + +## 相关示例 + +针对AVPlayer播放器开发,有以下相关示例可供参考: + +待补充 \ No newline at end of file diff --git a/zh-cn/application-dev/media/avrecorder.md b/zh-cn/application-dev/media/avrecorder.md new file mode 100644 index 0000000000000000000000000000000000000000..85c5d6081b9180cd9e0fa5ba1183f4ee19ecc2b5 --- /dev/null +++ b/zh-cn/application-dev/media/avrecorder.md @@ -0,0 +1,490 @@ +# 音视频录制开发指导 + +## 简介 + +音视频录制的主要工作是捕获音频信号,接收视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能,包括开始录制、暂停录制、恢复录制、停止录制、释放资源等功能控制。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。 + +## 运作机制 + +该模块提供了音视频录制状态变化示意图和音视频录制外部模块交互图。 + +**图1** 音视频录制状态变化示意图 + +![zh-ch_image_video_recorder_state_machine](figures/zh-ch_image_avrecorder_state_machine.png) + +**图2** 视频录制外部模块交互图--待修改 + +![zh-ch_image_video_recorder_zero](figures/zh-ch_image_avrecorder_module_interaction.png) + +**说明**:音频录制时,框架层会通过Native Framework的媒体服务,调用音频子系统通过音频HDI捕获音频数据,通过软件编码封装后保存至文件中,实现音频录制功能。视频录制时,由相机子系统通过视频HDI捕获图像数据,媒体服务将图像数据通过视频编码HDI编码,再将编码后的图像数据封装至文件中,实现视频录制功能。通过音视频录制组合,可分别实现纯音频录制、纯视频录制,音视频录制。 + +## 约束与限制 + +开发者在进行录制功能开发前,需要先对所开发的应用配置相应权限。涉及音频录制,需要获取麦克风权限(ohos.permission.MICROPHONE),权限配置相关内容可参考:[访问控制权限申请指导](../security/accesstoken-guidelines.md)。 + +使用相机进行视频录制还需要与相机模块配合,接口使用以及权限获取详见[相机管理](../reference/apis/js-apis-camera.md)。 + +## 开发指导 + +详细API含义可参考:[媒体服务API文档AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) + +媒体库相关流程含义可参考:[媒体库管理](../reference/apis/js-apis-medialibrary.md) + +相机相关流程含义可参考:[相机管理](../reference/apis/js-apis-camera.md) + +### 音视频录制全流程场景 + +音视频录制全流程场景包含:创建实例、设置录制参数、获取输入surface、开始录制、暂停录制、恢复录制、停止录制、释放资源等流程。 + +音频录制相关配置参数范围,受到设备编解码性能,音频子系统性能等综合限制。 + +视频录制相关配置参数范围,受到设备编解码性能,相机子系统性能等综合限制。 + +``` +import media from '@ohos.multimedia.media' +import camera from '@ohos.multimedia.camera' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +export class AVRecorderDemo { + private testFdNumber; // 用于保存fd地址 + + // 获取录制的音频文件fileName对应的fd,需借助媒体库能力。使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA. + async getFd(fileName) { + // 实现方式参考媒体库资料文档。 + this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54 + } + + // 当promise接口发生错误上上报的错误回调接口 + failureCallback(error) { + console.info('error happened, error message is ' + error.message); + } + + // 当promise接口发生异常时,系统调用的错误回调接口 + catchCallback(error) { + console.info('catch error happened, error message is ' + error.message); + } + + async AVRecorderDemo() { + let AVRecorder; // AVRecorder空对象在createAVRecorder成功后赋值 + let surfaceID; // 从getInputSurface获取surfaceID,传递给相机的videoOutput + await this.getFd('01.mp4'); + + // 音视频录制相关参数配置 + let avProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 + } + let avConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : avProfile, + url : 'fd://', + rotation : 0, + location : { latitude : 30, longitude : 130 } + } + + // 创建AVRecorder对象 + await media.createAVRecorder().then((recorder) => { + console.info('case createAVRecorder called'); + if (typeof (recorder) != 'undefined') { + AVRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.info('createAVRecorder failed'); + } + }, this.failureCallback).catch(this.catchCallback); + + // 对象创建成功后创建on('stateChange')和on('error')监听回调用于监听状态机变化和错误上报 + AVRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state); + switch (state) { + // 用户可以根据需求在不同状态设置自己想要进行的行为 + case 'idle': + // 调用rest接口后触发idle状态;create后也在idle状态 + break; + case 'prepared': + // 调用prepare接口后触发prepared状态; + break; + case 'started': + // 调用start接口后触发started状态; + break; + case 'paused': + // 调用pause接口后触发paused状态; + break; + case 'stopped': + // 调用stop接口后触发stopped状态; + break; + case 'released': + // 调用release接口后触发released状态; + break; + case 'error': + // error状态说明底层出错,用户需排查错误,重新创建avRecorder; + break; + default: + console.info('case state is unknown'); + } + }); + AVRecorder.on('error', (err) => { + // 监听非接口类错误上报 + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); + }); + + // 调用prepare完成音频录制前的准备工作;底层实际是根据prepare的入参来判断是音频录制、视频录制还是音视频录制 + await AVRecorder.prepare(avConfig).then(() => { + console.info('prepare success'); + }, this.failureCallback).catch(this.catchCallback); + + // 包含视频的录制需要调用getInputSurface接口,并将返回值surfaceID传递给camera相关接口 + await AVRecorder.getInputSurface().then((surface) => { + console.info('getInputSurface success'); + surfaceID = surface; // surfaceID给camera的createVideoOutput()作为其中的一个入参 + }, this.failureCallback).catch(this.catchCallback); + + // 视频录制依赖相机相关接口,以下需要先调用相机起流接口后才能继续执行,具体的相机接口调用请参考sample用例 + // 视频录制启动接口 + await AVRecorder.start().then(() => { + console.info('start success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用pause接口时需要暂停camera出流 + await AVRecorder.pause().then(() => { + console.info('pause success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用resume接口时需要恢复camera出流 + await AVRecorder.resume().then(() => { + console.info('resume success'); + }, this.failureCallback).catch(this.catchCallback); + + // 停止camera出流后,停止视频录制 + await AVRecorder.stop().then(() => { + console.info('stop success'); + }, this.failureCallback).catch(this.catchCallback); + + // 重置录制相关配置 + await AVRecorder.reset().then(() => { + console.info('reset success'); + }, this.failureCallback).catch(this.catchCallback); + + // 关闭监听回调,如果用户不自行调用off接口,在调用release后,设置的回调接口也会无效 + AVRecorder.off('stateChange'); + AVRecorder.off('error'); + + // 释放视频录制相关资源并释放camera对象相关资源 + await AVRecorder.release().then(() => { + console.info('release success'); + }, this.failureCallback).catch(this.catchCallback); + + // 相关对象置null + AVRecorder = undefined; + surfaceID = undefined; + } +} +``` + +### 纯音频录制全流程场景 + +纯音频录制全流程场景包含:创建实例、设置录制参数、开始录制、暂停录制、恢复录制、停止录制、释放资源等流程。 + +音频录制相关配置参数范围,受到设备编解码性能,音频子系统性能等综合限制。 + +``` +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +export class AudioRecorderDemo { + private testFdNumber; // 用于保存fd地址 + + // 获取录制的音频文件fileName对应的fd,需借助媒体库能力。使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA + async getFd(fileName) { + // 实现方式参考媒体库资料文档。 + this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54 + } + + // 当promise接口发生错误上报的错误回调接口 + failureCallback(error) { + console.info('error happened, error message is ' + error.message); + } + + // 当promise接口发生异常时,系统调用的错误回调接口 + catchCallback(error) { + console.info('catch error happened, error message is ' + error.message); + } + + async audioRecorderDemo() { + let audioRecorder; // audioRecorder空对象在createAVRecorder成功后赋值 + await this.getFd('01.m4a'); + // 音频录制相关参数配置 + let audioProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + } + let audioConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + profile : audioProfile, + url : this.testFdNumber, + rotation : 0, + location : { latitude : 30, longitude : 130 } + } + + // 创建audioRecorder对象 + await media.createAVRecorder().then((recorder) => { + console.info('case createAVRecorder called'); + if (typeof (recorder) != 'undefined') { + audioRecorder = recorder; + console.info('createAudioRecorder success'); + } else { + console.info('createAudioRecorder failed'); + } + }, this.failureCallback).catch(this.catchCallback); + + // 对象创建成功后创建on('stateChange')和on('error')监听回调用于监听状态机变化和错误上报 + audioRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state); + switch (state) { + // 用户可以根据需求在不同状态设置自己想要进行的行为 + case 'idle': + // 调用rest接口后触发idle状态;create后也在idle状态 + break; + case 'prepared': + // 调用prepare接口后触发prepared状态; + break; + case 'started': + // 调用start接口后触发started状态; + break; + case 'paused': + // 调用pause接口后触发paused状态; + break; + case 'stopped': + // 调用stop接口后触发stopped状态; + break; + case 'released': + // 调用release接口后触发released状态; + break; + case 'error': + // error状态说明底层出错,用户需排查错误,重新创建avRecorder; + break; + default: + console.info('case state is unknown'); + } + }); + audioRecorder.on('error', (err) => { + // 监听非接口类错误上报 + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); + }); + + // 调用prepare完成音频录制前的准备工作;底层实际是根据prepare的入参来判断是音频录制、视频录制还是音视频录制 + await audioRecorder.prepare(audioConfig).then(() => { + console.info('prepare success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用start接口启动音频录制 + await audioRecorder.start().then(() => { + console.info('start success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用pause接口暂停音频录制 + await audioRecorder.pause().then(() => { + console.info('pause success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用resume接口恢复音频录制 + await audioRecorder.resume().then(() => { + console.info('resume success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用stop接口停止音频录制 + await audioRecorder.stop().then(() => { + console.info('stop success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用reset接口重置录制相关配置 + await audioRecorder.reset().then(() => { + console.info('reset success'); + }, this.failureCallback).catch(this.catchCallback); + + // 关闭监听回调,如果用户不自行调用off接口,在调用release后,设置的回调接口也会无效 + avRecorder.off('stateChange'); + avRecorder.off('error'); + + // 调用release接口释放音频录制相关资源 + await audioRecorder.release().then(() => { + console.info('release success'); + }, this.failureCallback).catch(this.catchCallback); + + // 相关对象置null + audioRecorder = undefined; + } +} + +``` + +### 纯视频录制全流程场景 + +纯视频录制全流程场景包含:创建实例、设置录制参数、获取输入surface、开始录制、暂停录制、恢复录制、停止录制、释放资源等流程。 + +视频录制相关配置参数范围,受到设备编解码性能,相机子系统性能等综合限制。 + +``` +import media from '@ohos.multimedia.media' +import camera from '@ohos.multimedia.camera' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +export class VideoRecorderDemo { + private testFdNumber; // 用于保存fd地址 + + // 获取录制的音频文件fileName对应的fd,需借助媒体库能力。使用mediaLibrary需要添加以下权限, ohos.permission.MEDIA_LOCATION、ohos.permission.WRITE_MEDIA、ohos.permission.READ_MEDIA. + async getFd(fileName) { + // 实现方式参考媒体库资料文档。 + this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54 + } + + // 当promise接口发生错误上上报的错误回调接口 + failureCallback(error) { + console.info('error happened, error message is ' + error.message); + } + + // 当promise接口发生异常时,系统调用的错误回调接口 + catchCallback(error) { + console.info('catch error happened, error message is ' + error.message); + } + + async videoRecorderDemo() { + let videoRecorder; // videoRecorder空对象在createAVRecorder成功后赋值 + let surfaceID; // 从getInputSurface获取surfaceID,传递给相机的videoOutput + await this.getFd('01.mp4'); + + // 纯视频录制相关参数配置 + let videoProfile = { + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 + } + let videoConfig = { + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : videoProfile, + url : 'fd://', + rotation : 0, + location : { latitude : 30, longitude : 130 } + } + + // 创建videoRecorder对象 + await media.createAVRecorder().then((recorder) => { + console.info('case createVideoRecorder called'); + if (typeof (recorder) != 'undefined') { + videoRecorder = recorder; + console.info('createVideoRecorder success'); + } else { + console.info('createVideoRecorder failed'); + } + }, this.failureCallback).catch(this.catchCallback); + + // 对象创建成功后创建on('stateChange')和on('error')监听回调用于监听状态机变化和错误上报 + videoRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state); + switch (state) { + // 用户可以根据需求在不同状态设置自己想要进行的行为 + case 'idle': + // 调用rest接口后触发idle状态;create后也在idle状态 + break; + case 'prepared': + // 调用prepare接口后触发prepared状态; + break; + case 'started': + // 调用start接口后触发started状态; + break; + case 'paused': + // 调用pause接口后触发paused状态; + break; + case 'stopped': + // 调用stop接口后触发stopped状态; + break; + case 'released': + // 调用release接口后触发released状态; + break; + case 'error': + // error状态说明底层出错,用户需排查错误,重新创建avRecorder; + break; + default: + console.info('case state is unknown'); + } + }); + videoRecorder.on('error', (err) => { + // 监听非接口类错误上报 + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); + }); + + // 调用prepare完成音频录制前的准备工作;底层实际是根据prepare的入参来判断是音频录制、视频录制还是音视频录制 + await videoRecorder.prepare(videoConfig).then(() => { + console.info('prepare success'); + }, this.failureCallback).catch(this.catchCallback); + + // 包含视频的录制需要调用getInputSurface接口,并将返回值surfaceID传递给camera相关接口 + await videoRecorder.getInputSurface().then((surface) => { + console.info('getInputSurface success'); + surfaceID = surface; // surfaceID给camera的createVideoOutput()作为其中的一个入参 + }, this.failureCallback).catch(this.catchCallback); + + // 视频录制依赖相机相关接口,以下需要先调用相机起流接口后才能继续执行,具体的相机接口调用请参考sample用例 + // 视频录制启动接口 + await videoRecorder.start().then(() => { + console.info('start success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用pause接口时需要暂停camera出流 + await videoRecorder.pause().then(() => { + console.info('pause success'); + }, this.failureCallback).catch(this.catchCallback); + + // 调用resume接口时需要恢复camera出流 + await videoRecorder.resume().then(() => { + console.info('resume success'); + }, this.failureCallback).catch(this.catchCallback); + + // 停止camera出流后,停止视频录制 + await videoRecorder.stop().then(() => { + console.info('stop success'); + }, this.failureCallback).catch(this.catchCallback); + + // 重置录制相关配置 + await videoRecorder.reset().then(() => { + console.info('reset success'); + }, this.failureCallback).catch(this.catchCallback); + + // 关闭监听回调,如果用户不自行调用off接口,在调用release后,设置的回调接口也会无效 + videoRecorder.off('stateChange'); + videoRecorder.off('error'); + + // 释放视频录制相关资源并释放camera对象相关资源 + await videoRecorder.release().then(() => { + console.info('release success'); + }, this.failureCallback).catch(this.catchCallback); + + // 相关对象置null + videoRecorder = undefined; + surfaceID = undefined; + } +} +``` + + + +### 音视频录制APP + +音视频录制APP案例包含:创建实例、设置录制参数、获取输入surface、开始录制、暂停录制、恢复录制、停止录制、释放资源等流程。 + +详细代码可参考:[AVRecorderDemo]([multimedia_player_framework: Implementation of media playback and recording | 媒体播放和录制功能实现 - Gitee.com](https://gitee.com/openharmony/multimedia_player_framework/tree/master/test/appdemo/AVRecorderDemo)) \ No newline at end of file diff --git a/zh-cn/application-dev/media/avsession-guidelines.md b/zh-cn/application-dev/media/avsession-guidelines.md index 96e7ce8701a43e4d4b31abbdf63c608d06344b8f..761506bfbfb3bdf3e7fcd892447c99195797e9f4 100644 --- a/zh-cn/application-dev/media/avsession-guidelines.md +++ b/zh-cn/application-dev/media/avsession-guidelines.md @@ -32,7 +32,7 @@ ```js import avSession from '@ohos.multimedia.avsession'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; import featureAbility from '@ohos.ability.featureAbility'; ``` @@ -372,7 +372,7 @@ currentSession.deactivate().then(() => { ```js import avSession from '@ohos.multimedia.avsession'; import {Action, KeyEvent} from '@ohos.multimodalInput.KeyEvent'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; import audio from '@ohos.multimedia.audio'; ``` diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_audio.png b/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_audio.png new file mode 100644 index 0000000000000000000000000000000000000000..23b05d2a51adb734eab3099c36ff438aba895df8 Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_audio.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_state_machine.png b/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_state_machine.png new file mode 100644 index 0000000000000000000000000000000000000000..aa8afdbcbf142fd745cee03fc422caec51cfe41b Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_state_machine.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_video.png b/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_video.png new file mode 100644 index 0000000000000000000000000000000000000000..7a3c6795de742ad057b07223b8051fd2ae576974 Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_avplayer_video.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_avrecorder_module_interaction.png b/zh-cn/application-dev/media/figures/zh-ch_image_avrecorder_module_interaction.png new file mode 100644 index 0000000000000000000000000000000000000000..99f521f7f9b020212db9c19ee64a38649dbe604b Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_avrecorder_module_interaction.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_avrecorder_state_machine.png b/zh-cn/application-dev/media/figures/zh-ch_image_avrecorder_state_machine.png new file mode 100644 index 0000000000000000000000000000000000000000..7ffcb21f09365e9b072bdaf48f8b98d7d45a8aaa Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_avrecorder_state_machine.png differ diff --git a/zh-cn/application-dev/napi/Readme-CN.md b/zh-cn/application-dev/napi/Readme-CN.md index e6626f0373a002a6344fe7b8c934b99d9b7209b6..752a456fca9fed148b05885c3ce41c1ebfc1b456 100644 --- a/zh-cn/application-dev/napi/Readme-CN.md +++ b/zh-cn/application-dev/napi/Readme-CN.md @@ -3,6 +3,6 @@ - [Native API在应用工程中的使用指导](napi-guidelines.md) - [Drawing开发指导](drawing-guidelines.md) - [Rawfile开发指导](rawfile-guidelines.md) -- [Window开发指导](native-window-guidelines.md) +- [NativeWindow开发指导](native-window-guidelines.md) - [使用MindSpore Lite引擎进行模型推理](mindspore-lite-guidelines.md) - [Neural Network Runtime对接AI推理框架开发指导](neural-network-runtime-guidelines.md) \ No newline at end of file diff --git a/zh-cn/application-dev/napi/native-window-guidelines.md b/zh-cn/application-dev/napi/native-window-guidelines.md index f62485e260ed60cd2658245e55a688da973f49e5..0bc953f8d2fb3bdd548feb1d7a5f186afb179e6d 100644 --- a/zh-cn/application-dev/napi/native-window-guidelines.md +++ b/zh-cn/application-dev/napi/native-window-guidelines.md @@ -35,15 +35,68 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生 以下步骤描述了在**OpenHarmony**中如何使用`NativeWindow`提供的`NAPI`接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列。 -1. **获取NativeWindow实例**。例如,使用`Surface`创建`NativeWindow`实例。 - ```c++ - sptr cSurface = Surface::CreateSurfaceAsConsumer(); - sptr listener = new BufferConsumerListenerTest(); - cSurface->RegisterConsumerListener(listener); - sptr producer = cSurface->GetProducer(); - sptr pSurface = Surface::CreateSurfaceAsProducer(producer); - OHNativeWindow* nativeWindow = OH_NativeWindow_CreateNativeWindow(&pSurface); - ``` +1. **获取NativeWindow实例**。可在[`OH_NativeXComponent_Callback`](../reference/native-apis/_o_h___native_x_component___callback.md)提供的接口中获取。 + 1. 在xxx.ets 中定义 XComponent。 + ```ts + XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'nativerender'}) + .onLoad((context) => { + this.context = context; + }) + .onDestroy(() => { + }) + ``` + 2. 在 native c++ 层获取 NativeXComponent。 + ```c++ + napi_value exportInstance = nullptr; + napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); + + OH_NativeXComponent *nativeXComponent = nullptr; + napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); + + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { }; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize); + ``` + 3. 定义 OH_NativeXComponent_Callback。 + ```c++ + // 定义回调函数 + void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) + { + // 可获取 NativeWindow 实例 + OHNativeWindow* nativeWindow = window; + // ... + } + void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window) + { + // 可获取 NativeWindow 实例 + OHNativeWindow* nativeWindow = window; + // ... + } + void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) + { + // 可获取 NativeWindow 实例 + OHNativeWindow* nativeWindow = window; + // ... + } + void DispatchTouchEventCB(OH_NativeXComponent* component, void* window) + { + // 可获取 NativeWindow 实例 + OHNativeWindow* nativeWindow = window; + // ... + } + ``` + ```c++ + // 初始化 OH_NativeXComponent_Callback + OH_NativeXComponent_Callback callback_; + callback_->OnSurfaceCreated = OnSurfaceCreatedCB; + callback_->OnSurfaceChanged = OnSurfaceChangedCB; + callback_->OnSurfaceDestroyed = OnSurfaceDestroyedCB; + callback_->DispatchTouchEvent = DispatchTouchEventCB; + ``` + 4. 将 OH_NativeXComponent_Callback 注册给 NativeXComponent。 + ```c++ + OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback_); + ``` 2. **设置NativeWindowBuffer的属性**。使用`OH_NativeWindow_NativeWindowHandleOpt`设置`NativeWindowBuffer`的属性。 ```c++ @@ -91,7 +144,6 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生 ``` 5. **提交NativeWindowBuffer到图形队列**。 - ```c++ // 设置刷新区域,如果Region中的Rect为nullptr,或者rectNumber为0,则认为NativeWindowBuffer全部有内容更改。 Region region{nullptr, 0}; diff --git a/zh-cn/application-dev/quick-start/app-structure.md b/zh-cn/application-dev/quick-start/app-structure.md index b865b4bb2e485ca84117a61496c44ef49d447d81..3cfc6a9f1560db75f13cb32e847e578669afaafb 100644 --- a/zh-cn/application-dev/quick-start/app-structure.md +++ b/zh-cn/application-dev/quick-start/app-structure.md @@ -3,7 +3,7 @@ app对象包含应用全局配置信息,内部结构如下: -### **表1** **app对象内部结构说明** +**表1** **app对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -14,7 +14,9 @@ app对象包含应用全局配置信息,内部结构如下: | smartWindowSize | 标识应用在模拟器中运行时使用的屏幕尺寸。 | 字符串 | 可缺省,缺省值为空。 | | smartWindowDeviceType | 标识应用在模拟器中运行时可以模拟的设备。 | 字符串数组 | 可缺省,缺省值为空。 | -#### **表2** **version对象内部结构说明** +## version对象内部结构 + +**表2** **version对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -22,7 +24,9 @@ app对象包含应用全局配置信息,内部结构如下: | code | 标识应用的版本号,仅用于OpenHarmony管理该应用,不对应用的终端用户呈现。取值规则如下:API5及更早版本:二进制32位以内的非负整数,需要从version.name的值转换得到。转换规则为:code值=A \* 1,000,000 + B \* 1,000 + C例如,version.name字段取值为2.2.1,则code值为2002001。API6版本起:code的取值不与version.name字段的取值关联,开发者可自定义code取值,取值范围为2^31以内的非负整数,但是每次应用版本的更新,均需要更新code字段的值,新版本code取值必须大于旧版本code的值。 | 数值 | 不可缺省。 | | minCompatibleVersionCode | 标识应用可兼容的最低版本号,用于跨设备场景下,判断其他设备上该应用的版本是否兼容。格式与version.code字段的格式要求相同。 | 数值 | 可缺省,缺省值为code标签值。 | -#### **表3** **apiVersion内部结构** +## apiVersion内部结构 + +**表3** **apiVersion内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -30,7 +34,7 @@ app对象包含应用全局配置信息,内部结构如下: | target | 用于标识应用运行时使用的API版本,取值范围为0~2147483647。 | 数值 | 配置在build.profile中,打包时由IDE填充到config.json中。 | | releaseType | 用于标识应用运行时SDK的状态。
canary:面向特定开发者早期预览版本,不承诺质量,不承诺API稳定。
beta:公开发布的Beta版本,早期Beta版本不承诺API稳定,经历若干次发布后,通过Release Notes对开发者声明该Beta版本为API稳定里程碑,后续版本的API冻结。
release:正式发布版本,承诺质量,API不可变更。当版本处于此状态时版本号中不呈现Stage字段。 | 字符串 | 配置在build.profile中,打包时由IDE填充到config.json中。 | -### app对象示例 +app对象示例 ```json "app": { diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control.md b/zh-cn/application-dev/quick-start/arkts-rendering-control.md index f1f9ca3657e46f9d6400aa414759763d6053a6cd..b9cc90f0b09ef277437451bdcd5a7b87daf54949 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control.md @@ -267,7 +267,7 @@ struct MyComponent { > > - 生成的子组件必须是允许包含在LazyForEach父容器组件中的子组件。 > -> - 允许LazyForEach包含在if/else条件渲染语句中,但不允许LazyForEach中出现if/else条件渲染语句。 +> - 允许LazyForEach包含在if/else条件渲染语句中。 > > - 为了高性能渲染,通过DataChangeListener对象的onDataChange方法来更新UI时,仅当itemGenerator中创建的子组件内使用了状态变量时,才会触发组件刷新。 > diff --git a/zh-cn/application-dev/quick-start/deviceconfig-structure.md b/zh-cn/application-dev/quick-start/deviceconfig-structure.md index f63652f6f5dc8209662faff81ecd2e43ee4d8ae6..b6e981883ba5452c972efbccbd82fe24c5b1b733 100644 --- a/zh-cn/application-dev/quick-start/deviceconfig-structure.md +++ b/zh-cn/application-dev/quick-start/deviceconfig-structure.md @@ -3,7 +3,9 @@ deviceConfig包含设备上的应用配置信息,可以包含default,tv,car,wearable等属性。default标签内的配置适用于所有通用设备,其他设备类型如果有特殊的需求,则需要在该设备类型的标签下进行配置。 -### **表1** **deviceConfig对象内部结构说明** +## deviceConfig对象内部结构 + +**表1** **deviceConfig对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -16,7 +18,9 @@ deviceConfig包含设备上的应用配置信息,可以包含default,tv,ca 上表中各类设备对象的内部结构说明请见表2。 -#### **表2** **deviceConfig设备对象内部结构说明** +## deviceConfig设备对象内部结构 + +**表2** **deviceConfig设备对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -26,27 +30,33 @@ deviceConfig包含设备上的应用配置信息,可以包含default,tv,ca | compressNativeLibs | 标识libs库是否以压缩存储的方式打包到HAP。如果配置为"false",则libs库以不压缩的方式存储,HAP在安装时无需解压libs,运行时会直接从HAP内加载libs库。 | 布尔值 | 可缺省,缺省值为false。 | | network | 标识网络安全性配置。该标签允许应用通过配置文件的安全声明来自定义其网络安全,无需修改应用代码。 | 对象 | 可缺省,缺省值为空。 | -#### **表3** **network对象的内部结构说明** +## network对象的内部结构 + +**表3** **network对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | cleartextTraffic | 标识是否允许应用使用明文网络流量(例如,明文HTTP)。
true:允许应用使用明文流量的请求。false:拒绝应用使用明文流量的请求。 | 布尔值 | 可缺省,缺省值为false。 | | securityConfig | 标识应用的网络安全配置信息。 | 对象 | 可缺省,缺省为空。 | -#### **表4** **securityConfig对象的内部结构说明** +## securityConfig对象的内部结构 + +**表4** **securityConfig对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | domainSettings | 标识自定义的网域范围的安全配置,支持多层嵌套,即一个domainSettings对象中允许嵌套更小网域范围的domainSettings对象。 | 对象类型 | 可缺省,缺省为空。 | -#### **表5** **domainSettings对象内部结构说明** +## domainSettings对象内部结构 + +**表5** **domainSettings对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | cleartextPermitted | 标识自定义的网域范围内是否允许明文流量传输。当cleartextTraffic和security同时存在时,自定义网域是否允许明文流量传输以cleartextPermitted的取值为准。true:允许明文流量传输。false:拒绝明文流量传输。 | 布尔类型 | 可缺省,缺省值为空。 | | domains | 标识域名配置信息,包含两个参数:subdomains和name。subdomains(布尔类型):表示是否包含子域名。如果为"true",此网域规则将与相应网域及所有子网域(包括子网域的子网域)匹配。否则,该规则仅适用于精确匹配项。name(字符串):表示域名名称。 | 对象数组 | 可缺省,缺省值为空。 | -### deviceConfig示例 +deviceConfig示例 ```json "deviceConfig": { diff --git a/zh-cn/application-dev/quick-start/figures/02.png b/zh-cn/application-dev/quick-start/figures/02.png index 19dd76ca232282b19883dde63075c5d155e7db70..eef374a1fd63f2b1e4d72e3323e7f4c23f5705fb 100644 Binary files a/zh-cn/application-dev/quick-start/figures/02.png and b/zh-cn/application-dev/quick-start/figures/02.png differ diff --git a/zh-cn/application-dev/quick-start/figures/04.png b/zh-cn/application-dev/quick-start/figures/04.png index cf23d17c7ee8552e30a5b234c97862b51981dcf8..1190d1e5aa631b12171632d258e4c4fae32e9bba 100644 Binary files a/zh-cn/application-dev/quick-start/figures/04.png and b/zh-cn/application-dev/quick-start/figures/04.png differ diff --git a/zh-cn/application-dev/quick-start/figures/07.png b/zh-cn/application-dev/quick-start/figures/07.png index 0f34d01d824ae1780c73cade9a39fff5f4b9b84e..17f2b060d300667ff250935b6a37485843e854ce 100644 Binary files a/zh-cn/application-dev/quick-start/figures/07.png and b/zh-cn/application-dev/quick-start/figures/07.png differ diff --git a/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md b/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md index 1e9c4022a1d3b23c0fb1c0f93cad77f096e0b83e..73c9190d9fc124b353e6372ee1acc52f5d5781a8 100644 --- a/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md +++ b/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md @@ -4,7 +4,7 @@ **full-SDK**是提供给OEM厂商开发应用的工具包,不能随DevEco Studio下载,包含了系统应用所需要的高权限API -三方开发者通过DevEco Studio自动下载的**API8版本**SDK均为**public版本**。public-SDK**不支持**开发者使用**所有的系统API**,包括animator组件、xcomponent组件、@ohos.application.abilityManager.d.ts、@ohos.application.formInfo.d.ts、@ohos.bluetooth.d.ts等,如工程必须依赖于系统API,请按照以下步骤替换**full-SDK**。 +三方开发者通过DevEco Studio自动下载的**API8版本**SDK均为**public版本**。public-SDK**不支持**开发者使用**所有的系统API**,包括animator组件、xcomponent组件、@ohos.app.ability.abilityManager.d.ts、@ohos.app.form.formInfo.d.ts、@ohos.bluetooth.d.ts等,如工程必须依赖于系统API,请按照以下步骤替换**full-SDK**。 > **说明**:本文中的截图仅为参考,具体的显示界面请以实际使用的DevEco Studio和SDK的版本为准。 @@ -32,7 +32,7 @@ full-SDK需要手动下载。请参考[版本说明书](../../release-notes/Open ![image-20220613220702504](figures/zh-cn_image_0000001655129232.png) - b.检查api中是否包含系统API(@ohos.application.abilityManager.d.ts、@ohos.application.formInfo.d.ts、@ohos.bluetooth.d.ts等) + b.检查api中是否包含系统API(@ohos.app.ability.abilityManager.d.ts、@ohos.app.form.formInfo.d.ts、@ohos.bluetooth.d.ts等) 注:系统api判定标准以发布api指导文档为主。 diff --git a/zh-cn/application-dev/quick-start/har-structure.md b/zh-cn/application-dev/quick-start/har-structure.md index 34a14a5b5ac987e2c19228ad537c44ef2a26a8f3..6bd6ad0d4ff3c2c0e9efa60955d19d36d3dd8c2f 100644 --- a/zh-cn/application-dev/quick-start/har-structure.md +++ b/zh-cn/application-dev/quick-start/har-structure.md @@ -1,10 +1,10 @@ # HAR包结构 -HAR(Harmony Ability Resources)包用于实现多个模块或多个工程间的代码共享。HAR包不同于HAP,不能独立安装运行在设备上,只能作为应用模块的依赖项被引用。 +HAR(OpenHarmony Archive)包用于实现多个模块或多个工程间的代码共享。HAR包不同于HAP,不能独立安装运行在设备上,只能作为应用模块的依赖项被引用。 HAR包对应DevEco Studio工程中的“Library”类型的[Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3)。 -OpenHarmony的HAR包复用标准的[npm包](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434)发布方式,会打包成tar包(后缀为.tgz)。打包后的HAR包中包含源代码、资源文件、module.json文件(Stage模型)或config.json文件(FA模型)等。 +OpenHarmony的[HAR包](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434),是OpenHarmony静态共享包,可以包含代码、C++库、资源和module.json文件(Stage模型)或config.json文件(FA模型)等。 diff --git a/zh-cn/application-dev/quick-start/module-structure.md b/zh-cn/application-dev/quick-start/module-structure.md index a47a7d713b20b99d305987c3a40edf169d053337..a1c8867f3d3577f3cefc2efdd143885430565b86 100644 --- a/zh-cn/application-dev/quick-start/module-structure.md +++ b/zh-cn/application-dev/quick-start/module-structure.md @@ -3,7 +3,7 @@ module对象包含HAP的配置信息。 -### **表1** **module对象内部结构说明** + **表1** **module对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -89,7 +89,9 @@ module示例: } ``` -#### **表2** **distro对象内部结构说明** +## distro对象内部结构 + +**表2** **distro对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -110,7 +112,9 @@ distro示例: } ``` -#### **表3** **metadata对象内部结构说明** +## metadata对象内部结构 + +**表3** **metadata对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -118,7 +122,9 @@ distro示例: | results | 标识Ability返回值的元信息。每个返回值的元信息由以下三个标签组成:description、name、type。 | 对象数组 | 可缺省,缺省值为空。 | | customizeData | 该标签标识父级组件的自定义元信息,Parameters和results在application不可配。 | 对象数组 | 可缺省,缺省值为空。 | -#### **表4** **parameters对象内部结构说明** +## parameters对象内部结构 + +**表4** **parameters对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -126,7 +132,9 @@ distro示例: | name | 标识调用参数的名称。该标签最大长度为255个字节。 | 字符串 | 不可缺省。 | | type | 标识调用参数的类型,如Integer。 | 字符串 | 不可缺省。 | -#### **表5** **results对象内部结构说明** +## results对象内部结构 + +**表5** **results对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -134,7 +142,9 @@ distro示例: | name | 标识返回值的名字。该标签最大长度为255个字节。 | 字符串 | 可缺省,缺省值为空。 | | type | 标识返回值的类型,如Integer。 | 字符串 | 不可缺省 | -#### **表6** **customizeData对象的内部结构说明** +## customizeData对象的内部结构 + +**表6** **customizeData对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -166,7 +176,9 @@ metadata对象示例: } ``` -#### **表7** **deviceType标签配置说明** +## deviceType标签 + +**表7** **deviceType标签配置说明** | 设备类型 | 枚举值 | 说明 | | -------- | -------- | -------- | @@ -176,7 +188,9 @@ metadata对象示例: | 车机 | car | - | | 默认设备 | default | 能够使用全部系统能力的OpenHarmony设备。 | -#### **表8** **abilities对象的内部结构说明** +## abilities对象的内部结构 + +**表8** **abilities对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -210,7 +224,9 @@ metadata对象示例: | startWindowBackground | 标识该Ability启动页面背景颜色资源文件的索引。该标签仅适用于page类型的Ability。取值示例:$color:red。 | 字符串 | 可缺省,缺省值为空。 | | removeMissionAfterTerminate | 该标签标识Ability销毁后是否从任务列表中移除任务。该标签仅适用于page类型的Ability。true表示销毁后移除任务, false表示销毁后不移除任务。 | 布尔值 | 可缺省,缺省值为false。 | -#### **表9** **uriPermission对象的内部结构说明** +## uriPermission对象的内部结构 + +**表9** **uriPermission对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -286,8 +302,9 @@ abilities示例: } ] ``` +## skills对象的内部结构 -#### **表10** **skills对象的内部结构说明** +**表10** **skills对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -295,7 +312,9 @@ abilities示例: | entities | 标识能够接收的want的Ability的类别(如视频、桌面应用等),可以包含一个或多个entity。 | 字符串数组 | 可缺省,缺省值为空。 | | uris | 该标签标识向want过滤器添加数据规范集合。该规范可以是只有数据类型(mimeType属性),可以是只有URI,也可以是既有数据类型又有URI。
URI由其各个部分的单独属性指定:<scheme>://<host>:<port>[<path>\|<pathStartWith>\|<pathRegex>]。该标签可缺省,缺省值为空。
其中,scheme字段配置为uri时必配;当只设置数据类型(mimeType)时,则scheme字段为非必配项。 | 对象数组 | 可缺省,缺省值为空。 | -#### **表11** **uris对象的内部结构说明** +## uris对象的内部结构 + +**表11** **uris对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -332,7 +351,9 @@ skills示例: ] ``` -#### **表12** **reqPermissions权限申请字段说明** +## reqPermissions权限申请 + +**表12** **reqPermissions权限申请字段说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -340,14 +361,18 @@ skills示例: | reason | 描述申请权限的原因。需要做多语种适配。 | 字符串 | 分情况:当申请的权限为user_grant时,必须填写此字段,否则不允许在应用市场上架;其他权限可缺省,缺省为空 | | usedScene | 描述权限使用的场景和时机。场景类型如下两种:
- ability:ability的名称,可配置多个。
- when:调用时机,可填的值有inuse(使用时)、always(始终)。 | 对象 | 可缺省,缺省值为空。
when可缺省,缺省值为"inuse" | -#### **表13** **usedScene对象内部结构说明** +## usedScene对象内部结构 + +**表13** **usedScene对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | ability | 标识哪些Ability需要此权限,里面配置Ability的名称。 | 字符串数组 | 可以缺省,缺省表示所有Ability都需要此权限。 | | when | 标识此权限的使用时间:
inuse: 使用时需要此权限。
always: 所有时间都需要此权限。 | 枚举值 | 可缺省,缺省值为空。 | -#### **表14** **js对象的内部结构说明** +## js对象的内部结构 + +**表14** **js对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -357,14 +382,18 @@ skills示例: | type | 标识JS应用的类型。取值范围如下:
normal:标识该JS Component为应用实例。
form:标识该JS Component为卡片实例。 | 字符串 | 可缺省,缺省值为"normal"。 | |mode | 定义JS组件的开发模式。 | 对象 | 可缺省,缺省值为空。 | -#### **表15** **window对象的内部结构说明** +## window对象的内部结构 + +**表15** **window对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | designWidth | 标识页面设计基准宽度。以此为基准,根据实际设备宽度来缩放元素大小。 | 数值 | 可缺省,缺省值为720px。 | | autoDesignWidth | 标识页面设计基准宽度是否自动计算。当配置为true时,designWidth将会被忽略,设计基准宽度由设备宽度与屏幕密度计算得出。 | 布尔值 | 可缺省,缺省值为false。 | -#### **表16** **mode对象的内部结构说明** +## mode对象的内部结构 + +**表16** **mode对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -391,7 +420,9 @@ js示例: ] ``` -#### **表17** **shortcuts对象的内部结构说明** +## shortcuts对象的内部结构 + +**表17** **shortcuts对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -400,7 +431,9 @@ js示例: | icon | 标识快捷方式的图标信息。取值为表示icon的资源索引。 | 字符串 | 可缺省,缺省为空。 | | intents | 标识快捷方式内定义的目标intent信息集合,每个intent可配置两个子标签,targetClass, targetBundle。 | 对象数组 | 可缺省,缺省为空。 | -#### **表18** **intents对象的内部结构说明** +## intents对象的内部结构 + +**表18** **intents对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -426,7 +459,9 @@ shortcuts示例: ] ``` -#### **表19** **forms对象的内部结构说明** +## forms对象的内部结构 + +**表19** **forms对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -445,7 +480,9 @@ shortcuts示例: | metaData | 标识卡片的自定义信息,包含customizeData数组标签。 | 对象 | 可缺省,缺省值为空。 | | customizeData | 标识自定义的卡片信息。 | 对象数组 | 可缺省,缺省值为空。 | -#### **表20** **customizeData对象内部结构说明** +## customizeData对象内部结构 + +**表20** **customizeData对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -507,7 +544,9 @@ forms示例: ] ``` -#### **表21** **distroFilter对象的内部结构说明** +## distroFilter对象的内部结构 + +**表21** **distroFilter对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -517,35 +556,45 @@ forms示例: |screenDensity | 标识屏幕的像素密度(dpi:Dots Per Inch)。 | 对象数组 | 可缺省,缺省值为空。 | | countryCode | 标识分发应用时的国家码。具体值参考ISO-3166-1的标准,支持多个国家和地区的枚举定义。 | 对象数组 | 可缺省,缺省值为空。 | -#### **表22** **apiVersion对象的内部结构说明** +## apiVersion对象的内部结构 + +**表22** **apiVersion对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | policy | 标识该子属性取值规则。配置为“exclude”或“include”。
- exclude:表示需要排除的value属性。
- include:表示需要包含的value属性。 | 字符串 | 不可缺省。 | | value | 支持的取值为API Version存在的整数值,例如4、5、6。场景示例:某应用,针对相同设备型号,同时在网的为使用API 5和API 6开发的两个软件版本,则允许上架2个entry类型的安装包,分别支持到对应设备侧软件版本的分发。 | 数组 | 不可缺省。 | -#### **表23** **screenShape对象的内部结构说明** +## screenShape对象的内部结构 + +**表23** **screenShape对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | policy | 标识该子属性取值规则。配置为“exclude”或“include”。
- exclude:表示需要排除的value属性。
- include:表示需要包含的value属性。 | 字符串 | 不可缺省。 | | value | 支持的取值为API Version存在的整数值,例如4、5、6。场景示例:某应用,针对相同设备型号,同时在网的为使用API 5和API 6开发的两个软件版本,则允许上架2个entry类型的安装包,分别支持到对应设备侧软件版本的分发。 | 数组 | 不可缺省。 | -#### **表24** **screenWindow对象的内部结构说明** +## screenWindow对象的内部结构 + +**表24** **screenWindow对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | policy | 标识该子属性取值规则。配置为“exclude”或“include”。
- exclude:表示需要排除的value属性。
- include:表示需要包含的value属性。 | 字符串 | 不可缺省。 | | value | 支持的取值为API Version存在的整数值,例如4、5、6。场景示例:某应用,针对相同设备型号,同时在网的为使用API 5和API 6开发的两个软件版本,则允许上架2个entry类型的安装包,分别支持到对应设备侧软件版本的分发。 | 数组 | 不可缺省。 | -#### **表25** **screenDensity对象的内部结构说明** +## screenDensity对象的内部结构 + +**表25** **screenDensity对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | | policy | 标识该子属性取值规则。配置为“exclude”或“include”。
- exclude:表示需要排除的value属性。
- include:表示需要包含的value属性。 | 字符串 | 不可缺省。 | | value | 取值范围如下:
sdpi:表示小规模的屏幕密度(Small-scale Dots Per Inch),适用于dpi取值为(0,120]的设备。
mdpi:表示中规模的屏幕密度(Medium-scale Dots Per Inch),适用于dpi取值为(120,160]的设备。
ldpi:表示大规模的屏幕密度(Large-scale Dots Per Inch),适用于dpi取值为(160,240]的设备。
xldpi:表示特大规模的屏幕密度(Extra Large-scale Dots Per Inch),适用于dpi取值为(240,320]的设备。
xxldpi:表示超大规模的屏幕密度(Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(320,480]的设备。
xxxldpi:表示超特大规模的屏幕密度(Extra Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(480,640]的设备。 | 数组 | 不可缺省。 | -#### **表26** **countryCode对象的内部结构说明** +## countryCode对象的内部结构 + +**表26** **countryCode对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -580,7 +629,9 @@ distroFilter示例: } ``` -#### **表27** **commonEvents对象的内部结构说明** +## commonEvents对象的内部结构 + +**表27** **commonEvents对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -610,7 +661,9 @@ commonEvents示例: ] ``` -#### **表28** **testRunner对象的内部结构说明** +## testRunner对象的内部结构 + +**表28** **testRunner对象的内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | @@ -627,7 +680,8 @@ commonEvents示例: definePermission仅支持系统应用配置,三方应用配置不生效。 -#### **表29** **definePermissions对象内部结构说明** +## definePermissions对象内部结构 +**表29** **definePermissions对象内部结构说明** | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md b/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md index c78473d692056a2925c7f9221ba313e29c25cd5b..f85e7013ce3fc0840dcbb23c5e176495b5d91ed4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -224,7 +224,7 @@ startBackgroundRunning(id: number, request: NotificationRequest, callback: Async ```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; function callback(err, data) { if (err) { @@ -293,7 +293,7 @@ startBackgroundRunning(id: number, request: NotificationRequest): Promise<voi ```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md index 6b644c9a217ef1bc71edde2bb7a73ecee1bef0c3..0a958c87ae5f3de3874043ec71a0b488cf9fdebc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -9,7 +9,7 @@ ## 导入模块 ```ts -import Configuration from '@ohos.app.ability.Configuration' +import Configuration from '@ohos.app.ability.Configuration'; ``` **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase @@ -26,31 +26,31 @@ import Configuration from '@ohos.app.ability.Configuration' 具体字段描述参考ohos.app.ability.Configuration.d.ts文件 **示例:** - + ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; - export default class EntryAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - let envCallback = { - onConfigurationUpdated(config) { - console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) - let language = config.language; - let colorMode = config.colorMode; - let direction = config.direction; - let screenDensity = config.screenDensity; - let displayId = config.displayId; - let hasPointerDevice = config.hasPointerDevice; + let envCallback = { + onConfigurationUpdated(config) { + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + let language = config.language; + let colorMode = config.colorMode; + let direction = config.direction; + let screenDensity = config.screenDensity; + let displayId = config.displayId; + let hasPointerDevice = config.hasPointerDevice; + } + }; + try { + let applicationContext = this.context.getApplicationContext(); + let callbackId = applicationContext.on("environment", envCallback); + console.log("callbackId: " + callbackId); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); } - }; - try { - let applicationContext = this.context.getApplicationContext(); - let callbackId = applicationContext.on("environment", envCallback); - console.log("callbackId: " + callbackId); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } } - } +} ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md index 5d227bbcaa4439be09bf9895c330f0cd5975d4ca..9573cf44549f443ca03114be99c12dec3f74122a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -124,7 +124,7 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call **示例:** ```ts -import formBindingData from '@ohos.application.formBindingData'; +import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let formId = "12400633174999288"; @@ -173,7 +173,7 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr **示例:** ```ts -import formBindingData from '@ohos.application.formBindingData'; +import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let formId = "12400633174999288"; @@ -349,7 +349,7 @@ requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, **示例:** ```ts -import formBindingData from '@ohos.application.formBindingData'; +import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let want = { diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md index 7da6408723c082cb55b1ac93762a3b548df0e311..0f422ebb87ae2ff1710133ece24c273741bc3d8c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md @@ -8,14 +8,17 @@ Ability模块提供对Ability生命周期、上下文环境等调用管理的能 - [Callee](#callee):通用组件服务端注册和解除客户端caller通知送信的callback接口。 > **说明:** -> -> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 从API Version 9开始,该接口不再维护,推荐使用新接口[`@ohos.app.ability.UIAbility (UIAbility)`](js-apis-app-ability-uiAbility.md)。 +> +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> > 本模块接口仅可在Stage模型下使用。 ## 导入模块 ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.application.Ability'; ``` ## 属性 @@ -72,7 +75,7 @@ onWindowStageCreate(windowStage: window.WindowStage): void **示例:** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); } @@ -91,7 +94,7 @@ onWindowStageDestroy(): void **示例:** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageDestroy() { console.log('onWindowStageDestroy'); } @@ -116,7 +119,7 @@ onWindowStageRestore(windowStage: window.WindowStage): void **示例:** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageRestore(windowStage) { console.log('onWindowStageRestore'); } @@ -133,9 +136,9 @@ Ability生命周期回调,在销毁时回调,执行资源清理等操作。 **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore **示例:** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onDestroy() { console.log('onDestroy'); } @@ -152,9 +155,9 @@ Ability生命周期回调,当应用从后台转到前台时触发。 **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore **示例:** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onForeground() { console.log('onForeground'); } @@ -171,9 +174,9 @@ Ability生命周期回调,当应用从前台转到后台时触发。 **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore **示例:** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onBackground() { console.log('onBackground'); } @@ -202,10 +205,11 @@ onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; | AbilityConstant.OnContinueResult | 继续的结果。 | **示例:** - + ```ts - import AbilityConstant from "@ohos.application.AbilityConstant" - class myAbility extends Ability { + import AbilityConstant from "@ohos.app.ability.AbilityConstant"; + + export default class EntryAbility extends UIAbility { onContinue(wantParams) { console.log('onContinue'); wantParams["myData"] = "my1234567"; @@ -231,9 +235,9 @@ onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | launchParams | AbilityConstant.LaunchParam | 是 | Ability启动的原因、上次异常退出的原因信息。 | **示例:** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); @@ -256,9 +260,9 @@ onConfigurationUpdated(config: Configuration): void; | config | [Configuration](js-apis-application-configuration.md) | 是 | 发生全局配置变更时触发回调,当前全局配置包括系统语言、深浅色模式。 | **示例:** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, language:' + config.language); } @@ -280,9 +284,9 @@ dump(params: Array\): Array\; | params | Array\ | 是 | 表示命令形式的参数。| **示例:** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { dump(params) { console.log('dump, params:' + JSON.stringify(params)); return ["params"] @@ -305,9 +309,9 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | 是 | 回调返回内存微调级别,显示当前内存使用状态。| **示例:** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); } @@ -338,9 +342,9 @@ onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}) **示例:** ```ts -import AbilityConstant from '@ohos.application.AbilityConstant' +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; -class myAbility extends Ability { +export default class EntryAbility extends UIAbility { onSaveState(reason, wantParam) { console.log('onSaveState'); wantParam["myData"] = "my1234567"; @@ -349,8 +353,6 @@ class myAbility extends Ability { } ``` - - ## Caller 通用组件Caller通信客户端调用接口, 用来向通用组件服务端发送约定数据。 @@ -387,7 +389,7 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; | 16000050 | Internal Error. | **示例:** - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -545,7 +547,6 @@ release(): void; | 16000050 | Internal Error. | **示例:** - ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -589,7 +590,7 @@ release(): void; | callback | OnReleaseCallBack | 是 | 返回onRelease回调结果。 | **示例:** - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -716,7 +717,6 @@ off(method: string): void; **示例:** - ```ts import UIAbility from '@ohos.app.ability.UIAbility'; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index 6850a49cce385c59b1b1c925715dac4a777f8a8c..4d5b2ba0d9be7c4f01f700de31c1895fc9b5f70b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -9,7 +9,7 @@ AbilityDelegatorRegistry模块提供用于存储已注册的AbilityDelegator和A ## 导入模块 ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; ``` ## AbilityLifecycleState diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index bc65594148e918b9719d49ebb8cca0736b3212af..cd2faf8c5843b1eea4af6bf3129b9cbd974f38a9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -156,7 +156,7 @@ onAbilityContinue(ability: Ability): void; **示例:** ```ts -import AbilityStage from "@ohos.application.AbilityStage"; +import AbilityStage from "@ohos.app.ability.AbilityStage"; var lifecycleId; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md index 47cd2130163689e591cda66214ba35aedd13add6..f10bf6565e5fded4a7f9a447c23de17bf7d7cec4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -10,7 +10,7 @@ AbilityManager模块提供对Ability相关信息和状态信息进行获取、 ## 导入模块 ```ts -import abilityManager from '@ohos.application.abilityManager' +import abilityManager from '@ohos.application.abilityManager'; ``` ## AbilityState @@ -38,7 +38,7 @@ updateConfiguration(config: Configuration, callback: AsyncCallback\): void **需要权限**: ohos.permission.UPDATE_CONFIGURATION **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -176,7 +176,7 @@ abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { getExtensionRunningInfos(upperLimit: number): Promise\> 获取关于运行扩展能力的信息(Promise形式)。 - + **需要权限**: ohos.permission.GET_RUNNING_INFO **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core @@ -232,7 +232,7 @@ abilityManager.getTopAbility((err,data) => { getTopAbility(): Promise\; 获取窗口焦点的ability接口(Promise形式)。 - + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md index ce602be043df8fe4b32c74297d2e3cf5bbe17e80..a39b42400e04f0db7f070bcdc9a5208ef4701211 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md @@ -420,7 +420,7 @@ unregisterApplicationStateObserver(observerId: number): Promise\; getForegroundApplications(callback: AsyncCallback\>): void; 获取所有当前处于前台的应用信息。该应用信息由[AppStateData](js-apis-inner-application-appStateData.md)定义。 - + **需要权限**:ohos.permission.GET_RUNNING_INFO **系统能力**:SystemCapability.Ability.AbilityRuntime.Core diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md index 0af24476df9124f9eb096738e48ef51172eb8af5..3c845b46dec3e12eff340ca44185e2faf116bb58 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @@ -26,7 +26,6 @@ import Configuration from '@ohos.application.Configuration' 具体字段描述参考ohos.application.Configuration.d.ts文件 **示例:** - ```ts import hilog from '@ohos.hilog'; import UIAbility from '@ohos.app.ability.UIAbility'; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index 1c07c97d90aa08b99151299360c95ab64e624669..c3844b5182cca13b14e048ceb8144a3fdebb69a9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -75,7 +75,8 @@ let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { onCreate(want, callback) { rdb.getRdbStore(this.context, { - name: DB_NAME + name: DB_NAME, + securityLevel: rdb.SecurityLevel.S1 }, function (err, data) { console.log('getRdbStore done, data : ' + data); rdbStore = data; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md index 186be6c6dbc65dfad52d64fb2e0cb0967e412116..b3f85620f65ef55dc1da14fe22c6042239ef1566 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md @@ -8,7 +8,7 @@ ErrorManager模块提供对错误观察器的注册和注销的能力。 ## 导入模块 ```ts -import errorManager from '@ohos.application.errorManager' +import errorManager from '@ohos.application.errorManager'; ``` ## ErrorManager.registerErrorObserver @@ -20,7 +20,7 @@ registerErrorObserver(observer: ErrorObserver): number; **系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** - + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | 是 | 返回观察者的数字代码。 | @@ -45,7 +45,7 @@ unregisterErrorObserver(observerId: number, callback: AsyncCallback\): vo **系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** - + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | observerId | number | 是 | 返回观察者的数字代码。 | @@ -74,7 +74,7 @@ unregisterErrorObserver(observerId: number): Promise\; **系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** - + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | observerId | number | 是 | 返回观察者的数字代码。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md b/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md index b2b44ab897eebc9df87860180985ae99dd40e502..78f507d1bc172f864f28c6ea597d3e99ca6939f8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -48,7 +48,7 @@ createFormBindingData(obj?: Object | string): FormBindingData **示例:** ```ts -import formBindingData from @ohos.application.formBindingData; +import formBindingData from '@ohos.application.formBindingData'; import fs from '@ohos.file.fs'; try { diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md b/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md index 66db8400ea57b6343fbf2b7cf217eaa0981162c8..6f78d8cb6fb2b2c16f62c648e1dc5533ae77c2c3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md @@ -94,7 +94,7 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call **示例:** ```ts - import formBindingData from '@ohos.application.formBindingData'; + import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let formId = "12400633174999288"; diff --git a/zh-cn/application-dev/reference/apis/js-apis-avsession.md b/zh-cn/application-dev/reference/apis/js-apis-avsession.md index 3e9151bbabc6961cfd85f93a4605ec6cfa7a544d..6937049624fafdd34768ff75e9866e53e0fc5c28 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-avsession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-avsession.md @@ -1001,7 +1001,7 @@ setLaunchAbility(ability: WantAgent): Promise\ **示例:** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; //WantAgentInfo对象 let wantAgentInfo = { @@ -1066,7 +1066,7 @@ setLaunchAbility(ability: WantAgent, callback: AsyncCallback\): void **示例:** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; //WantAgentInfo对象 let wantAgentInfo = { @@ -2222,7 +2222,7 @@ getLaunchAbility(): Promise\ **示例:** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; controller.getLaunchAbility().then((agent) => { console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`); @@ -2257,7 +2257,7 @@ getLaunchAbility(callback: AsyncCallback\): void **示例:** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; controller.getLaunchAbility(function (err, agent) { if (err) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 19b83a579091657f576b373ee1ecc3d75dccea02..605da9955596508dd7fa5bf8417aa8e3b2d05486 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -173,7 +173,7 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; function callback(err, data) { if (err) { @@ -207,7 +207,7 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; function callback(err, data) { if (err) { @@ -270,7 +270,7 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ @@ -299,7 +299,7 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md index f5bf333d21d98990ea3ac0a3bc99e5dea16bc189..95c477c34d8fecf0b0c1a51e2bb36490c4c677a6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -46,7 +46,7 @@ batteryStats.getBatteryStats() console.info('battery statistics info: ' + data); }) .catch(err => { - console.error('get battery statisitics failed, err: ' + err); + console.error('get battery statistics failed, err: ' + err); }); ``` @@ -81,7 +81,7 @@ batteryStats.getBatteryStats((err, data) => { if (typeof err === 'undefined') { console.info('battery statistics info: ' + data); } else { - console.error('get battery statisitics failed, err: ' + err); + console.error('get battery statistics failed, err: ' + err); } }); ``` @@ -123,7 +123,7 @@ try { var value = batteryStats.getAppPowerValue(10021); console.info('battery statistics value of app is: ' + value); } catch(err) { - console.error('get battery statisitics value of app failed, err: ' + err); + console.error('get battery statistics value of app failed, err: ' + err); } ``` @@ -164,7 +164,7 @@ try { var percent = batteryStats.getAppPowerPercent(10021); console.info('battery statistics percent of app is: ' + percent); } catch(err) { - console.error('get battery statisitics percent of app failed, err: ' + err); + console.error('get battery statistics percent of app failed, err: ' + err); } ``` @@ -205,7 +205,7 @@ try { var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); console.info('battery statistics percent of hardware is: ' + percent); } catch(err) { - console.error('get battery statisitics percent of hardware failed, err: ' + err); + console.error('get battery statistics percent of hardware failed, err: ' + err); } ``` @@ -246,7 +246,7 @@ try { var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); console.info('battery statistics percent of hardware is: ' + percent); } catch(err) { - console.error('get battery statisitics percent of hardware failed, err: ' + err); + console.error('get battery statistics percent of hardware failed, err: ' + err); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-cert.md b/zh-cn/application-dev/reference/apis/js-apis-cert.md index 946f6009db7a7efdcbd789d5343a219a795a0d17..c629d49bab2e59319c06abec8557a7dc5791904d 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-cert.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cert.md @@ -203,7 +203,7 @@ cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); } else { console.log("createX509Cert success"); - // 业务需通过AsyKeyGenerator生成PubKey或通过上级X509Cert证书对象的getPublicKey获取PubKey + // 业务需通过上级X509Cert证书对象的getPublicKey获取PubKey let pubKey = null; x509Cert.verify(pubKey, function (error, data) { if (error != null) { @@ -355,8 +355,7 @@ getPublicKey() : cryptoFramework.PubKey | 类型 | 说明 | | ------ | ---------------- | -| cryptoFramework.PubKey | X509证书公钥对象 | - +| cryptoFramework.PubKey | X509证书公钥对象:仅用于X509Cert的verify接口 | **示例:** @@ -398,8 +397,7 @@ checkValidityWithDate(date: string) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------- | -| date | string | 是 | 日期 | - +| date | string | 是 | 日期(格式:YYMMDDHHMMSSZ 或 YYYYMMDDHHMMSSZ,时间必须以Z结尾:表示标准时间) | **示例:** @@ -584,9 +582,9 @@ getNotBeforeTime() : string **返回值**: -| 类型 | 说明 | -| ------ | -------------------------- | -| string | 表示X509证书有效期起始时间 | +| 类型 | 说明 | +| ------ | ------------------------------------------------------------ | +| string | 表示X509证书有效期起始时间(格式:YYMMDDHHMMSSZ 或 YYYYMMDDHHMMSSZ,时间以Z结尾:表示标准时间) | **示例:** @@ -620,9 +618,9 @@ getNotAfterTime() : string **返回值**: -| 类型 | 说明 | -| ------ | -------------------------- | -| string | 表示X509证书有效期截止时间 | +| 类型 | 说明 | +| ------ | ------------------------------------------------------------ | +| string | 表示X509证书有效期截止时间(格式:YYMMDDHHMMSSZ 或 YYYYMMDDHHMMSSZ,时间以Z结尾:表示标准时间) | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-curve.md b/zh-cn/application-dev/reference/apis/js-apis-curve.md index df2ac9f009210152b40baa1715b1593d7210fcf6..51af65f7cc9437fb90a1156ce33f1492008788a9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-curve.md +++ b/zh-cn/application-dev/reference/apis/js-apis-curve.md @@ -58,7 +58,7 @@ stepsCurve(count: number, end: boolean):ICurve | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ----| ------------------------------------------------------------ | | count | number | 是 | 阶梯的数量,需要为正整数。 | -| end | boolean | 是 | 在每个间隔的起点或是终点发生阶跃变化。
-true:在终点发生阶跃变化。
-false:在起点发生阶跃变化。 | +| end | boolean | 是 | 在每个间隔的起点或是终点发生阶跃变化。
-true:在终点发生阶跃变化。
-false:在起点发生阶跃变化。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md index 1c74807e53310bc5529cef01f2cc5c9fcd10e9a4..9290088c53a09d04c8056fdb817d6ec80a373c99 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -271,9 +271,10 @@ createKVManager(config: KVManagerConfig): KVManager Stage模型下的示例: ```js -import AbilityStage from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let kvManager; -export default class MyAbilityStage extends AbilityStage { +export default class EntryAbility extends UIAbility { onCreate() { console.log("MyAbilityStage onCreate") let context = this.context @@ -294,7 +295,7 @@ export default class MyAbilityStage extends AbilityStage { FA模型下的示例: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; let kvManager; let context = featureAbility.getContext() const kvManagerConfig = { diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md index a7dbee35c1df0f916f0d707a4a08e34b215e71a7..96fdfe4a492282df8b7768476592e8320cd0286b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @@ -1,4 +1,4 @@ -# @ohos.data.fileAccess (公共文件访问与管理) +# @ohos.file.fileAccess (公共文件访问与管理) fileAccess模块是基于extension机制实现的一个对公共文件访问和操作的框架。该模块一方面对接各类文件管理服务,如媒体库、外置存储管理服务等,另一方面为系统应用提供一套统一的文件访问管理接口。其中,媒体库服务提供本地设备、分布式设备等公共文件访问服务;外置存储管理服务可以提供共享盘、U盘、SD卡等设备的公共文件访问服务。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md b/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md index bc1e98d8d6de99e35e656c77627e9cdf8e0eaab5..b55f8ba04d0c4664cf153ea178b08cc1ac5d5460 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @@ -1,4 +1,4 @@ -# @ohos.fileExtensionInfo (公共文件访问与管理属性信息) +# @ohos.file.fileExtensionInfo (公共文件访问与管理属性信息) 该模块提供公共文件访问和管理模块中RootInfo与FileInfo中部分属性值的定义。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md index f067a976424b9f35415c3aea5f91727b7722dff5..1887a656860e3358afa2b986d8b4757eff74e151 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -775,7 +775,7 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo ```ts import geoLocationManager from '@ohos.geoLocationManager'; - import wantAgent from '@ohos.wantAgent'; + import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ @@ -833,7 +833,7 @@ off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): v ```ts import geoLocationManager from '@ohos.geoLocationManager'; - import wantAgent from '@ohos.wantAgent'; + import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ diff --git a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md index 16a018d2ce0dfd446255a4eeb6df6a104a02b3c1..ebe0fa3d296fa83bb971fb90d34a13f576e53a80 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md @@ -404,7 +404,7 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; ```ts import geolocation from '@ohos.geolocation'; - import wantAgent from '@ohos.wantAgent'; + import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ @@ -452,7 +452,7 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; ```ts import geolocation from '@ohos.geolocation'; - import wantAgent from '@ohos.wantAgent'; + import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index fe66bf067e46dbd9dc5e7e720517f4686999c5ac..e032f3805e99473879f246614f2a2f86ddc7240f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -10,7 +10,7 @@ AbilityDelegator提供添加用于监视指定ability的生命周期状态更改 通过AbilityDelegatorRegistry中[getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator)方法获取。 ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` @@ -35,13 +35,13 @@ addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void **示例:** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -75,13 +75,13 @@ addAbilityMonitor(monitor: AbilityMonitor): Promise\; **示例:** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -92,8 +92,6 @@ abilityDelegator.addAbilityMonitor(monitor).then(() => { }); ``` - - ### removeAbilityMonitor9+ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; @@ -112,13 +110,13 @@ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): v **示例:** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -129,8 +127,6 @@ abilityDelegator.removeAbilityMonitor(monitor, (err : any) => { }); ``` - - ### removeAbilityMonitor9+ removeAbilityMonitor(monitor: AbilityMonitor): Promise\; @@ -154,13 +150,13 @@ removeAbilityMonitor(monitor: AbilityMonitor): Promise\; - 示例 ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -171,8 +167,6 @@ abilityDelegator.removeAbilityMonitor(monitor).then(() => { }); ``` - - ### waitAbilityMonitor9+ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; @@ -191,13 +185,13 @@ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\) **示例:** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -227,14 +221,14 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCall **示例:** ```ts -var abilityDelegator; -var timeout = 100; +let abilityDelegator; +let timeout = 100; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -271,13 +265,13 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\ { }); ``` - - ### getAppContext9+ getAppContext(): Context; @@ -307,14 +299,12 @@ getAppContext(): Context; **示例:** ```ts -var abilityDelegator; +let abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -var context = abilityDelegator.getAppContext(); +let context = abilityDelegator.getAppContext(); ``` - - ### getAbilityState9+ getAbilityState(ability: UIAbility): number; @@ -338,20 +328,18 @@ getAbilityState(ability: UIAbility): number; **示例:** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info("getCurrentTopAbility callback"); ability = data; - var state = abilityDelegator.getAbilityState(ability); + let state = abilityDelegator.getAbilityState(ability); console.info("getAbilityState" + state); }); ``` - - ### getCurrentTopAbility9+ getCurrentTopAbility(callback: AsyncCallback\): void; @@ -369,8 +357,8 @@ getCurrentTopAbility(callback: AsyncCallback\): void; **示例:** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -379,8 +367,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### getCurrentTopAbility9+ getCurrentTopAbility(): Promise\; @@ -398,8 +384,8 @@ getCurrentTopAbility(): Promise\; **示例:** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility().then((data : any) => { @@ -408,8 +394,6 @@ abilityDelegator.getCurrentTopAbility().then((data : any) => { }); ``` - - ### startAbility9+ startAbility(want: Want, callback: AsyncCallback\): void; @@ -428,8 +412,8 @@ startAbility(want: Want, callback: AsyncCallback\): void; **示例:** ```ts -var abilityDelegator; -var want = { +let abilityDelegator; +let want = { bundleName: "bundleName", abilityName: "abilityName" }; @@ -440,8 +424,6 @@ abilityDelegator.startAbility(want, (err : any, data : any) => { }); ``` - - ### startAbility9+ startAbility(want: Want): Promise\; @@ -465,8 +447,8 @@ startAbility(want: Want): Promise\; **示例:** ```ts -var abilityDelegator; -var want = { +let abilityDelegator; +let want = { bundleName: "bundleName", abilityName: "abilityName" }; @@ -477,8 +459,6 @@ abilityDelegator.startAbility(want).then((data: any) => { }); ``` - - ### doAbilityForeground9+ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void; @@ -497,8 +477,8 @@ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void; **示例:** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -510,8 +490,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### doAbilityForeground9+ doAbilityForeground(ability: UIAbility): Promise\; @@ -535,8 +513,8 @@ doAbilityForeground(ability: UIAbility): Promise\; **示例:** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -548,8 +526,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### doAbilityBackground9+ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void; @@ -568,8 +544,8 @@ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void; **示例:** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -581,8 +557,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### doAbilityBackground9+ doAbilityBackground(ability: UIAbility): Promise\; @@ -606,8 +580,8 @@ doAbilityBackground(ability: UIAbility): Promise\; **示例:** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -619,8 +593,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### printSync9+ printSync(msg: string): void; @@ -638,15 +610,13 @@ printSync(msg: string): void; **示例:** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.printSync(msg); ``` - - ### print print(msg: string, callback: AsyncCallback\): void; @@ -665,8 +635,8 @@ print(msg: string, callback: AsyncCallback\): void; **示例:** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.print(msg, (err : any) => { @@ -674,8 +644,6 @@ abilityDelegator.print(msg, (err : any) => { }); ``` - - ### print print(msg: string): Promise\; @@ -699,8 +667,8 @@ print(msg: string): Promise\; **示例:** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.print(msg).then(() => { @@ -708,8 +676,6 @@ abilityDelegator.print(msg).then(() => { }); ``` - - ### executeShellCommand executeShellCommand(cmd: string, callback: AsyncCallback\): void; @@ -728,8 +694,8 @@ executeShellCommand(cmd: string, callback: AsyncCallback\): void **示例:** ```ts -var abilityDelegator; -var cmd = "cmd"; +let abilityDelegator; +let cmd = "cmd"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { @@ -737,8 +703,6 @@ abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { }); ``` - - ### executeShellCommand executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void; @@ -758,9 +722,9 @@ executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\ { @@ -768,8 +732,6 @@ abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { }); ``` - - ### executeShellCommand executeShellCommand(cmd: string, timeoutSecs?: number): Promise\; @@ -794,9 +756,9 @@ executeShellCommand(cmd: string, timeoutSecs?: number): Promise\ **示例:** ```ts -var abilityDelegator; -var cmd = "cmd"; -var timeout = 100; +let abilityDelegator; +let cmd = "cmd"; +let timeout = 100; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { @@ -804,8 +766,6 @@ abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { }); ``` - - ### finishTest9+ finishTest(msg: string, code: number, callback: AsyncCallback\): void; @@ -825,8 +785,8 @@ finishTest(msg: string, code: number, callback: AsyncCallback\): void; **示例:** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.finishTest(msg, 0, (err : any) => { @@ -834,8 +794,6 @@ abilityDelegator.finishTest(msg, 0, (err : any) => { }); ``` - - ### finishTest9+ finishTest(msg: string, code: number): Promise\; @@ -860,8 +818,8 @@ finishTest(msg: string, code: number): Promise\; **示例:** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.finishTest(msg, 0).then(() => { @@ -887,9 +845,9 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ { }); ``` - - ### addAbilityStageMonitor9+ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; @@ -925,9 +881,9 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; **示例:** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -956,9 +912,9 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ **示例:** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -969,8 +925,6 @@ abilityDelegator.removeAbilityStageMonitor(monitor, (err : any) => { }); ``` - - ### removeAbilityStageMonitor9+ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; @@ -994,9 +948,9 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; **示例:** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -1025,13 +979,13 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ { }); ``` - diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index 79dd323daeeef52717d3d571181603ed51affe57..12de812a9cb3cb1f81063f504d53c73517d4895d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -28,7 +28,8 @@ AbilityRunningInfo模块提供对Ability运行的相关信息和状态的定义 **示例:** ```ts -import abilitymanager from '@ohos.application.abilityManager'; +import abilitymanager from '@ohos.app.ability.abilityManager'; + abilitymanager.getAbilityRunningInfos((err,data) => { console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); for (let i = 0; i < data.length; i++) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 4664de608fb2b18de7a2160e1c178ade303a1de2..c5b4aae5a0e82d0bdccc8b93738baa8e59340e73 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -14,7 +14,8 @@ AbilityStageContext提供允许访问特定于abilityStage的资源的能力, 通过AbilityStage实例来获取。 ```ts -import AbilityStage from '@ohos.application.AbilityStage'; +import AbilityStage from '@ohos.app.ability.AbilityStage'; + class MyAbilityStage extends AbilityStage { onCreate() { let abilityStageContext = this.context; diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md index 840cc6da4dab10dd9bb3898dbdb2a4ce59422b74..68ca3259d21e37889c4a0efd0baba95d47929bd1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -11,7 +11,7 @@ **示例:** ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; let monitor = { moduleName: "feature_as1", 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 32084be192c100c27333aa0522958e1dd6eefd61..9e077460adb3d1fd332efcc1d58d6c3143393ee3 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 @@ -16,7 +16,7 @@ **示例:** ```ts -import appManager from "@ohos.application.appManager" +import appManager from "@ohos.app.ability.appManager"; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index 8bcef45ca75f01221cecee54b083b55ec719ff38..f45abf105bdaa9d18ffd2ee8b07405a44204249a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -31,8 +31,9 @@ ExtensionContext主要用于查询所属Extension的信息、Module的配置信 三个Module内都定义一个相同名称的ServiceExtension: ```ts -import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' -import Want from '@ohos.application.Want' +import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility'; +import Want from '@ohos.app.ability.Want'; + export default class TheServiceExtension extends ServiceExtension { onCreate(want:Want) { console.log('ServiceAbility onCreate, want: ' + want.abilityName); diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md index 69f0f5d0f9e5191ebacfc6e91ee5ac3da0ba0fc9..1b0a054930850bcdc387db9edb98d51e1ce4ab18 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -17,7 +17,7 @@ **示例:** ```ts -import appManager from '@ohos.application.appManager' +import appManager from '@ohos.app.ability.appManager'; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index e184f612c16a0a00b85a2935c38b446cebedc85b..d28e3d0eb888323684bab4865ad5c0c9011df71d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -23,7 +23,7 @@ **示例:** ```ts -import appManager from '@ohos.application.appManager'; +import appManager from '@ohos.app.ability.appManager'; appManager.getProcessRunningInfos().then((data) => { console.log('success:' + JSON.stringify(data)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 2b664bda21be0db446efd27cc1faf2cb864b0891..aeae1305fb1d5451d69bd96ab0b3ec54b0c912ec 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -19,7 +19,7 @@ **示例:** ```ts -import AbilityDelegatorRegistry from "@ohos.application.abilityDelegatorRegistry"; +import AbilityDelegatorRegistry from "@ohos.app.ability.abilityDelegatorRegistry"; let abilityDelegator; let cmd = "cmd"; diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md index b6c47634264863083e9a81d534c526b638fa1411..17317ee22534a529e150a7bf39f3f34895802292 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -389,7 +389,7 @@ removeFirst(): T | 错误码ID | 错误信息 | | -------- | -------- | | 10200011 | The removeFirst method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **示例:** @@ -424,7 +424,7 @@ removeLast(): T | 错误码ID | 错误信息 | | -------- | -------- | | 10200011 | The removeLast method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **示例:** @@ -504,7 +504,7 @@ removeFirstFound(element: T): boolean | 错误码ID | 错误信息 | | -------- | -------- | | 10200011 | The removeFirstFound method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **示例:** @@ -544,7 +544,7 @@ removeLastFound(element: T): boolean | 错误码ID | 错误信息 | | -------- | -------- | | 10200011 | The removeLastFound method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **示例:** 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 78c725ceaed8d3b32ac8b3a08f6981ae7d04c202..8f4c2dece5dcff8a8a068a0dba8568b9d122cef9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -7,12 +7,12 @@ 媒体子系统包含了音视频相关媒体业务,提供以下常用功能: -- 音频播放([AudioPlayer](#audioplayer)) -- 视频播放([VideoPlayer](#videoplayer8)) -- 音频录制([AudioRecorder](#audiorecorder)) -- 视频录制([VideoRecorder](#videorecorder9)) - -后续将提供以下功能:DataSource音视频播放、音视频编解码、容器封装解封装、媒体能力查询等功能。 +- 音视频播放([AVPlayer](#avplayer9)9+),[AudioPlayer](#audioplayerdeprecated)6+和[VideoPlayer](#videoplayer)8+整合,升级了状态机和错误码,推荐使用 +- 音视频录制([AVRecorder](#avrecorder9)9+),[AudioRecorder](#audiorecorderdeprecated)6+和[VideoRecorder](#videorecorder9)9+整合,推荐使用 +- 音频播放([AudioPlayer](#audioplayerdeprecated)6+),[AVPlayer](#avplayer9)9+发布后停止维护,请使用[AVPlayer](#avplayer9)9+ +- 视频播放([VideoPlayer](#videoplayerdeprecated)8+),[AVPlayer](#avplayer9)9+发布后停止维护,请使用[AVPlayer](#avplayer9)9+ +- 音频录制([AudioRecorder](#audiorecorderdeprecated)6+),[AVRecorder](#avrecorder9)9+发布后停止维护,请使用[AVRecorder](#avrecorder9)9+ +- 视频录制([VideoRecorder](#videorecorder9)9+),[AVRecorder](#avrecorder9)9+发布后停止维护,请使用[AVRecorder](#avrecorder9)9+ ## 导入模块 @@ -20,110 +20,163 @@ import media from '@ohos.multimedia.media'; ``` -## media.createAudioPlayer +## media.createAVPlayer9+ -createAudioPlayer(): [AudioPlayer](#audioplayer) +createAVPlayer(callback: AsyncCallback\): void -同步方式创建音频播放实例。 +异步方式创建音视频播放实例,通过注册回调函数获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**返回值:** +**参数:** -| 类型 | 说明 | -| --------------------------- | ------------------------------------------------------------ | -| [AudioPlayer](#audioplayer) | 返回AudioPlayer类实例,失败时返回null。可用于音频播放、暂停、停止等操作。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[AVPlayer](#avplayer9)> | 是 | 回调函数。异步返回AVPlayer实例,失败时返回null。可用于音视频播放。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 5400101 | No memory. Return by callback. | **示例:** ```js -let audioPlayer = media.createAudioPlayer(); +let avPlayer + +media.createAVPlayer((error, video) => { + if (video != null) { + avPlayer = video; + console.info('createAVPlayer success'); + } else { + console.info(`createAVPlayer fail, error:${error}`); + } +}); ``` -## media.createVideoPlayer8+ +## media.createAVPlayer9+ -createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void +createAVPlayer(): Promise\ -异步方式创建视频播放实例,通过注册回调函数获取返回值。 +异步方式创建音视频播放实例,通过Promise获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**参数:** +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| Promise\<[AVPlayer](#avplayer9)> | Promise对象。异步返回AVPlayer实例,失败时返回null。可用于录制视频媒体。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | 是 | 回调函数。异步返回VideoPlayer实例,失败时返回null。可用于管理和播放视频媒体。 | +| 错误码ID | 错误信息 | +| -------- | ----------------------------- | +| 5400101 | No memory. Return by promise. | **示例:** ```js -let videoPlayer +let avPlayer -media.createVideoPlayer((error, video) => { - if (video != null) { - videoPlayer = video; - console.info('video createVideoPlayer success'); +media.createAVPlayer().then((video) => { + if (video != null) { + avPlayer = video; + console.info('createAVPlayer success'); } else { - console.info(`video createVideoPlayer fail, error:${error}`); + console.info('createAVPlayer fail'); } +}).catch((error) => { + console.info(`AVPlayer catchCallback, error:${error}`); }); ``` -## media.createVideoPlayer8+ +## media.createAVRecorder9+ -createVideoPlayer(): Promise<[VideoPlayer](#videoplayer8)> +createAVRecorder(callback: AsyncCallback\): void -异步方式创建视频播放实例,通过Promise获取返回值。 +异步方式创建音视频录制实例。通过注册回调函数获取返回值。 +一台设备只允许创建一个录制实例。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -**返回值:** +**参数:** -| 类型 | 说明 | -| ------------------------------------- | ------------------------------------------------------------ | -| Promise<[VideoPlayer](#videoplayer8)> | Promise对象。异步返回VideoPlayer实例,失败时返回null。可用于管理和播放视频媒体。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[AVRecorder](#avrecorder9)> | 是 | 回调函数。异步返回AVRecorder实例,失败时返回null。可用于录制音视频媒体。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 5400101 | No memory. Return by callback. | **示例:** ```js -let videoPlayer +let avRecorder -media.createVideoPlayer().then((video) => { - if (video != null) { - videoPlayer = video; - console.info('video createVideoPlayer success'); +media.createAVRecorder((error, recorder) => { + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); } else { - console.info('video createVideoPlayer fail'); + console.info(`createAVRecorder fail, error:${error}`); } -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); }); ``` -## media.createAudioRecorder +## media.createAVRecorder9+ -createAudioRecorder(): AudioRecorder +createAVRecorder(): Promise\ -创建音频录制的实例来控制音频的录制。 +异步方式创建音视频录制实例。通过Promise获取返回值。 一台设备只允许创建一个录制实例。 -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -**返回值:** +**返回值:** -| 类型 | 说明 | -| ------------------------------- | ------------------------------------------------------------ | -| [AudioRecorder](#audiorecorder) | 返回AudioRecorder类实例,失败时返回null。可用于录制音频媒体。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------------------------------ | +| Promise\<[AVRecorder](#avrecorder9)> | Promise对象。异步返回AVRecorder实例,失败时返回null。可用于录制音视频媒体。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------- | +| 5400101 | No memory. Return by promise. | **示例:** ```js -let audioRecorder = media.createAudioRecorder(); +let avRecorder + +media.createAVRecorder().then((recorder) => { + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.info('createAVRecorder fail'); + } +}).catch((error) => { + console.info(`createAVRecorder catchCallback, error:${error}`); +}); ``` ## media.createVideoRecorder9+ -createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): void +createVideoRecorder(callback: AsyncCallback\): void 异步方式创建视频录制实例。通过注册回调函数获取返回值。 一台设备只允许创建一个录制实例。 @@ -134,8 +187,8 @@ createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------- | ---- | ------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | 是 | 回调函数。异步返回VideoRecorder实例,失败时返回null。可用于录制视频媒体。 | **错误码:** @@ -163,7 +216,7 @@ media.createVideoRecorder((error, video) => { ## media.createVideoRecorder9+ -createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)> +createVideoRecorder(): Promise\ 异步方式创建视频录制实例。通过Promise获取返回值。 一台设备只允许创建一个录制实例。 @@ -203,26 +256,24 @@ media.createVideoRecorder().then((video) => { }); ``` +## AVErrorCode9+ - -## MediaErrorCode8+ - -媒体服务错误类型枚举。 +[媒体错误码](../errorcodes/errorcode-media.md)类型枚举 **系统能力:** SystemCapability.Multimedia.Media.Core -| 名称 | 值 | 说明 | -| -------------------------- | ---- | -------------------------------------- | -| MSERR_OK | 0 | 表示操作成功。 | -| MSERR_NO_MEMORY | 1 | 表示申请内存失败,系统可能无可用内存。 | -| MSERR_OPERATION_NOT_PERMIT | 2 | 表示无权限执行此操作。 | -| MSERR_INVALID_VAL | 3 | 表示传入入参无效。 | -| MSERR_IO | 4 | 表示发生IO错误。 | -| MSERR_TIMEOUT | 5 | 表示操作超时。 | -| MSERR_UNKNOWN | 6 | 表示未知错误。 | -| MSERR_SERVICE_DIED | 7 | 表示服务端失效。 | -| MSERR_INVALID_STATE | 8 | 表示在当前状态下,不允许执行此操作。 | -| MSERR_UNSUPPORTED | 9 | 表示在当前版本下,不支持此操作。 | +| 名称 | 值 | 说明 | +| :------------------------- | ------- | ------------------------------------ | +| AVERR_OK | 0 | 表示操作成功。 | +| AVERR_NO_PERMISSION | 201 | 表示无权限执行此操作。 | +| AVERR_INVALID_PARAMETER | 401 | 表示传入入参无效。 | +| AVERR_UNSUPPORT_CAPABILITY | 801 | 表示当前版本不支持该API能力。 | +| AVERR_NO_MEMORY | 5400101 | 表示系统内存不足或服务数量达到上限。 | +| AVERR_OPERATE_NOT_PERMIT | 5400102 | 表示当前状态不允许或无权执行此操作。 | +| AVERR_IO | 5400103 | 表示数据流异常信息。 | +| AVERR_TIMEOUT | 5400104 | 表示系统或网络响应超时。 | +| AVERR_SERVICE_DIED | 5400105 | 表示服务进程死亡。 | +| AVERR_UNSUPPORT_FORMAT | 5400106 | 表示不支持当前媒体资源的格式。 | ## MediaType8+ @@ -284,1247 +335,1277 @@ Codec MIME类型枚举。 | BUFFERING_PERCENT | 3 | 表示缓存百分比。 | | CACHED_DURATION | 4 | 表示缓存时长,单位为毫秒(ms)。 | -## AudioPlayer +## StateChangeReason9+ -音频播放管理类,用于管理和播放音频媒体。在调用AudioPlayer的方法前,需要先通过[createAudioPlayer()](#mediacreateaudioplayer)构建一个[AudioPlayer](#audioplayer)实例。 +表示播放或录制实例状态机切换原因的枚举,伴随state一起上报。 -音频播放demo可参考:[音频播放开发指导](../../media/audio-playback.md) +**系统能力:** SystemCapability.Multimedia.Media.Core -### 属性 +| 名称 | 值 | 说明 | +| ---------- | ---- | ------------------------------------------------------------ | +| USER | 1 | 表示用户行为造成的状态切换,由用户或客户端主动调用接口产生。 | +| BACKGROUND | 2 | 表示系统行为造成的状态切换,比如应用未注册播控中心权限,退到后台时被系统强制暂停或停止。 | -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +## AVPlayer9+ -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| src | string | 是 | 是 | 音频媒体URI,支持当前主流的音频格式(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
**需要权限:** ohos.permission.READ_MEDIA 或 ohos.permission.INTERNET。 | -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 音频媒体文件描述,使用场景:应用中的音频资源被连续存储在同一个文件中。
**使用示例**:
假设一个连续存储的音乐文件:
音乐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
| -| loop | boolean | 是 | 是 | 音频循环播放属性,设置为'true'表示循环播放。 | -| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | 是 | 是 | 音频焦点模型。 | -| currentTime | number | 是 | 否 | 音频的当前播放位置,单位为毫秒(ms)。 | -| duration | number | 是 | 否 | 音频时长,单位为毫秒(ms)。 | -| state | [AudioState](#audiostate) | 是 | 否 | 可以查询音频播放的状态,该状态不可作为调用play/pause/stop等状态切换的触发条件。 | -### play +播放管理类,用于管理和播放媒体资源。在调用AVPlayer的方法前,需要先通过[createAVPlayer()](#mediacreateavplayer9)构建一个AVPlayer实例。 -play(): void +Audio/Video播放demo可参考:[AVPlayer开发指导](../../media/avplayer-playback.md)。 -开始播放音频资源,需在[dataLoad](#audioplayer_on)事件成功触发后,才能调用。 +### 属性 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**示例:** +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| 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**状态下设置,静态属性。
使用场景:应用中的媒体资源被连续存储在同一个文件中。
**使用示例**:
假设一个连续存储的媒体文件:
视频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。 | +| surfaceId9+ | string | 是 | 是 | 视频窗口ID,默认无窗口,只允许在**initialized**状态下设置,静态属性。
使用场景:视频播放的窗口渲染,纯音频播放不用设置。
**使用示例**:
[通过Xcomponent创建surfaceId](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid)。 | +| loop9+ | boolean | 是 | 是 | 视频循环播放属性,默认'false',设置为'true'表示循环播放,动态属性。
只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 | +| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式,默认VIDEO_SCALE_TYPE_FIT_CROP,动态属性。
只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | 是 | 是 | 音频焦点模型,默认SHARE_MODE,动态属性。
只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 | +| audioRendererInfo10+ | [audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8) | 是 | 是 | 设置音频渲染信息。
只允许在**initialized**状态下设置 | +| state9+ | [AVPlayerState](#avplayerstate9) | 是 | 否 | 音视频播放的状态,全状态有效,可查询参数。 | +| currentTime9+ | number | 是 | 否 | 视频的当前播放位置,单位为毫秒(ms),可查询参数。
返回为(-1)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 | +| duration9+ | number | 是 | 否 | 视频时长,单位为毫秒(ms),可查询参数。
返回为(-1)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。
直播场景默认返回(-1)。 | +| width9+ | number | 是 | 否 | 视频宽,单位为像素(px),可查询参数。
返回为(0)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 | +| height9+ | number | 是 | 否 | 视频高,单位为像素(px),可查询参数。
返回为(0)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 | -```js -audioPlayer.on('play', () => { //设置'play'事件回调 - console.log('audio play success'); -}); -audioPlayer.play(); -``` +### on('stateChange')9+ -### pause +on(type: 'stateChange', callback: (state: AVPlayerState, reason: StateChangeReason) => void): void -pause(): void +监听播放状态机AVPlayerState切换的事件。 -暂停播放音频资源。 +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 状态机切换事件回调类型,支持的事件:'stateChange',用户操作和系统都会触发此事件。 | +| callback | function | 是 | 状态机切换事件回调方法:
state: [AVPlayerState](#avplayerstate9),表示当前播放状态;
reason: [StateChangeReason](#statechangereason9),表示当前播放状态的切换原因。 | **示例:** ```js -audioPlayer.on('pause', () => { //设置'pause'事件回调 - console.log('audio pause success'); -}); -audioPlayer.pause(); +avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': + console.info('state idle called') + break; + case 'initialized': + console.info('initialized prepared called') + break; + case 'prepared': + console.info('state prepared called') + break; + case 'playing': + console.info('state playing called') + break; + case 'paused': + console.info('state paused called') + break; + case 'completed': + console.info('state completed called') + break; + case 'stopped': + console.info('state stopped called') + break; + case 'released': + console.info('state released called') + break; + case 'error': + console.info('state error called') + break; + default: + console.info('unkown state :' + state) + break; + } +}) ``` -### stop +### off('stateChange')9+ -stop(): void +off(type: 'stateChange'): void -停止播放音频资源。 +取消监听播放状态机[AVPlayerState](#avplayerstate9)切换的事件。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------------------------------------------------- | +| type | string | 是 | 状态机切换事件回调类型,取消注册的事件:'stateChange' | **示例:** ```js -audioPlayer.on('stop', () => { //设置'stop'事件回调 - console.log('audio stop success'); -}); -audioPlayer.stop(); +avPlayer.off('stateChange') ``` -### reset7+ +### on('error')9+ -reset(): void +on(type: 'error', callback: ErrorCallback): void -重置播放音频资源。 +监听[AVPlayer](#avplayer9)的错误事件,该事件仅用于错误提示,不需要用户停止播控动作。如果此时[AVPlayerState](#avplayerstate9)也切至error状态,用户需要通过reset()或者release()退出播放操作。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 错误事件回调类型,支持的事件:'error',用户操作和系统都会触发此事件。 | +| callback | function | 是 | 错误事件回调方法:使用播放器的过程中发生错误,会提供错误码ID和错误信息。 | + +AVPlayer回调的**错误分类**可以分为以下几种: + +| 错误码ID | 错误信息 | 说明 | +| -------- | --------------------- | ------------------------------------------------------------ | +| 201 | No Permission: | 无权限执行此操作,[AVPlayerState](#avplayerstate9)会进入error状态。 | +| 401 | Invalid Parameter: | 入参错误,表示调用无效。 | +| 801 | Unsupport Capability: | 不支持该API能力,表示调用无效。 | +| 5400101 | No Memory: | 播放内存不足,[AVPlayerState](#avplayerstate9)会进入error状态。 | +| 5400102 | Operate Not Permit: | 当前状态机不支持此操作,表示调用无效。 | +| 5400103 | IO Error: | 播放中发现码流异常。 | +| 5400104 | Network Timeout: | 网络原因超时响应,[AVPlayerState](#avplayerstate9)会进入error状态。 | +| 5400105 | Service Died: | 播放进程死亡,[AVPlayerState](#avplayerstate9)会进入error状态。 | +| 5400106 | Unsupport Format: | 不支持的文件格式,[AVPlayerState](#avplayerstate9)会进入error状态。 | **示例:** ```js -audioPlayer.on('reset', () => { //设置'reset'事件回调 - console.log('audio reset success'); -}); -audioPlayer.reset(); +avPlayer.on('error', (error) => { + console.info('error happened,and error message is :' + error.message) + console.info('error happened,and error code is :' + error.code) +}) ``` -### seek +### off('error')9+ -seek(timeMs: number): void +off(type: 'error'): void -跳转到指定播放位置。 +取消监听播放的错误事件。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ----------------------------------------------------------- | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围[0, duration]。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------------------------------------- | +| type | string | 是 | 错误事件回调类型,取消注册的事件:'error' | **示例:** ```js -audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调 - if (seekDoneTime == null) { - console.info('audio seek fail'); - return; - } - console.log('audio seek success. seekDoneTime: ' + seekDoneTime); -}); -audioPlayer.seek(30000); //seek到30000ms的位置 +avPlayer.off('error') ``` -### setVolume +### prepare9+ -setVolume(vol: number): void +prepare(callback: AsyncCallback\): void -设置音量。 +通过回调方式准备播放视频,需在[stateChange](#stateChange_on)事件成功触发至initialized状态后,才能调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | -------------------- | +| callback | function | 是 | 准备播放的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400106 | Unsupport format. Return by callback. | **示例:** ```js -audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 - console.log('audio volumeChange success'); -}); -audioPlayer.setVolume(1); //设置音量到100% +avPlayer.prepare((err) => { + if (err == null) { + console.info('prepare success'); + } else { + console.error('prepare filed,error message is :' + err.message) + } +}) ``` -### release +### prepare9+ -release(): void +prepare(): Promise\ -释放音频资源。 +通过Promise方式准备播放视频,需在[stateChange](#stateChange_on)事件成功触发至initialized状态后,才能调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 准备播放的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400106 | Unsupport format. Return by promise. | **示例:** ```js -audioPlayer.release(); -audioPlayer = undefined; +avPlayer.prepare().then(() => { + console.info('prepare success'); +}, (err) => { + console.error('prepare filed,error message is :' + err.message) +}) ``` -### getTrackDescription8+ +### play9+ -getTrackDescription(callback: AsyncCallback>): void +play(callback: AsyncCallback\): void -通过回调方式获取音频轨道信息。需在[dataLoad](#audioplayer_on)事件成功触发后,才能调用。 +通过回调方式开始播放音视频资源,只能在prepared/paused/complete状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | -| callback | AsyncCallback> | 是 | 音频轨道信息MediaDescription数组回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | -------------------- | +| callback | function | 是 | 开始播放的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **示例:** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } -} - -audioPlayer.getTrackDescription((error, arrList) => { - if (arrList != null) { - for (let i = 0; i < arrList.length; i++) { - printfDescription(arrList[i]); - } +avPlayer.play((err) => { + if (err == null) { + console.info('play success'); } else { - console.log(`audio getTrackDescription fail, error:${error}`); + console.error('play filed,error message is :' + err.message) } -}); +}) ``` -### getTrackDescription8+ +### play9+ -getTrackDescription(): Promise> +play(): Promise\ -通过Promise方式获取音频轨道信息。需在[dataLoad](#audioplayer_on)事件成功触发后,才能调用 +通过Promise方式开始播放音视频资源,只能在prepared/paused/complete状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **返回值:** -| 类型 | 说明 | -| ------------------------------------------------------ | ----------------------------------------------- | -| Promise> | 音频轨道信息MediaDescription数组Promise返回值。 | +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 开始播放的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **示例:** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } -} -let arrayDescription = null -audioPlayer.getTrackDescription().then((arrList) => { - if (arrList != null) { - arrayDescription = arrList; - } else { - console.log('audio getTrackDescription fail'); - } -}).catch((error) => { - console.info(`audio catchCallback, error:${error}`); -}); - -for (let i = 0; i < arrayDescription.length; i++) { - printfDescription(arrayDescription[i]); -} +avPlayer.play().then(() => { + console.info('play success'); +}, (err) => { + console.error('play filed,error message is :' + err.message) +}) ``` -### on('bufferingUpdate')8+ +### pause9+ -on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void +pause(callback: AsyncCallback\): void -开始订阅音频缓存更新事件。仅网络播放支持该订阅事件。 +通过回调方式暂停播放音视频资源,只能在playing状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 音频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | -| callback | function | 是 | 音频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | -------------------- | +| callback | function | 是 | 暂停播放的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **示例:** ```js -audioPlayer.on('bufferingUpdate', (infoType, value) => { - console.log('audio bufferingInfo type: ' + infoType); - console.log('audio bufferingInfo value: ' + value); -}); +avPlayer.pause((err) => { + if (err == null) { + console.info('pause success'); + } else { + console.error('pause filed,error message is :' + err.message) + } +}) ``` - ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') +### pause9+ -on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void +pause(): Promise\ -开始订阅音频播放事件。 +通过Promise方式暂停播放音视频资源,只能在playing状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**参数:** +**返回值:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。
- 'play':完成[play()](#audioplayer_play)调用,音频开始播放,触发该事件。
- 'pause':完成[pause()](#audioplayer_pause)调用,音频暂停播放,触发该事件。
- 'stop':完成[stop()](#audioplayer_stop)调用,音频停止播放,触发该事件。
- 'reset':完成[reset()](#audioplayer_reset)调用,播放器重置,触发该事件。
- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。
- 'finish':完成音频播放后触发该事件。
- 'volumeChange':完成[setVolume()](#audioplayer_setvolume)调用,播放音量改变后触发该事件。 | -| callback | () => void | 是 | 播放事件回调方法。 | +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 暂停播放的Promise返回值。 | -**示例:** +**错误码:** -```js -import fileio from '@ohos.fileio' +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 -audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 - console.info('audio set source success'); - audioPlayer.play(); //开始播放,并触发'play'事件回调 -}); -audioPlayer.on('play', () => { //设置'play'事件回调 - console.info('audio play success'); - audioPlayer.seek(30000); //调用seek方法,并触发'timeUpdate'事件回调 -}); -audioPlayer.on('pause', () => { //设置'pause'事件回调 - console.info('audio pause success'); - audioPlayer.stop(); //停止播放,并触发'stop'事件回调 -}); -audioPlayer.on('reset', () => { //设置'reset'事件回调 - console.info('audio reset success'); - audioPlayer.release(); //释放播放实例资源 - audioPlayer = undefined; -}); -audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调 - if (seekDoneTime == null) { - console.info('audio seek fail'); - return; - } - console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); //设置音量为50%,并触发'volumeChange'事件回调 -}); -audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 - console.info('audio volumeChange success'); - audioPlayer.pause(); //暂停播放,并触发'pause'事件回调 -}); -audioPlayer.on('finish', () => { //设置'finish'事件回调 - console.info('audio play finish'); - audioPlayer.stop(); //停止播放,并触发'stop'事件回调 -}); -audioPlayer.on('error', (error) => { //设置'error'事件回调 - console.info(`audio error called, error: ${error}`); -}); +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | -// 用户选择视频设置fd(本地播放) -let fdPath = 'fd://'; -// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上 -let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; -fileio.open(path).then((fdValue) => { - fdPath = fdPath + '' + fdValue; - console.info('open fd success fd is' + fdPath); +**示例:** + +```js +avPlayer.pause().then(() => { + console.info('pause success'); }, (err) => { - console.info('open fd failed err is' + err); -}).catch((err) => { - console.info('open fd failed err is' + err); -}); -audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 + console.error('pause filed,error message is :' + err.message) +}) ``` -### on('timeUpdate') +### stop9+ -on(type: 'timeUpdate', callback: Callback\): void +stop(callback: AsyncCallback\): void -开始订阅音频播放时间更新事件。处于播放状态时,每隔1s上报一次该事件。 +通过回调方式停止播放音视频资源,只能在prepared/playing/paused/complete状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放事件回调类型,支持的事件包括:'timeUpdate'。
- 'timeUpdate':音频播放时间戳更新,开始播放后自动触发该事件。 | -| callback | Callback\ | 是 | 播放事件回调方法。回调方法入参为更新后的时间戳。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | -------------------- | +| callback | function | 是 | 停止播放的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **示例:** ```js -audioPlayer.on('timeUpdate', (newTime) => { //设置'timeUpdate'事件回调 - if (newTime == null) { - console.info('audio timeUpadate fail'); - return; +avPlayer.stop((err) => { + if (err == null) { + console.info('stop success'); + } else { + console.error('stop filed,error message is :' + err.message) } - console.log('audio timeUpadate success. seekDoneTime: ' + newTime); -}); -audioPlayer.play(); //开始播放后,自动触发时间戳更新事件 +}) ``` -### on('error') +### stop9+ -on(type: 'error', callback: ErrorCallback): void +stop(): Promise\ -开始订阅音频播放错误事件,当上报error错误事件后,用户需处理error事件,退出播放操作。 +通过Promise方式停止播放音视频资源,只能在prepared/playing/paused/complete状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**参数:** +**返回值:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':音频播放中发生错误,触发该事件。 | -| callback | ErrorCallback | 是 | 播放错误事件回调方法。 | +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 停止播放的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **示例:** ```js -audioPlayer.on('error', (error) => { //设置'error'事件回调 - console.info(`audio error called, error: ${error}`); -}); -audioPlayer.setVolume(3); //设置volume为无效值,触发'error'事件 +avPlayer.stop().then(() => { + console.info('stop success'); +}, (err) => { + console.error('stop filed,error message is :' + err.message) +}) ``` -## AudioState - -音频播放的状态机。可通过state属性获取当前状态。 +### reset9+ -**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer +reset(callback: AsyncCallback\): void -| 名称 | 类型 | 说明 | -| ------- | ------ | ---------------------------------------------- | -| idle | string | 音频播放空闲,dataload/reset成功后处于此状态。 | -| playing | string | 音频正在播放,play成功后处于此状态。 | -| paused | string | 音频暂停播放,pause成功后处于此状态。 | -| stopped | string | 音频播放停止,stop/播放结束后处于此状态。 | -| error | string | 错误状态。 | +通过回调方式重置播放,只能在initialized/prepared/playing/paused/complete/stopped/error状态调用。 -## AVFileDescriptor9+ +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -音视频文件资源描述,一种特殊资源的播放方式,使用场景:应用中的音频资源被连续存储在同一个文件中,需要根据偏移量和长度进行播放。 +**参数:** -**系统能力:** SystemCapability.Multimedia.Media.Core +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | -------------------- | +| callback | function | 是 | 重置播放的回调方法。 | -| 名称 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| fd | number | 是 | 资源句柄,通过resourceManager.getRawFileDescriptor获取 | -| offset | number | 是 | 资源偏移量,需要基于预置资源的信息输入,非法值会造成音视频资源解析错误 | -| length | number | 是 | 资源长度,需要基于预置资源的信息输入,非法值会造成音视频资源解析错误 | +**错误码:** -## VideoPlayer8+ +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -视频播放管理类,用于管理和播放视频媒体。在调用VideoPlayer的方法前,需要先通过[createVideoPlayer()](#mediacreatevideoplayer8)构建一个[VideoPlayer](#videoplayer8)实例。 +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | -视频播放demo可参考:[视频播放开发指导](../../media/video-playback.md) +**示例:** -### 属性 +```js +avPlayer.reset((err) => { + if (err == null) { + console.info('reset success'); + } else { + console.error('reset filed,error message is :' + err.message) + } +}) +``` -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +### reset9+ -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | 是 | 是 | 视频媒体URL,支持当前主流的视频格式(mp4、mpeg-ts、webm、mkv)。
**支持路径示例**:
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) | 是 | 是 | 视频媒体文件描述,使用场景:应用中的视频资源被连续存储在同一个文件中。
**使用示例**:
假设一个连续存储的音乐文件:
视频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
| -| loop8+ | boolean | 是 | 是 | 视频循环播放属性,设置为'true'表示循环播放。 | -| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式。 | -| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | 是 | 是 | 音频焦点模型。 | -| currentTime8+ | number | 是 | 否 | 视频的当前播放位置,单位为毫秒(ms)。 | -| duration8+ | number | 是 | 否 | 视频时长,单位为毫秒(ms),返回-1表示直播模式。 | -| state8+ | [VideoPlayState](#videoplaystate8) | 是 | 否 | 视频播放的状态。 | -| width8+ | number | 是 | 否 | 视频宽,单位为像素(px)。 | -| height8+ | number | 是 | 否 | 视频高,单位为像素(px)。 | +reset(): Promise\ -### setDisplaySurface8+ +通过Promise方式通过Promise方式重置播放,只能在initialized/prepared/playing/paused/complete/stopped/error状态调用。 -setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -通过回调方式设置SurfaceId。 +**返回值:** -*注意:SetDisplaySurface需要在设置url和Prepare之间,无音频的视频流必须设置Surface否则Prepare失败。 +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 重置播放的Promise返回值。 | -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**错误码:** -**参数:** +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -| 参数名 | 类型 | 必填 | 说明 | -| --------- | -------------------- | ---- | ------------------------- | -| surfaceId | string | 是 | SurfaceId | -| callback | AsyncCallback\ | 是 | 设置SurfaceId的回调方法。 | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **示例:** ```js -let surfaceId = null; -videoPlayer.setDisplaySurface(surfaceId, (err) => { - if (err == null) { - console.info('setDisplaySurface success!'); - } else { - console.info('setDisplaySurface fail!'); - } -}); +avPlayer.reset().then(() => { + console.info('reset success'); +}, (err) => { + console.error('reset filed,error message is :' + err.message) +}) ``` -### setDisplaySurface8+ +### release9+ -setDisplaySurface(surfaceId: string): Promise\ +release(callback: AsyncCallback\): void -通过Promise方式设置SurfaceId。 +通过回调方式销毁播放资源,除released状态,都可以调用。 -*注意:SetDisplaySurface需要在设置url和Prepare之间,无音频的视频流必须设置Surface否则Prepare失败。 - -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | --------- | -| surfaceId | string | 是 | SurfaceId | - -**返回值:** - -| 类型 | 说明 | -| -------------- | ------------------------------ | -| Promise\ | 设置SurfaceId的Promise返回值。 | - -**示例:** - -```js -let surfaceId = null; -videoPlayer.setDisplaySurface(surfaceId).then(() => { - console.info('setDisplaySurface success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); -``` - -### prepare8+ - -prepare(callback: AsyncCallback\): void - -通过回调方式准备播放视频。 +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | -------------------- | +| callback | function | 是 | 销毁播放的回调方法。 | -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**错误码:** -**参数:** +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | 是 | 准备播放视频的回调方法。 | +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **示例:** ```js -videoPlayer.prepare((err) => { +avPlayer.release((err) => { if (err == null) { - console.info('prepare success!'); + console.info('reset success'); } else { - console.info('prepare fail!'); + console.error('release filed,error message is :' + err.message) } -}); +}) ``` -### prepare8+ +### release9+ -prepare(): Promise\ +release(): Promise\ -通过Promise方式准备播放视频。 +通过Promise方式通过Promise方式销毁播放,除released状态,都可以调用。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **返回值:** -| 类型 | 说明 | -| -------------- | ----------------------------- | -| Promise\ | 准备播放视频的Promise返回值。 | +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 销毁播放的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **示例:** ```js -videoPlayer.prepare().then(() => { - console.info('prepare success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.release().then(() => { + console.info('release success'); +}, (err) => { + console.error('release filed,error message is :' + err.message) +}) ``` -### play8+ +### getTrackDescription9+ -play(callback: AsyncCallback\): void; +getTrackDescription(callback: AsyncCallback\>): void -通过回调方式开始播放视频。 +通过回调方式获取音视频轨道信息,可以在prepared/playing/paused状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | 是 | 开始播放视频的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | +| callback | AsyncCallback> | 是 | 音视频轨道信息MediaDescription数组回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **示例:** ```js -videoPlayer.play((err) => { - if (err == null) { - console.info('play success!'); +avPlayer.getTrackDescription((error, arrList) => { + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); + } } else { - console.info('play fail!'); + console.log(`video getTrackDescription fail, error:${error}`); } }); ``` -### play8+ +### getTrackDescription9+ -play(): Promise\; +getTrackDescription(): Promise\> -通过Promise方式开始播放视频。 +通过Promise方式获取音频轨道信息,可以在prepared/playing/paused状态调用。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **返回值:** -| 类型 | 说明 | -| -------------- | ----------------------------- | -| Promise\ | 开始播放视频的Promise返回值。 | +| 类型 | 说明 | +| ------------------------------------------------------ | ------------------------------------------------- | +| Promise> | 音视频轨道信息MediaDescription数组Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **示例:** ```js -videoPlayer.play().then(() => { - console.info('play success'); +let arrayDescription; +avPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('video getTrackDescription fail'); + } }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.info(`video catchCallback, error:${error}`); }); +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} ``` -### pause8+ +### seek9+ -pause(callback: AsyncCallback\): void +seek(timeMs: number, mode?:SeekMode): void -通过回调方式暂停播放视频。 +跳转到指定播放位置,只能在prepared/playing/paused/complete状态调用,可以通过[seekDone事件](#seekDone_on)确认是否生效。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | 是 | 暂停播放视频的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, [duration](#avplayer_duration)]。 | +| mode | [SeekMode](#seekmode8) | 否 | 基于视频I帧的跳转模式,**仅在视频资源播放时设置**。 | **示例:** ```js -videoPlayer.pause((err) => { - if (err == null) { - console.info('pause success!'); - } else { - console.info('pause fail!'); - } -}); +let seekTime = 1000 +avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC) ``` -### pause8+ +### on('seekDone')9+ -pause(): Promise\ +on(type: 'seekDone', callback: Callback\): void -通过Promise方式暂停播放视频。 +监听seek生效的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**返回值:** +**参数:** -| 类型 | 说明 | -| -------------- | ----------------------------- | -| Promise\ | 暂停播放视频的Promise返回值。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | seek生效的事件回调类型,支持的事件:'seekDone',每次调用seek后都会回调此事件。 | +| callback | Callback\ | 是 | seek生效的事件回调方法,只会上报用户请求的time位置。
**视频播放:**[SeekMode](#seekmode8)会造成实际跳转位置与用户设置产生偏差,精准位置需要通过currentTime获取,事件回调的time仅代表完成用户某一次请求。 | **示例:** ```js -videoPlayer.pause().then(() => { - console.info('pause success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.on('seekDone', (seekDoneTime:number) => { + console.info('seekDone success,and seek time is:' + seekDoneTime) +}) ``` -### stop8+ +### off('seekDone')9+ -stop(callback: AsyncCallback\): void +off(type: 'seekDone'): void -通过回调方式停止播放视频。 +取消监听seek生效的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | 是 | 停止播放视频的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------------------------------------- | +| type | string | 是 | seek生效的事件回调类型,取消注册的事件:'seekDone'。 | **示例:** ```js -videoPlayer.stop((err) => { - if (err == null) { - console.info('stop success!'); - } else { - console.info('stop fail!'); - } -}); +avPlayer.off('seekDone') ``` -### stop8+ +### setSpeed9+ -stop(): Promise\ +setSpeed(speed: PlaybackSpeed): void -通过Promise方式停止播放视频。 +设置倍速模式,只能在prepared/playing/paused/complete状态调用,可以通过[speedDone事件](#speedDone_on)确认是否生效。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**返回值:** +**参数:** -| 类型 | 说明 | -| -------------- | ----------------------------- | -| Promise\ | 停止播放视频的Promise返回值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------------------------- | ---- | ------------------ | +| speed | [PlaybackSpeed](#playbackspeed8) | 是 | 指定播放倍速模式。 | **示例:** ```js -videoPlayer.stop().then(() => { - console.info('stop success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.setSpeed(media.AVPlayerSpeed.SPEED_FORWARD_2_00_X) ``` -### reset8+ +### on('speedDone')9+ -reset(callback: AsyncCallback\): void +on(type: 'speedDone', callback: Callback\): void -通过回调方式重置播放视频。 +监听setSpeed生效的事件 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | 是 | 切换播放视频的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | setSpeed生效的事件回调类型,支持的事件:'speedDone',每次调用setSpeed后都会回调此事件。 | +| callback | Callback\ | 是 | setSpeed生效的事件回调方法,上报生效的倍速模式,具体见[PlaybackSpeed](#playbackspeed8)。 | **示例:** ```js -videoPlayer.reset((err) => { - if (err == null) { - console.info('reset success!'); - } else { - console.info('reset fail!'); - } -}); +avPlayer.on('speedDone', (speed:number) => { + console.info('speedDone success,and speed value is:' + speed) +}) ``` -### reset8+ +### off('speedDone')9+ -reset(): Promise\ +off(type: 'speedDone'): void -通过Promise方式重置播放视频。 +取消监听setSpeed生效的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**返回值:** +**参数:** -| 类型 | 说明 | -| -------------- | ----------------------------- | -| Promise\ | 切换播放视频的Promise返回值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | --------------------------------------------------------- | +| type | string | 是 | setSpeed生效的事件回调类型,取消注册的事件:'speedDone'。 | **示例:** ```js -videoPlayer.reset().then(() => { - console.info('reset success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.off('speedDone') ``` -### seek8+ +### setBitrate9+ -seek(timeMs: number, callback: AsyncCallback\): void +setBitrate(bitrate: number): void -通过回调方式跳转到指定播放位置,默认跳转到指定时间点的下一个关键帧。 +选择要播放的指定比特率,仅对**HLS协议网络流**有效,只能在prepared/playing/paused/complete状态调用,可以通过[bitrateDone](#bitrateDone_on)事件确认是否生效。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | -| callback | AsyncCallback\ | 是 | 跳转到指定播放位置的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| bitrate | number | 是 | 指定比特率,可以通过[availableBitrates](#availableBitrates_on)事件获得当前HLS协议流可用的比特率,如果用户指定的比特率不在此列表中,则播放器将从可用比特率列表中选择最小和最接近的比特率。 | **示例:** ```js -let seekTime = 5000; -videoPlayer.seek(seekTime, (err, result) => { - if (err == null) { - console.info('seek success!'); - } else { - console.info('seek fail!'); - } -}); +let bitrate = 96000 +avPlayer.setBitrate(bitrate) ``` -### seek8+ +### on('bitrateDone')9+ -seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void +on(type: 'bitrateDone', callback: Callback\): void -通过回调方式跳转到指定播放位置。 +监听setBitrate生效的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | -| mode | [SeekMode](#seekmode8) | 是 | 跳转模式。 | -| callback | AsyncCallback\ | 是 | 跳转到指定播放位置的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | setBitrate生效的事件回调类型,支持的事件:'bitrateDone',每次调用setBitrate后都会回调此事件。 | +| callback | function | 是 | setBitrate生效的事件回调方法,上报生效的比特率。 | **示例:** ```js -import media from '@ohos.multimedia.media' -let seekTime = 5000; -videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err, result) => { - if (err == null) { - console.info('seek success!'); - } else { - console.info('seek fail!'); - } -}); +avPlayer.on('bitrateDone', (bitrate:number) => { + console.info('bitrateDone success,and bitrate value is:' + bitrate) +}) ``` -### seek8+ +### off('bitrateDone')9+ -seek(timeMs: number, mode?:SeekMode): Promise\ +off(type: 'bitrateDone'): void -通过Promise方式跳转到指定播放位置,如果没有设置mode则跳转到指定时间点的下一个关键帧。 +取消监听setBitrate生效的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---------------------- | ---- | ------------------------------------------------------------ | -| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | -| mode | [SeekMode](#seekmode8) | 否 | 跳转模式。 | - -**返回值:** - -| 类型 | 说明 | -| -------------- | ------------------------------------------- | -| Promise\ | 跳转到指定播放位置的Promise返回值,单位ms。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | setBitrate生效的事件回调类型,取消注册的事件:'bitrateDone'。 | **示例:** ```js -import media from '@ohos.multimedia.media' -let seekTime = 5000; -videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime表示seek完成后的时间点 - console.info('seek success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); - -videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => { - console.info('seek success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.off('bitrateDone') ``` -### setVolume8+ +### on('availableBitrates')9+ -setVolume(vol: number, callback: AsyncCallback\): void +on(type: 'availableBitrates', callback: (bitrates: Array\) => void): void -通过回调方式设置音量。 +监听HLS协议流可用的比特率列表,只会在切换prepared状态后上报。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | -| callback | AsyncCallback\ | 是 | 设置音量的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | HLS协议可用比特率上报事件回调类型,支持的事件:'availableBitrates',只会在prepared之后上报一次。 | +| callback | function | 是 | HLS协议可用比特率上报事件回调方法,使用数组存放支持的比特率。 | **示例:** ```js -let vol = 0.5; -videoPlayer.setVolume(vol, (err, result) => { - if (err == null) { - console.info('setVolume success!'); - } else { - console.info('setVolume fail!'); - } -}); +avPlayer.on('availableBitrates', (bitrates: Array) => { + console.info('availableBitrates success,and availableBitrates length is:' + bitrates.length) +}) ``` -### setVolume8+ +### off('availableBitrates')9+ -setVolume(vol: number): Promise\ +off(type: 'availableBitrates'): void -通过Promise方式设置音量。 +取消监听HLS协议流可用的比特率列表。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | -| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | - -**返回值:** - -| 类型 | 说明 | -| -------------- | ------------------------- | -| Promise\ | 设置音量的Promise返回值。 | +| type | string | 是 | HLS协议可用比特率上报事件回调类型,取消注册的事件:'availableBitrates'。 | **示例:** ```js -let vol = 0.5; -videoPlayer.setVolume(vol).then(() => { - console.info('setVolume success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.off('availableBitrates') ``` -### release8+ +### setVolume9+ -release(callback: AsyncCallback\): void +setVolume(volume: number): void -通过回调方式释放视频资源。 +设置媒体播放音量,只能在prepared/playing/paused/complete状态调用,可以通过[volumeChange事件](#volumeChange_on)确认是否生效。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | 是 | 释放视频资源的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| volume | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | **示例:** ```js -videoPlayer.release((err) => { - if (err == null) { - console.info('release success!'); - } else { - console.info('release fail!'); - } -}); +let volume = 1.0 +avPlayer.setVolume(volume) ``` -### release8+ +### on('volumeChange')9+ -release(): Promise\ +on(type: 'volumeChange', callback: Callback\): void -通过Promise方式释放视频资源。 +监听setVolume生效的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**返回值:** +**参数:** -| 类型 | 说明 | -| -------------- | ----------------------------- | -| Promise\ | 释放视频资源的Promise返回值。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | setVolume生效的事件回调类型,支持的事件:'volumeChange',每次调用setVolume后都会回调此事件。 | +| callback | function | 是 | setVolume生效的事件回调方法,上报生效的媒体音量。 | **示例:** ```js -videoPlayer.release().then(() => { - console.info('release success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.on('volumeChange', (vol:number) => { + console.info('volumeChange success,and new volume is :' + vol) +}) ``` -### getTrackDescription8+ +### off('volumeChange')9+ -getTrackDescription(callback: AsyncCallback>): void +off(type: 'volumeChange'): void -通过回调方式获取视频轨道信息。 +取消监听setVolume生效的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | -| callback | AsyncCallback> | 是 | 视频轨道信息MediaDescription数组回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | setVolume生效的事件回调类型,取消注册的事件:'availableBitrates'。 | **示例:** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('video key is ' + item); - console.info('video value is ' + property); - } -} - -videoPlayer.getTrackDescription((error, arrList) => { - if ((arrList) != null) { - for (let i = 0; i < arrList.length; i++) { - printfDescription(arrList[i]); - } - } else { - console.log(`video getTrackDescription fail, error:${error}`); - } -}); +avPlayer.off('volumeChange') ``` -### getTrackDescription8+ +### on('endOfStream')9+ -getTrackDescription(): Promise> +on(type: 'endOfStream', callback: Callback\): void -通过Promise方式获取视频轨道信息。 +监听资源播放至结尾的事件;如果用户设置**loop=1**,播放会跳转至开头重播;如果用户没有设置loop,会通过[stateChange](#stateChange_on)上报completed状态。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer -**返回值:** +**参数:** -| 类型 | 说明 | -| ------------------------------------------------------ | ----------------------------------------------- | -| Promise> | 视频轨道信息MediaDescription数组Promise返回值。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 资源播放至结尾的事件回调类型,支持的事件:'endOfStream',当播放至结尾时会上报此事件。 | +| callback | Callback\ | 是 | 资源播放至结尾的事件回调方法。 | **示例:** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('video key is ' + item); - console.info('video value is ' + property); - } -} - -let arrayDescription; -videoPlayer.getTrackDescription().then((arrList) => { - if (arrList != null) { - arrayDescription = arrList; - } else { - console.log('video getTrackDescription fail'); - } -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); -for (let i = 0; i < arrayDescription.length; i++) { - printfDescription(arrayDescription[i]); -} +avPlayer.on('endOfStream', () => { + console.info('endOfStream success') +}) ``` -### setSpeed8+ +### off('endOfStream')9+ -setSpeed(speed:number, callback: AsyncCallback\): void +off(type: 'endOfStream'): void -通过回调方式设置播放速度。 +取消监听资源播放至结尾的事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ---------------------------------------------------------- | -| speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 | -| callback | AsyncCallback\ | 是 | 设置播放速度的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 资源播放至结尾的事件回调类型,取消注册的事件:'endOfStream'。 | **示例:** ```js -import media from '@ohos.multimedia.media' -let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; - -videoPlayer.setSpeed(speed, (err, result) => { - if (err == null) { - console.info('setSpeed success!'); - } else { - console.info('setSpeed fail!'); - } -}); +avPlayer.off('endOfStream') ``` -### setSpeed8+ +### on('timeUpdate')9+ -setSpeed(speed:number): Promise\ +on(type: 'timeUpdate', callback: Callback\): void -通过Promise方式设置播放速度。 +监听资源播放当前时间,单位为毫秒(ms),用于刷新进度条当前位置,默认间隔1s时间上报,因用户操作(seek)产生的时间变化会立刻上报。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------------------------------------------- | -| speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | ------------------------------------------------------------ | -| Promise\ | 播放速度Promise返回值,具体见[PlaybackSpeed](#playbackspeed8)。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ---------------------------------------------- | +| type | string | 是 | 时间更新的回调类型,支持的事件:'timeUpdate'。 | +| callback | function | 是 | 当前时间。 | **示例:** ```js -import media from '@ohos.multimedia.media' -let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; - -videoPlayer.setSpeed(speed).then(() => { - console.info('setSpeed success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.on('timeUpdate', (time:number) => { + console.info('timeUpdate success,and new time is :' + time) +}) ``` -### on('playbackCompleted')8+ +### off('timeUpdate')9+ -on(type: 'playbackCompleted', callback: Callback\): void +off(type: 'timeUpdate'): void -开始监听视频播放完成事件。 +取消监听资源播放当前时间。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ----------------------------------------------------------- | -| type | string | 是 | 视频播放完成事件回调类型,支持的事件:'playbackCompleted'。 | -| callback | function | 是 | 视频播放完成事件回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------------------------------- | +| type | string | 是 | 时间更新的回调类型,取消注册的事件:'timeUpdate'。 | **示例:** ```js -videoPlayer.on('playbackCompleted', () => { - console.info('playbackCompleted success!'); -}); +avPlayer.off('timeUpdate') ``` -### on('bufferingUpdate')8+ +### on('durationUpdate')9+ -on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void +on(type: 'durationUpdate', callback: Callback\): void -开始监听视频缓存更新事件。仅网络播放支持该订阅事件。 +监听资源播放资源的时长,单位为毫秒(ms),用于刷新进度条长度,默认只在prepared上报一次,同时允许一些特殊码流刷新多次时长。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | -| callback | function | 是 | 视频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | -------------------------------------------------- | +| type | string | 是 | 时长更新的回调类型,支持的事件:'durationUpdate'。 | +| callback | function | 是 | 资源时长。 | **示例:** ```js -videoPlayer.on('bufferingUpdate', (infoType, value) => { - console.log('video bufferingInfo type: ' + infoType); - console.log('video bufferingInfo value: ' + value); -}); +avPlayer.on('durationUpdate', (duration) => { + console.info('durationUpdate success,new duration is :' + duration) +}) ``` -### on('startRenderFrame')8+ +### off('durationUpdate')9+ -on(type: 'startRenderFrame', callback: Callback\): void +off(type: 'durationUpdate'): void -开始监听视频播放首帧送显上报事件。 +取消监听资源播放资源的时长。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频播放首帧送显上报事件回调类型,支持的事件:'startRenderFrame'。 | -| callback | Callback\ | 是 | 视频播放首帧送显上报事件回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------ | +| type | string | 是 | 时长更新的回调类型,取消注册的事件:'durationUpdate'。 | **示例:** ```js -videoPlayer.on('startRenderFrame', () => { - console.info('startRenderFrame success!'); -}); +avPlayer.off('durationUpdate') ``` -### on('videoSizeChanged')8+ +### on('bufferingUpdate')9+ -on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void +on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void -开始监听视频播放宽高变化事件。 +订阅音视频缓存更新事件,仅网络播放支持该订阅事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频播放宽高变化事件回调类型,支持的事件:'videoSizeChanged'。 | -| callback | function | 是 | 视频播放宽高变化事件回调方法,width表示宽,height表示高。 | +| type | string | 是 | 播放缓存事件回调类型,支持的事件:'bufferingUpdate'。 | +| callback | function | 是 | 播放缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | **示例:** ```js -videoPlayer.on('videoSizeChanged', (width, height) => { - console.log('video width is: ' + width); - console.log('video height is: ' + height); -}); +avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { + console.info('bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value) +}) ``` -### on('error')8+ +### off('bufferingUpdate')9+ -on(type: 'error', callback: ErrorCallback): void +off(type: 'bufferingUpdate'): void -开始监听视频播放错误事件,当上报error错误事件后,用户需处理error事件,退出播放操作。 +取消监听音视频缓存更新事件。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':视频播放中发生错误,触发该事件。 | -| callback | ErrorCallback | 是 | 播放错误事件回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | --------------------------------------------------------- | +| type | string | 是 | 播放缓存事件回调类型,取消注册的事件:'bufferingUpdate'。 | **示例:** ```js -videoPlayer.on('error', (error) => { // 设置'error'事件回调 - console.info(`video error called, error: ${error}`); -}); -videoPlayer.url = 'fd://error'; //设置错误的播放地址,触发'error'事件 +avPlayer.off('bufferingUpdate') ``` -### on('availableBitratesCollect')9+ +### on('startRenderFrame')9+ -on(type: 'availableBitratesCollect', callback: (bitrates: Array\) => void): void +on(type: 'startRenderFrame', callback: Callback\): void -开始监听视频播放码率上报事件。 +订阅视频播放开始首帧渲染的更新事件,仅视频播放支持该订阅事件,该事件仅代表播放服务将第一帧画面送显示模块,实际效果依赖显示服务渲染性能。 -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 视频播放码率上报事件回调类型,支持的事件:'availableBitratesCollect',只在开始播放时候上报一次 | -| callback | function | 是 | 视频播放码率事件回调方法,使用数组存放支持的码率。 | +| type | string | 是 | 视频播放开始首帧渲染事件回调类型,支持的事件:'startRenderFrame'。 | +| callback | Callback\ | 是 | 视频播放开始首帧渲染事件回调方法。 | **示例:** ```js -videoPlayer.on('availableBitratesCollect', (bitrates) => { - for (let i = 0; i < bitrates.length; i++) { - console.info('case availableBitratesCollect bitrates: ' + bitrates[i]); //打印支持的码率 - } -}); +avPlayer.on('startRenderFrame', () => { + console.info('startRenderFrame success') +}) ``` -## VideoPlayState8+ +### off('startRenderFrame')9+ -视频播放的状态机,可通过state属性获取当前状态。 +off(type: 'startRenderFrame'): void -**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer +取消监听视频播放开始首帧渲染的更新事件。 -| 名称 | 类型 | 说明 | -| -------- | ------ | -------------- | -| idle | string | 视频播放空闲。 | -| prepared | string | 视频播放准备。 | -| playing | string | 视频正在播放。 | -| paused | string | 视频暂停播放。 | -| stopped | string | 视频播放停止。 | -| error | string | 错误状态。 | +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 视频播放开始首帧渲染事件回调类型,取消注册的事件:'startRenderFrame'。 | + +**示例:** + +```js +avPlayer.off('startRenderFrame') +``` + +### on('videoSizeChange')9+ + +on(type: 'videoSizeChange', callback: (width: number, height: number) => void): void + +监听视频播放宽高变化事件,仅视频播放支持该订阅事件,默认只在prepread状态上报一次,但HLS协议码流会在切换分辨率时上报; + +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 视频播放宽高变化事件回调类型,支持的事件:'videoSizeChange'。 | +| callback | function | 是 | 视频播放宽高变化事件回调方法,width表示宽,height表示高。 | + +**示例:** + +```js +avPlayer.on('videoSizeChange', (width: number, height: number) => { + console.info('videoSizeChange success,and width is:' + width + ', height is :' + height) +}) +``` + +### off('videoSizeChange')9+ + +off(type: 'videoSizeChange'): void + +取消监听视频播放宽高变化事件。 + +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 视频播放宽高变化事件回调类型,取消注册的事件:'videoSizeChange'。 | + +**示例:** + +```js +avPlayer.off('videoSizeChange') +``` + +### on('audioInterrupt')9+ + +on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void + +监听音频焦点变化事件,多个音视频资源同时播放时,会根据音频焦点模型[audio.InterruptMode](js-apis-audio.md#interruptmode9)触发此事件。 + +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | +| type | string | 是 | 音频焦点变化事件回调类型,支持的事件:'audioInterrupt'。 | +| callback | [audio.InterruptEvent9+](js-apis-audio.md#interruptevent9) | 是 | 音频焦点变化事件回调方法。 | + +**示例:** + +```js +avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { + console.info('audioInterrupt success,and InterruptEvent info is:' + info) +}) +``` + +### off('audioInterrupt')9+ + +off(type: 'audioInterrupt'): void + +取消监听音频焦点变化事件。 + +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 音频焦点变化事件回调类型,取消注册的事件:'audioInterrupt'。 | + +**示例:** + +```js +avPlayer.off('audioInterrupt') +``` + +## AVPlayerState9+ + +[AVPlayer](#avplayer9)的状态机,可通过state属性主动获取当前状态,也可通过监听[stateChange](#stateChange_on)事件上报当前状态,状态机之间的切换规则,可参考[AVPlayer播放器开发指导](../../media/avplayer-playback.md)。 + +**系统能力:** SystemCapability.Multimedia.Media.AVPlayer + +| 名称 | 类型 | 说明 | +| :-----------------------------: | :----: | :----------------------------------------------------------- | +| idle | string | 闲置状态,AVPlayer刚被创建[createAVPlayer()](#mediacreateavplayer9)或者调用了reset()方法之后,进入Idle状态。
首次创建createAVPlayer(),所有属性都为默认值。
调用reset()方法,url9+ 或 fdSrc9+属性会被重置,其他用户设置的属性将被保留。 | +| initialized | string | 资源初始化,在Idle 状态设置 url9+ 或 fdSrc9+属性,AVPlayer会进入initialized状态,此时可以配置窗口、音频等静态属性。 | +| prepared | string | 已准备状态,在initialized状态调用prepare()方法,AVPlayer会进入prepared状态,此时播放引擎的资源已准备就绪。 | +| playing | string | 正在播放状态,在prepared/paused/completed状态调用play()方法,AVPlayer会进入playing状态。 | +| paused | string | 暂停状态,在playing状态调用pause方法,AVPlayer会进入paused状态。 | +| completed | string | 播放至结尾状态,当媒体资源播放至结尾时,如果用户未设置循环播放(loop = 1),AVPlayer会进入completed状态,此时调用play()会进入playing状态和重播,调用stop()会进入stopped状态。 | +| stopped | string | 停止状态,在prepared/playing/paused/completed状态调用stop()方法,AVPlayer会进入stopped状态,此时播放引擎只会保留属性,但会释放内存资源,可以调用prepare()重新准备,也可以调用reset()重置,或者调用release()彻底销毁。 | +| released | string | 销毁状态,销毁与当前AVPlayer关联的播放引擎,无法再进行状态转换,调用release()方法后,会进入released状态,结束流程。 | +| error | string | 错误状态,当**播放引擎**发生**不可逆的错误**,详见[错误分类](#error_info),则会转换至当前状态,可以调用reset()重置,也可以调用release()销毁重建。
**注意:** 区分error状态和 [on('error')](#error_on) :
1、进入error状态时,会触发[on('error')](#error_on)监听事件,可以通过[on('error')](#error_on)事件获取详细错误信息;
2、处于error状态时,播放服务进入不可播控的状态,要求客户端设计容错机制,使用reset()重置或者release()销毁重建;
3、如果客户端收到[on('error')](#error_on),但未进入error状态:
原因1:客户端未按状态机调用API或传入参数错误,被AVPlayer拦截提醒,需要客户端调整代码逻辑;
原因2:播放过程发现码流问题,导致容器、解码短暂异常,不影响连续播放和播控操作的,不需要客户端设计容错机制。 | + +## AVFileDescriptor9+ + +音视频文件资源描述,一种特殊资源的播放方式,使用场景:应用中的音频资源被连续存储在同一个文件中,需要根据偏移量和长度进行播放。 + +**系统能力:** SystemCapability.Multimedia.Media.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| fd | number | 是 | 资源句柄,通过resourceManager.getRawFileDescriptor获取。 | +| offset | number | 是 | 资源偏移量,需要基于预置资源的信息输入,非法值会造成音视频资源解析错误。 | +| length | number | 是 | 资源长度,需要基于预置资源的信息输入,非法值会造成音视频资源解析错误。 | ## SeekMode8+ @@ -1557,10 +1638,10 @@ videoPlayer.on('availableBitratesCollect', (bitrates) => { **系统能力:** SystemCapability.Multimedia.Media.VideoPlayer -| 名称 | 值 | 说明 | -| ---------------------------- | ------ | ---------- | -| VIDEO_SCALE_TYPE_FIT | 0 | 视频拉伸至与窗口等大。 | -| VIDEO_SCALE_TYPE_FIT_CROP| 1 | 保持视频宽高比拉伸至填满窗口,内容可能会有裁剪。 | +| 名称 | 值 | 说明 | +| ------------------------- | ---- | ------------------------------------------------ | +| VIDEO_SCALE_TYPE_FIT | 0 | 视频拉伸至与窗口等大。 | +| VIDEO_SCALE_TYPE_FIT_CROP | 1 | 保持视频宽高比拉伸至填满窗口,内容可能会有裁剪。 | ## MediaDescription8+ @@ -1589,926 +1670,914 @@ audioPlayer.getTrackDescription((error, arrList) => { }); ``` -## AudioRecorder +## AVRecorder9+ -音频录制管理类,用于录制音频媒体。在调用AudioRecorder的方法前,需要先通过[createAudioRecorder()](#mediacreateaudiorecorder) 构建一个[AudioRecorder](#audiorecorder)实例。 +音视频录制管理类,用于音视频媒体录制。在调用AVRecorder的方法前,需要先通过createAVRecorder()构建一个AVRecorder实例。 -音频录制demo可参考:[音频录制开发指导](../../media/audio-recorder.md) +音视频录制demo可参考:[音视频录制开发指导](../../media/avrecorder.md) -### prepare +### 属性 -prepare(config: AudioRecorderConfig): void +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -录音准备。 +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------- | ------------------------------------ | ---- | ---- | ------------------ | +| state9+ | [AVRecorderState](#avrecorderstate9) | 是 | 否 | 音视频录制的状态。 | + +### prepare9+ + +prepare(config: AVRecorderConfig, callback: AsyncCallback\): void + +异步方式进行音视频录制的参数设置。通过注册回调函数获取返回值。 **需要权限:** ohos.permission.MICROPHONE -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +不涉及音频录制时,可以不需要获取ohos.permission.MICROPHONE权限。 + +使用相机视频录制还需要与相机模块配合,权限获取以及接口使用详见[相机管理](js-apis-camera.md)。 + +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| config | [AudioRecorderConfig](#audiorecorderconfig) | 是 | 配置录音的相关参数,包括音频输出URI、编码格式、采样率、声道数、输出格式等。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------- | ---- | ------------------------------------- | +| config | [AVRecorderConfig](#avrecorderconfig9) | 是 | 配置音视频录制的相关参数。 | +| callback | AsyncCallback\ | 是 | 异步音视频录制prepare方法的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------- | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operate not permit. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://1', // 文件需先由调用者创建,并给予适当的权限 - location : { latitude : 30, longitude : 130}, +let AVRecorderProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 } -audioRecorder.on('prepare', () => { //设置'prepare'事件回调 - console.log('prepare success'); -}); -audioRecorder.prepare(audioRecorderConfig); +let AVRecorderConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : AVRecorderProfile, + url : 'fd://', // 文件需先由调用者创建,赋予读写权限,将文件fd传给此参数,eg.fd://45 + rotation : 0, // 合理值0、90、180、270,非合理值prepare接口将报错 + location : { latitude : 30, longitude : 130 } +} + +AVRecorder.prepare(AVRecorderConfig, (err) => { + if (err == null) { + console.info('prepare success'); + } else { + console.info('prepare failed and error is ' + err.message); + } +}) ``` +### prepare9+ -### start +prepare(config: AVRecorderConfig): Promise\ -start(): void +异步方式进行音视频录制的参数设置。通过Promise获取返回值。 -开始录制,需在[prepare](#audiorecorder_on)事件成功触发后,才能调用start方法。 +**需要权限:** ohos.permission.MICROPHONE -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +不涉及音频录制时,可以不需要获ohos.permission.MICROPHONE权限。 -**示例:** +使用相机视频录制还需要与相机模块配合,权限获取以及接口使用详见[相机管理](js-apis-camera.md)。 -```js -audioRecorder.on('start', () => { //设置'start'事件回调 - console.log('audio recorder start success'); -}); -audioRecorder.start(); -``` +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -### pause +**参数:** -pause():void +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------------------------------- | ---- | -------------------------- | +| config | [AVRecorderConfig](#avrecorderconfig9) | 是 | 配置音视频录制的相关参数。 | -暂停录制,需要在[start](#audiorecorder_on)事件成功触发后,才能调用pause方法。 +**返回值:** -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +| 类型 | 说明 | +| -------------- | ------------------------------------------ | +| Promise\ | 异步音视频录制prepare方法的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operate not permit. Return by promise. | +| 5400105 | Service died. Return by promise. | **示例:** ```js -audioRecorder.on('pause', () => { //设置'pause'事件回调 - console.log('audio recorder pause success'); +let AVRecorderProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} +let AVRecorderConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : AVRecorderProfile, + url : 'fd://', // 文件需先由调用者创建,赋予读写权限,将文件fd传给此参数,eg.fd://45 + rotation : 0, // 合理值0、90、180、270,非合理值prepare接口报错 + location : { latitude : 30, longitude : 130 } +} + +AVRecorder.prepare(AVRecorderConfig).then(() => { + console.info('prepare success'); +}).catch((err) => { + console.info('prepare failed and catch error is ' + err.message); }); -audioRecorder.pause(); + ``` -### resume +### getInputSurface9+ -resume():void +getInputSurface(callback: AsyncCallback\): void -恢复录制,需要在[pause](#audiorecorder_on)事件成功触发后,才能调用resume方法。 +异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的视频数据。 -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +应当注意,填入的视频数据需要携带时间戳(单位ns)和buffersize。时间戳的起始时间请以系统启动时间为基准。 -**示例:** +需在prepare()事件成功触发后,才能调用getInputSurface()方法。 -```js -audioRecorder.on('resume', () => { //设置'resume'事件回调 - console.log('audio recorder resume success'); -}); -audioRecorder.resume(); -``` +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -### stop +**参数:** -stop(): void +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | --------------------------- | +| callback | AsyncCallback\ | 是 | 异步获得surface的回调方法。 | -停止录音。 +**错误码:** -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -audioRecorder.on('stop', () => { //设置'stop'事件回调 - console.log('audio recorder stop success'); +let surfaceID = null; // 该surfaceID用于传递给相机接口创造videoOutput + +AVRecorder.getInputSurface((err, surfaceId) => { + if (err == null) { + console.info('getInputSurface success'); + surfaceID = surfaceId; + } else { + console.info('getInputSurface failed and error is ' + err.message); + } }); -audioRecorder.stop(); + +// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); + ``` -### release +### getInputSurface9+ -release(): void +getInputSurface(): Promise\ -释放录音资源。 +异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的视频数据。 -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +应当注意,填入的视频数据需要携带时间戳(单位ns)和buffersize。时间戳的起始时间请以系统启动时间为基准。 -**示例:** +需在prepare()事件成功触发后,才能调用getInputSurface方法。 -```js -audioRecorder.on('release', () => { //设置'release'事件回调 - console.log('audio recorder release success'); -}); -audioRecorder.release(); -audioRecorder = undefined; -``` +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -### reset +**返回值:** -reset(): void +| 类型 | 说明 | +| ---------------- | -------------------------------- | +| Promise\ | 异步获得surface的Promise返回值。 | -重置录音。 +**错误码:** -进行重置录音之前,需要先调用[stop()](#audiorecorder_stop)停止录音。重置录音之后,需要调用[prepare()](#audiorecorder_prepare)设置录音参数项,才能再次进行录音。 +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **示例:** ```js -audioRecorder.on('reset', () => { //设置'reset'事件回调 - console.log('audio recorder reset success'); +let surfaceID = null; // 该surfaceID用于传递给相机接口创造videoOutput + +AVRecorder.getInputSurface().then((surfaceId) => { + console.info('getInputSurface success'); + surfaceID = surfaceId; +}).catch((err) => { + console.info('getInputSurface failed and catch error is ' + err.message); }); -audioRecorder.reset(); + +// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); ``` -### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset') +### start9+ -on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void +start(callback: AsyncCallback\): void -开始订阅音频录制事件。 +异步方式开始视频录制。通过注册回调函数获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +纯音频录制需在prepare()事件成功触发后,才能调用start方法。纯视频录制,音视频录制需在getInputSurface()事件成功触发后,才能调用start方法。 + +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 录制事件回调类型,支持的事件包括:'prepare' \| 'start' \| 'pause' \| ’resume‘ \| 'stop' \| 'release' \| 'reset'。
- 'prepare' :完成[prepare](#audiorecorder_prepare)调用,音频录制参数设置完成,触发该事件。
- 'start' :完成[start](#audiorecorder_start)调用,音频录制开始,触发该事件。
- 'pause': 完成[pause](#audiorecorder_pause)调用,音频暂停录制,触发该事件。
- 'resume': 完成[resume](#audiorecorder_resume)调用,音频恢复录制,触发该事件。
- 'stop' :完成[stop](#audiorecorder_stop)调用,音频停止录制,触发该事件。
- 'release' :完成[release](#audiorecorder_release)调用,音频释放录制资源,触发该事件。
- 'reset':完成[reset](#audiorecorder_reset)调用,音频重置为初始状态,触发该事件。 | -| callback | ()=>void | 是 | 录制事件回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步开始视频录制的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -let audioRecorder = media.createAudioRecorder(); // 创建一个音频录制实例 -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 - location : { latitude : 30, longitude : 130}, -} -audioRecorder.on('error', (error) => { // 设置'error'事件回调 - console.info(`audio error called, error: ${error}`); -}); -audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 - console.log('prepare success'); - audioRecorder.start(); // 开始录制,并触发'start'事件回调 -}); -audioRecorder.on('start', () => { // 设置'start'事件回调 - console.log('audio recorder start success'); -}); -audioRecorder.on('pause', () => { // 设置'pause'事件回调 - console.log('audio recorder pause success'); -}); -audioRecorder.on('resume', () => { // 设置'resume'事件回调 - console.log('audio recorder resume success'); -}); -audioRecorder.on('stop', () => { // 设置'stop'事件回调 - console.log('audio recorder stop success'); -}); -audioRecorder.on('release', () => { // 设置'release'事件回调 - console.log('audio recorder release success'); -}); -audioRecorder.on('reset', () => { // 设置'reset'事件回调 - console.log('audio recorder reset success'); +AVRecorder.start((err) => { + if (err == null) { + console.info('start AVRecorder success'); + } else { + console.info('start AVRecorder failed and error is ' + err.message); + } }); -audioRecorder.prepare(audioRecorderConfig) // 设置录制参数 ,并触发'prepare'事件回调 ``` -### on('error') +### start9+ -on(type: 'error', callback: ErrorCallback): void +start(): Promise\ -开始订阅音频录制错误事件,当上报error错误事件后,用户需处理error事件,退出录制操作。 +异步方式开始视频录制。通过Promise获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +纯音频录制需在prepare()事件成功触发后,才能调用start方法。纯视频录制,音视频录制需在getInputSurface()事件成功触发后,才能调用start方法。 -**参数:** +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':音频录制过程中发生错误,触发该事件。 | -| callback | ErrorCallback | 是 | 录制错误事件回调方法。 | +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步开始视频录制方法的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **示例:** ```js -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 - location : { latitude : 30, longitude : 130}, -} -audioRecorder.on('error', (error) => { // 设置'error'事件回调 - console.info(`audio error called, error: ${error}`); +AVRecorder.start().then(() => { + console.info('start AVRecorder success'); +}).catch((err) => { + console.info('start AVRecorder failed and catch error is ' + err.message); }); -audioRecorder.prepare(audioRecorderConfig); // prepare不设置参数,触发'error'事件 ``` -## AudioRecorderConfig +### pause9+ -表示音频的录音配置。 +pause(callback: AsyncCallback\): void -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +异步方式暂停视频录制。通过注册回调函数获取返回值。 -| 名称 | 类型 | 必填 | 说明 | -| --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| audioEncoder(deprecated) | [AudioEncoder](#audioencoder) | 否 | 音频编码格式,默认设置为AAC_LC。
**说明:** 从API Version 8 开始废弃,建议使用audioEncoderMime替代。 | -| audioEncodeBitRate | number | 否 | 音频编码比特率,默认值为48000。 | -| audioSampleRate | number | 否 | 音频采集采样率,默认值为48000。 | -| numberOfChannels | number | 否 | 音频采集声道数,默认值为2。 | -| format(deprecated) | [AudioOutputFormat](#audiooutputformat) | 否 | 音频输出封装格式,默认设置为MPEG_4。
**说明:** 从API Version 8 开始废弃,建议使用fileFormat替代。 | -| location | [Location](#location) | 否 | 音频采集的地理位置。 | -| uri | string | 是 | 音频输出URI:fd://xx (fd number)
![](figures/zh-cn_image_url.png)
文件需要由调用者创建,并赋予适当的权限。 | -| audioEncoderMime8+ | [CodecMimeType](#codecmimetype8) | 否 | 音频编码格式。 | -| fileFormat8+ | [ContainerFormatType](#containerformattype8) | 否 | 音频编码格式。 | +需要start()事件成功触发后,才能调用pause方法,可以通过调用resume()接口来恢复录制。 -## AudioEncoder(deprecated) +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -> **说明:** -> 从 API Version 8 开始废弃,建议使用[CodecMimeType](#codecmimetype8)替代。 +**参数:** -表示音频编码格式的枚举。 +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | --------------------------- | +| callback | AsyncCallback\ | 是 | 异步获得surface的回调方法。 | -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +**错误码:** -| 名称 | 值 | 说明 | -| ------- | ---- | ------------------------------------------------------------ | -| DEFAULT | 0 | 默认编码格式。
仅做接口定义,暂不支持使用。 | -| AMR_NB | 1 | AMR-NB(Adaptive Multi Rate-Narrow Band Speech Codec) 编码格式。
仅做接口定义,暂不支持使用。 | -| AMR_WB | 2 | AMR-WB(Adaptive Multi Rate-Wide Band Speech Codec) 编码格式。
仅做接口定义,暂不支持使用。 | -| AAC_LC | 3 | AAC-LC(Advanced Audio Coding Low Complexity)编码格式。 | -| HE_AAC | 4 | HE_AAC(High-Efficiency Advanced Audio Coding)编码格式。
仅做接口定义,暂不支持使用。 | +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 +| 错误码ID | 错误信息 | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | -## AudioOutputFormat(deprecated) +**示例:** -> **说明:** -> 从 API Version 8 开始废弃,建议使用[ContainerFormatType](#containerformattype8)替代。 +```js +AVRecorder.pause((err) => { + if (err == null) { + console.info('pause AVRecorder success'); + } else { + console.info('pause AVRecorder failed and error is ' + err.message); + } +}); +``` -表示音频封装格式的枚举。 +### pause9+ -**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder +pause(): Promise\ -| 名称 | 值 | 说明 | -| -------- | ---- | ------------------------------------------------------------ | -| DEFAULT | 0 | 默认封装格式。
仅做接口定义,暂不支持使用。 | -| MPEG_4 | 2 | 封装为MPEG-4格式。 | -| AMR_NB | 3 | 封装为AMR_NB格式。
仅做接口定义,暂不支持使用。 | -| AMR_WB | 4 | 封装为AMR_WB格式。
仅做接口定义,暂不支持使用。 | -| AAC_ADTS | 6 | 封装为ADTS(Audio Data Transport Stream)格式,是AAC音频的传输流格式。 | +异步方式暂停视频录制。通过Promise获取返回值。 -## VideoRecorder9+ +需要start()事件成功触发后,才能调用pause方法,可以通过调用resume()接口来恢复录制。 -视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorder()](#mediacreatevideorecorder9)构建一个[VideoRecorder](#videorecorder9)实例。 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -视频录制demo可参考:[视频录制开发指导](../../media/video-recorder.md) +**返回值:** -### 属性 +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步暂停视频录制方法的Promise返回值。 | -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**错误码:** -**系统接口:** 该接口为系统接口 +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------------------ | -------------------------------------- | ---- | ---- | ---------------- | -| state9+ | [VideoRecordState](#videorecordstate9) | 是 | 否 | 视频录制的状态。 | +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | -### prepare9+ +**示例:** -prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; +```js +AVRecorder.pause().then(() => { + console.info('pause AVRecorder success'); +}).catch((err) => { + console.info('pause AVRecorder failed and catch error is ' + err.message); +}); +``` -异步方式进行视频录制的参数设置。通过注册回调函数获取返回值。 +### resume9+ -**需要权限:** ohos.permission.MICROPHONE +resume(callback: AsyncCallback\): void -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +异步方式恢复视频录制。通过注册回调函数获取返回值。 -**系统接口:** 该接口为系统接口 +需要在pause()事件成功触发后,才能调用resume方法。 + +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------------- | ---- | ----------------------------------- | -| config | [VideoRecorderConfig](#videorecorderconfig9) | 是 | 配置视频录制的相关参数。 | -| callback | AsyncCallback\ | 是 | 异步视频录制prepare方法的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步恢复视频录制的回调方法。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ------------------------------------------ | -| 201 | Permission denied. Return by callback. | -| 401 | Parameter error. Return by callback. | -| 5400102 | Operation not allowed. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 错误码ID | 错误信息 | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} - -let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// asyncallback -videoRecorder.prepare(videoConfig, (err) => { +AVRecorder.resume((err) => { if (err == null) { - console.info('prepare success'); + console.info('resume AVRecorder success'); } else { - console.info('prepare failed and error is ' + err.message); + console.info('resume AVRecorder failed and error is ' + err.message); } -}) +}); ``` -### prepare9+ - -prepare(config: VideoRecorderConfig): Promise\; - -异步方式进行视频录制的参数设置。通过Promise获取返回值。 - -**需要权限:** ohos.permission.MICROPHONE +### resume9+ -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +resume(): Promise\ -**系统接口:** 该接口为系统接口 +异步方式恢复视频录制。通过Promise获取返回值。 -**参数:** +需要在pause()事件成功触发后,才能调用resume方法。 -| 参数名 | 类型 | 必填 | 说明 | -| ------ | -------------------------------------------- | ---- | ------------------------ | -| config | [VideoRecorderConfig](#videorecorderconfig9) | 是 | 配置视频录制的相关参数。 | +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **返回值:** -| 类型 | 说明 | -| -------------- | ---------------------------------------- | -| Promise\ | 异步视频录制prepare方法的Promise返回值。 | +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步恢复视频录制方法的Promise返回值。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ----------------------------------------- | -| 201 | Permission denied. Return by promise. | -| 401 | Parameter error. Return by promise. | -| 5400102 | Operation not allowed. Return by promise. | -| 5400105 | Service died. Return by promise. | +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **示例:** ```js -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} - -let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// promise -videoRecorder.prepare(videoConfig).then(() => { - console.info('prepare success'); +AVRecorder.resume().then(() => { + console.info('resume AVRecorder success'); }).catch((err) => { - console.info('prepare failed and catch error is ' + err.message); + console.info('resume AVRecorder failed and catch error is ' + err.message); }); ``` -### getInputSurface9+ - -getInputSurface(callback: AsyncCallback\): void; +### stop9+ -异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。 +stop(callback: AsyncCallback\): void -应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。 +异步方式停止视频录制。通过注册回调函数获取返回值。 -只能在[prepare()](#videorecorder_prepare1)接口调用后调用。 +需要在start()或pause()事件成功触发后,才能调用stop方法。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +纯音频录制时,需要重新调用prepare()接口才能重新录制。纯视频录制,音视频录制时,需要重新调用prepare()和getInputSurface()接口才能重新录制。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | --------------------------- | -| callback | AsyncCallback\ | 是 | 异步获得surface的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步停止视频录制的回调方法。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 错误码ID | 错误信息 | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -// asyncallback -let surfaceID = null; // 传递给外界的surfaceID -videoRecorder.getInputSurface((err, surfaceId) => { +AVRecorder.stop((err) => { if (err == null) { - console.info('getInputSurface success'); - surfaceID = surfaceId; + console.info('stop AVRecorder success'); } else { - console.info('getInputSurface failed and error is ' + err.message); + console.info('stop AVRecorder failed and error is ' + err.message); } }); ``` -### getInputSurface9+ +### stop9+ -getInputSurface(): Promise\; - - 异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。 +stop(): Promise\ -应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。 +异步方式停止视频录制。通过Promise获取返回值。 -只能在[prepare()](#videorecorder_prepare1)接口调用后调用。 +需要在start()或pause()事件成功触发后,才能调用stop方法。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +纯音频录制时,需要重新调用prepare()接口才能重新录制。纯视频录制,音视频录制时,需要重新调用prepare()和getInputSurface()接口才能重新录制。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **返回值:** -| 类型 | 说明 | -| ---------------- | -------------------------------- | -| Promise\ | 异步获得surface的Promise返回值。 | +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步停止视频录制方法的Promise返回值。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **示例:** ```js -// promise -let surfaceID = null; // 传递给外界的surfaceID -videoRecorder.getInputSurface().then((surfaceId) => { - console.info('getInputSurface success'); - surfaceID = surfaceId; +AVRecorder.stop().then(() => { + console.info('stop AVRecorder success'); }).catch((err) => { - console.info('getInputSurface failed and catch error is ' + err.message); + console.info('stop AVRecorder failed and catch error is ' + err.message); }); ``` -### start9+ - -start(callback: AsyncCallback\): void; +### reset9+ -异步方式开始视频录制。通过注册回调函数获取返回值。 +reset(callback: AsyncCallback\): void -在[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)后调用,需要依赖数据源先给surface传递数据。 +异步方式重置音视频录制。通过注册回调函数获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +纯音频录制时,需要重新调用prepare()接口才能重新录制。纯视频录制,音视频录制时,需要重新调用prepare()和getInputSurface()接口才能重新录制。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步开始视频录制的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\ | 是 | 异步重置音视频录制的回调方法。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -// asyncallback -videoRecorder.start((err) => { +AVRecorder.reset((err) => { if (err == null) { - console.info('start videorecorder success'); + console.info('reset AVRecorder success'); } else { - console.info('start videorecorder failed and error is ' + err.message); + console.info('reset AVRecorder failed and error is ' + err.message); } }); ``` -### start9+ - -start(): Promise\; +### reset9+ -异步方式开始视频录制。通过Promise获取返回值。 +reset(): Promise\ -在[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)后调用,需要依赖数据源先给surface传递数据。 +异步方式重置音视频录制。通过Promise获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +纯音频录制时,需要重新调用prepare()接口才能重新录制。纯视频录制,音视频录制时,需要重新调用prepare()和getInputSurface()接口才能重新录制。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------- | -| Promise\ | 异步开始视频录制方法的Promise返回值。 | +| 类型 | 说明 | +| -------------- | --------------------------------------- | +| Promise\ | 异步重置音视频录制方法的Promise返回值。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| 错误码ID | 错误信息 | +| -------- | -------------------------------- | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **示例:** ```js -// promise -videoRecorder.start().then(() => { - console.info('start videorecorder success'); +AVRecorder.reset().then(() => { + console.info('reset AVRecorder success'); }).catch((err) => { - console.info('start videorecorder failed and catch error is ' + err.message); + console.info('reset AVRecorder failed and catch error is ' + err.message); }); ``` -### pause9+ - -pause(callback: AsyncCallback\): void; +### release9+ -异步方式暂停视频录制。通过注册回调函数获取返回值。 +release(callback: AsyncCallback\): void -在[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。 +异步方式释放音视频录制资源。通过注册回调函数获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +释放音视频录制资源之后,该AVRecorder实例不能再进行任何操作。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步暂停视频录制的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 异步释放音视频录制资源的回调方法。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | **示例:** ```js -// asyncallback -videoRecorder.pause((err) => { +AVRecorder.release((err) => { if (err == null) { - console.info('pause videorecorder success'); + console.info('release AVRecorder success'); } else { - console.info('pause videorecorder failed and error is ' + err.message); + console.info('release AVRecorder failed and error is ' + err.message); } }); ``` -### pause9+ - -pause(): Promise\; +### release9+ -异步方式暂停视频录制。通过Promise获取返回值。 +release(): Promise\ -在[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。 +异步方式释放音视频录制资源。通过Promise获取返回值。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +释放音视频录制资源之后,该AVRecorder实例不能再进行任何操作。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------- | -| Promise\ | 异步暂停视频录制方法的Promise返回值。 | +| 类型 | 说明 | +| -------------- | ------------------------------------------- | +| Promise\ | 异步释放音视频录制资源方法的Promise返回值。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | **示例:** ```js -// promise -videoRecorder.pause().then(() => { - console.info('pause videorecorder success'); +AVRecorder.release().then(() => { + console.info('release AVRecorder success'); }).catch((err) => { - console.info('pause videorecorder failed and catch error is ' + err.message); + console.info('release AVRecorder failed and catch error is ' + err.message); }); ``` -### resume9+ - -resume(callback: AsyncCallback\): void; +### on('stateChange')9+ -异步方式恢复视频录制。通过注册回调函数获取返回值。 +on(type: 'stateChange', callback: (state: AVRecorderState, reason: StateChangeReason) => void): void -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +订阅录制状态机AVRecorderState切换的事件,当 AVRecorderState状态机发生变化时,会通过订阅的回调方法通知用户。用户只能订阅一个状态机切换事件的回调方法,当用户重复订阅时,以最后一次订阅的回调接口为准。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步恢复视频录制的回调方法。 | - -**错误码:** - -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) - -| 错误码ID | 错误信息 | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 状态机切换事件回调类型,支持的事件:'stateChange',用户操作和系统都会触发此事件。 | +| callback | function | 是 | 状态机切换事件回调方法:
state: [AVRecorderState](#avrecorderstate9),表示当前播放状态 ;
reason: [StateChangeReason](#statechangereason9),表示当前播放状态的切换原因。 | **示例:** ```js -// asyncallback -videoRecorder.resume((err) => { - if (err == null) { - console.info('resume videorecorder success'); - } else { - console.info('resume videorecorder failed and error is ' + err.message); +AVRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); } }); ``` -### resume9+ - -resume(): Promise\; - -异步方式恢复视频录制。通过Promise获取返回值。 - -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder - -**系统接口:** 该接口为系统接口 +### off('stateChange')9+ -**返回值:** +off(type: 'stateChange'): void -| 类型 | 说明 | -| -------------- | ------------------------------------- | -| Promise\ | 异步恢复视频录制方法的Promise返回值。 | +取消订阅播放状态机[AVRecorderState](#avrecorderstate9)切换的事件。 -**错误码:** +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +**参数:** -| 错误码ID | 错误信息 | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 状态机切换事件回调类型,支持的事件:'stateChange',用户操作和系统都会触发此事件。 | **示例:** ```js -// promise -videoRecorder.resume().then(() => { - console.info('resume videorecorder success'); -}).catch((err) => { - console.info('resume videorecorder failed and catch error is ' + err.message); -}); +AVRecorder.off('stateChange'); ``` -### stop9+ - -stop(callback: AsyncCallback\): void; +### on('error')9+ -异步方式停止视频录制。通过注册回调函数获取返回值。 +on(type: 'error', callback: ErrorCallback): void -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 +订阅AVRecorder的错误事件,该事件仅用于错误提示,不需要用户停止播控动作。如果此时[AVRecorderState](#avrecorderstate9)也切至error状态,用户需要通过reset()或者release()退出录制操作。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +用户只能订阅一个错误事件的回调方法,当用户重复订阅时,以最后一次订阅的回调接口为准。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步停止视频录制的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':录制过程中发生错误,触发该事件。 | +| callback | ErrorCallback | 是 | 录制错误事件回调方法。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -// asyncallback -videoRecorder.stop((err) => { - if (err == null) { - console.info('stop videorecorder success'); - } else { - console.info('stop videorecorder failed and error is ' + err.message); - } +AVRecorder.on('error', (err) => { + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); }); ``` -### stop9+ - -stop(): Promise\; - -异步方式停止视频录制。通过Promise获取返回值。 +### off('error')9+ -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 +off(type: 'error'): void -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +取消订阅录制错误事件,取消后不再接收到AVRecorder的错误事件。 -**系统接口:** 该接口为系统接口 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -**返回值:** +**参数:** -| 类型 | 说明 | -| -------------- | ------------------------------------- | -| Promise\ | 异步停止视频录制方法的Promise返回值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':录制过程中发生错误,触发该事件。 | **错误码:** -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md)。 -| 错误码ID | 错误信息 | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -// promise -videoRecorder.stop().then(() => { - console.info('stop videorecorder success'); -}).catch((err) => { - console.info('stop videorecorder failed and catch error is ' + err.message); -}); +AVRecorder.off('error'); ``` -### release9+ +## AVRecorderState9+ -release(callback: AsyncCallback\): void; +音视频录制的状态机。可通过state属性获取当前状态。 -异步方式释放视频录制资源。通过注册回调函数获取返回值。 +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +| 名称 | 类型 | 说明 | +| -------- | ------ | ------------------------------------------------------------ | +| idle | string | 闲置状态。此时可以调用[prepare()](#avrecorder_prepare)方法设置录制参数,进入prepared状态。AVRecorder刚被创建,或者在任何非released状态下调用[reset()](#avrecorder_reset)方法,均进入idle状态。 | +| prepared | string | 参数设置完成。此时可以调用[start()](#avrecorder_start)方法开始录制,进入started状态。 | +| started | string | 正在录制。此时可以调用[pause()](#avrecorder_pause)方法暂停录制,进入paused状态。也可以调用[stop()](#avrecorder_stop)方法结束录制,进入stopped状态。 | +| paused | string | 录制暂停。此时可以调用[resume()](#avrecorder_resume)方法继续录制,进入started状态。也可以调用[stop()](#avrecorder_stop)方法结束录制,进入stopped状态。 | +| stopped | string | 录制停止。此时可以调用[prepare()](#avrecorder_prepare)方法设置录制参数,重新进入prepared状态。 | +| released | string | 录制资源释放。此时不能再进行任何操作。在任何其他状态下,均可以通过调用[release()](#avrecorder_release)方法进入released状态。 | +| error | string | 错误状态。当AVRecorder实例发生不可逆错误,会转换至当前状态。切换至error状态时会伴随[on('error')事件](#avrecorder_onerror),该事件会上报详细错误原因。在error状态时,用户需要调用[reset()](#avrecorder_reset)方法重置AVRecorder实例,或者调用[release()](#avrecorder_release)方法释放资源。 | -**系统接口:** 该接口为系统接口 +## AVRecorderConfig9+ -**参数:** +表示音视频录制的参数设置。 -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | 是 | 异步释放视频录制资源的回调方法。 | +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -**错误码:** +| 名称 | 类型 | 必填 | 说明 | +| --------------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| audioSourceType | [AudioSourceType](#audiosourcetype9) | 否 | 选择录制的音频源类型。选择音频录制时必填。 | +| videoSourceType | [VideoSourceType](#videosourcetype9) | 否 | 选择录制的视频源类型。选择视频录制时必填。 | +| profile | [AVRecorderProfile](#avrecorderprofile9) | 是 | 录制的profile,必要参数。 | +| url | string | 是 | 录制输出URL:fd://xx (fd number) ![img](figures/zh-cn_image_url.png),必要参数。 | +| rotation | number | 否 | 录制的视频旋转角度,仅支持0,90,180,270。 | +| location | [Location](#location) | 否 | 录制的地理位置。 | -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +通过audioSourceType和videoSourceType区分纯音频录制、纯视频录制或音视频录制。纯音频录制时,仅需要设置audioSourceType;纯视频录制时,仅需要设置videoSourceType;音视频录制时,audioSourceType和videoSourceType均需要设置。 -| 错误码ID | 错误信息 | -| -------- | --------------------------------- | -| 5400105 | Service died. Return by callback. | +## AVRecorderProfile9+ -**示例:** +音视频录制的配置文件。 -```js -// asyncallback -videoRecorder.release((err) => { - if (err == null) { - console.info('release videorecorder success'); - } else { - console.info('release videorecorder failed and error is ' + err.message); - } -}); -``` +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -### release9+ +| 名称 | 类型 | 必填 | 说明 | +| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioBitrate | number | 否 | 音频编码比特率,选择音频录制时必填。 | +| audioChannels | number | 否 | 音频采集声道数,选择音频录制时必填。 | +| audioCodec | [CodecMimeType](#codecmimetype8) | 否 | 音频编码格式,选择音频录制时必填。当前仅支持AUDIO_AAC。 | +| audioSampleRate | number | 否 | 音频采样率,选择音频录制时必填。 | +| fileFormat | [ContainerFormatType](#containerformattype8) | 是 | 文件的容器格式,必要参数。 | +| videoBitrate | number | 否 | 视频编码比特率,选择视频录制时必填。 | +| videoCodec | [CodecMimeType](#codecmimetype8) | 否 | 视频编码格式,选择视频录制时必填。当前仅支持VIDEO_AVC和VIDEO_MPEG4。 | +| videoFrameWidth | number | 否 | 视频帧的宽,选择视频录制时必填。 | +| videoFrameHeight | number | 否 | 视频帧的高,选择视频录制时必填。 | +| videoFrameRate | number | 否 | 视频帧率,选择视频录制时必填。 | -release(): Promise\; +## AudioSourceType9+ -异步方式释放视频录制资源。通过Promise获取返回值。 +表示视频录制中音频源类型的枚举。 -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -**系统接口:** 该接口为系统接口 +| 名称 | 值 | 说明 | +| ------------------------- | ---- | ---------------------- | +| AUDIO_SOURCE_TYPE_DEFAULT | 0 | 默认的音频输入源类型。 | +| AUDIO_SOURCE_TYPE_MIC | 1 | 表示MIC的音频输入源。 | -**返回值:** +## VideoSourceType9+ -| 类型 | 说明 | -| -------------- | ----------------------------------------- | -| Promise\ | 异步释放视频录制资源方法的Promise返回值。 | +表示视频录制中视频源类型的枚举。 -**错误码:** +**系统能力:** SystemCapability.Multimedia.Media.AVRecorder -以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | ------------------------------- | +| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | 输入surface中携带的是raw data。 | +| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | 输入surface中携带的是ES data。 | -| 错误码ID | 错误信息 | -| -------- | --------------------------------- | -| 5400105 | Service died. Return by callback. | +## ContainerFormatType8+ -**示例:** +表示容器格式类型的枚举,缩写为CFT。 -```js -// promise -videoRecorder.release().then(() => { - console.info('release videorecorder success'); -}).catch((err) => { - console.info('release videorecorder failed and catch error is ' + err.message); -}); -``` +**系统能力:** SystemCapability.Multimedia.Media.Core -### reset9+ +| 名称 | 值 | 说明 | +| ----------- | ----- | --------------------- | +| CFT_MPEG_4 | 'mp4' | 视频的容器格式,MP4。 | +| CFT_MPEG_4A | 'm4a' | 音频的容器格式,M4A。 | -reset(callback: AsyncCallback\): void; +## Location -异步方式重置视频录制。通过注册回调函数获取返回值。 +视频录制的地理位置。 -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 +**系统能力:** SystemCapability.Multimedia.Media.Core + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------------- | +| latitude | number | 是 | 地理位置的纬度。 | +| longitude | number | 是 | 地理位置的经度。 | + +## VideoRecorder9+ + +> **说明:** +> AVRecorder9+发布后停止维护,建议使用[AVRecorder](#avrecorder9)替代。 + +视频录制管理类,用于录制视频媒体。在调用VideoRecorder的方法前,需要先通过[createVideoRecorder()](#mediacreatevideorecorder9)构建一个[VideoRecorder](#videorecorder9)实例。 + +视频录制demo可参考:[视频录制开发指导](../../media/video-recorder.md) + +### 属性 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------ | -------------------------------------- | ---- | ---- | ---------------- | +| state9+ | [VideoRecordState](#videorecordstate9) | 是 | 否 | 视频录制的状态。 | + +### prepare9+ + +prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; + +异步方式进行视频录制的参数设置。通过注册回调函数获取返回值。 + +**需要权限:** ohos.permission.MICROPHONE **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder @@ -2516,202 +2585,2407 @@ reset(callback: AsyncCallback\): void; **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步重置视频录制的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------- | ---- | ----------------------------------- | +| config | [VideoRecorderConfig](#videorecorderconfig9) | 是 | 配置视频录制的相关参数。 | +| callback | AsyncCallback\ | 是 | 异步视频录制prepare方法的回调方法。 | **错误码:** 以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -| 错误码ID | 错误信息 | -| -------- | --------------------------------- | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operation not allowed. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js +let videoProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 48000, + videoCodec : 'video/mp4v-es', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} + +let videoConfig = { + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, +} + // asyncallback -videoRecorder.reset((err) => { +videoRecorder.prepare(videoConfig, (err) => { if (err == null) { - console.info('reset videorecorder success'); + console.info('prepare success'); } else { - console.info('reset videorecorder failed and error is ' + err.message); + console.info('prepare failed and error is ' + err.message); } -}); +}) ``` -### reset9+ +### prepare9+ -reset(): Promise\; +prepare(config: VideoRecorderConfig): Promise\; -异步方式重置视频录制。通过Promise获取返回值。 +异步方式进行视频录制的参数设置。通过Promise获取返回值。 -需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 +**需要权限:** ohos.permission.MICROPHONE **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder **系统接口:** 该接口为系统接口 +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------------------------------------- | ---- | ------------------------ | +| config | [VideoRecorderConfig](#videorecorderconfig9) | 是 | 配置视频录制的相关参数。 | + **返回值:** -| 类型 | 说明 | -| -------------- | ------------------------------------- | -| Promise\ | 异步重置视频录制方法的Promise返回值。 | +| 类型 | 说明 | +| -------------- | ---------------------------------------- | +| Promise\ | 异步视频录制prepare方法的Promise返回值。 | **错误码:** 以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -| 错误码ID | 错误信息 | -| -------- | -------------------------------- | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operation not allowed. Return by promise. | +| 5400105 | Service died. Return by promise. | **示例:** ```js +let videoProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 48000, + videoCodec : 'video/mp4v-es', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} + +let videoConfig = { + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, +} + // promise -videoRecorder.reset().then(() => { - console.info('reset videorecorder success'); +videoRecorder.prepare(videoConfig).then(() => { + console.info('prepare success'); }).catch((err) => { - console.info('reset videorecorder failed and catch error is ' + err.message); + console.info('prepare failed and catch error is ' + err.message); }); ``` -### on('error')9+ +### getInputSurface9+ -on(type: 'error', callback: ErrorCallback): void +getInputSurface(callback: AsyncCallback\): void; -开始订阅视频录制错误事件,当上报error错误事件后,用户需处理error事件,退出录制操作。 +异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。 + +应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。 + +只能在[prepare()](#videorecorder_prepare1)接口调用后调用。 **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +**系统接口:** 该接口为系统接口 + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':视频录制过程中发生错误,触发该事件。 | -| callback | ErrorCallback | 是 | 录制错误事件回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | --------------------------- | +| callback | AsyncCallback\ | 是 | 异步获得surface的回调方法。 | **错误码:** 以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -| 错误码ID | 错误信息 | -| -------- | --------------------------------- | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **示例:** ```js -// 当获取videoRecordState接口出错时通过此订阅事件上报 -videoRecorder.on('error', (error) => { // 设置'error'事件回调 - console.info(`audio error called, error: ${error}`); -}) +// asyncallback +let surfaceID = null; // 传递给外界的surfaceID +videoRecorder.getInputSurface((err, surfaceId) => { + if (err == null) { + console.info('getInputSurface success'); + surfaceID = surfaceId; + } else { + console.info('getInputSurface failed and error is ' + err.message); + } +}); ``` -## VideoRecordState9+ - -视频录制的状态机。可通过state属性获取当前状态。 - -**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder +### getInputSurface9+ -**系统接口:** 该接口为系统接口 +getInputSurface(): Promise\; -| 名称 | 类型 | 说明 | -| -------- | ------ | ---------------------- | -| idle | string | 视频录制空闲。 | -| prepared | string | 视频录制参数设置完成。 | -| playing | string | 视频正在录制。 | -| paused | string | 视频暂停录制。 | -| stopped | string | 视频录制停止。 | -| error | string | 错误状态。 | + 异步方式获得录制需要的surface。此surface提供给调用者,调用者从此surface中获取surfaceBuffer,填入相应的数据。 -## VideoRecorderConfig9+ +应当注意,填入的视频数据需要携带时间戳(单位ns),buffersize。时间戳的起始时间请以系统启动时间为基准。 -表示视频录制的参数设置。 +只能在[prepare()](#videorecorder_prepare1)接口调用后调用。 **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder **系统接口:** 该接口为系统接口 -| 名称 | 类型 | 必填 | 说明 | -| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | -| audioSourceType | [AudioSourceType](#audiosourcetype9) | 是 | 视频录制的音频源类型。 | -| videoSourceType | [VideoSourceType](#videosourcetype9) | 是 | 视频录制的视频源类型。 | -| profile | [VideoRecorderProfile](#videorecorderprofile9) | 是 | 视频录制的profile。 | -| rotation | number | 否 | 录制视频的旋转角度。 | -| location | [Location](#location) | 否 | 录制视频的地理位置。 | -| url | string | 是 | 视频输出URL:fd://xx (fd number)
![](figures/zh-cn_image_url.png) | +**返回值:** -## AudioSourceType9+ +| 类型 | 说明 | +| ---------------- | -------------------------------- | +| Promise\ | 异步获得surface的Promise返回值。 | -表示视频录制中音频源类型的枚举。 +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**示例:** + +```js +// promise +let surfaceID = null; // 传递给外界的surfaceID +videoRecorder.getInputSurface().then((surfaceId) => { + console.info('getInputSurface success'); + surfaceID = surfaceId; +}).catch((err) => { + console.info('getInputSurface failed and catch error is ' + err.message); +}); +``` + +### start9+ + +start(callback: AsyncCallback\): void; + +异步方式开始视频录制。通过注册回调函数获取返回值。 + +在[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)后调用,需要依赖数据源先给surface传递数据。 **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder **系统接口:** 该接口为系统接口 -| 名称 | 值 | 说明 | -| ------------------------- | ---- | ---------------------- | -| AUDIO_SOURCE_TYPE_DEFAULT | 0 | 默认的音频输入源类型。 | -| AUDIO_SOURCE_TYPE_MIC | 1 | 表示MIC的音频输入源。 | +**参数:** -## VideoSourceType9+ +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步开始视频录制的回调方法。 | -表示视频录制中视频源类型的枚举。 +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**示例:** + +```js +// asyncallback +videoRecorder.start((err) => { + if (err == null) { + console.info('start videorecorder success'); + } else { + console.info('start videorecorder failed and error is ' + err.message); + } +}); +``` + +### start9+ + +start(): Promise\; + +异步方式开始视频录制。通过Promise获取返回值。 + +在[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)后调用,需要依赖数据源先给surface传递数据。 **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder **系统接口:** 该接口为系统接口 -| 名称 | 值 | 说明 | -| ----------------------------- | ---- | ------------------------------- | -| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | 输入surface中携带的是raw data。 | -| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | 输入surface中携带的是ES data。 | +**返回值:** -## VideoRecorderProfile9+ +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步开始视频录制方法的Promise返回值。 | -视频录制的配置文件。 +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**示例:** + +```js +// promise +videoRecorder.start().then(() => { + console.info('start videorecorder success'); +}).catch((err) => { + console.info('start videorecorder failed and catch error is ' + err.message); +}); +``` + +### pause9+ + +pause(callback: AsyncCallback\): void; + +异步方式暂停视频录制。通过注册回调函数获取返回值。 + +在[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。 **系统能力:** SystemCapability.Multimedia.Media.VideoRecorder **系统接口:** 该接口为系统接口 -| 名称 | 类型 | 必填 | 说明 | -| ---------------- | -------------------------------------------- | ---- | ---------------- | -| audioBitrate | number | 是 | 音频编码比特率。 | -| audioChannels | number | 是 | 音频采集声道数。 | -| audioCodec | [CodecMimeType](#codecmimetype8) | 是 | 音频编码格式。 | -| audioSampleRate | number | 是 | 音频采样率。 | -| fileFormat | [ContainerFormatType](#containerformattype8) | 是 | 文件的容器格式。 | -| videoBitrate | number | 是 | 视频编码比特率。 | -| videoCodec | [CodecMimeType](#codecmimetype8) | 是 | 视频编码格式。 | -| videoFrameWidth | number | 是 | 录制视频帧的宽。 | -| videoFrameHeight | number | 是 | 录制视频帧的高。 | -| videoFrameRate | number | 是 | 录制视频帧率。 | +**参数:** -## ContainerFormatType8+ +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步暂停视频录制的回调方法。 | -表示容器格式类型的枚举,缩写为CFT。 +**错误码:** -**系统能力:** SystemCapability.Multimedia.Media.Core +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) -| 名称 | 值 | 说明 | -| ----------- | ----- | --------------------- | -| CFT_MPEG_4 | 'mp4' | 视频的容器格式,MP4。 | -| CFT_MPEG_4A | 'm4a' | 音频的容器格式,M4A。 | +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | -## Location +**示例:** -视频录制的地理位置。 +```js +// asyncallback +videoRecorder.pause((err) => { + if (err == null) { + console.info('pause videorecorder success'); + } else { + console.info('pause videorecorder failed and error is ' + err.message); + } +}); +``` -**系统能力:** SystemCapability.Multimedia.Media.Core +### pause9+ -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ---------------- | -| latitude | number | 是 | 地理位置的纬度。 | -| longitude | number | 是 | 地理位置的经度。 | \ No newline at end of file +pause(): Promise\; + +异步方式暂停视频录制。通过Promise获取返回值。 + +在[start()](#videorecorder_start1)后调用。可以通过调用[resume()](#videorecorder_resume1)接口来恢复录制。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步暂停视频录制方法的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**示例:** + +```js +// promise +videoRecorder.pause().then(() => { + console.info('pause videorecorder success'); +}).catch((err) => { + console.info('pause videorecorder failed and catch error is ' + err.message); +}); +``` + +### resume9+ + +resume(callback: AsyncCallback\): void; + +异步方式恢复视频录制。通过注册回调函数获取返回值。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步恢复视频录制的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**示例:** + +```js +// asyncallback +videoRecorder.resume((err) => { + if (err == null) { + console.info('resume videorecorder success'); + } else { + console.info('resume videorecorder failed and error is ' + err.message); + } +}); +``` + +### resume9+ + +resume(): Promise\; + +异步方式恢复视频录制。通过Promise获取返回值。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步恢复视频录制方法的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**示例:** + +```js +// promise +videoRecorder.resume().then(() => { + console.info('resume videorecorder success'); +}).catch((err) => { + console.info('resume videorecorder failed and catch error is ' + err.message); +}); +``` + +### stop9+ + +stop(callback: AsyncCallback\): void; + +异步方式停止视频录制。通过注册回调函数获取返回值。 + +需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步停止视频录制的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**示例:** + +```js +// asyncallback +videoRecorder.stop((err) => { + if (err == null) { + console.info('stop videorecorder success'); + } else { + console.info('stop videorecorder failed and error is ' + err.message); + } +}); +``` + +### stop9+ + +stop(): Promise\; + +异步方式停止视频录制。通过Promise获取返回值。 + +需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步停止视频录制方法的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**示例:** + +```js +// promise +videoRecorder.stop().then(() => { + console.info('stop videorecorder success'); +}).catch((err) => { + console.info('stop videorecorder failed and catch error is ' + err.message); +}); +``` + +### release9+ + +release(callback: AsyncCallback\): void; + +异步方式释放视频录制资源。通过注册回调函数获取返回值。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | 是 | 异步释放视频录制资源的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + +**示例:** + +```js +// asyncallback +videoRecorder.release((err) => { + if (err == null) { + console.info('release videorecorder success'); + } else { + console.info('release videorecorder failed and error is ' + err.message); + } +}); +``` + +### release9+ + +release(): Promise\; + +异步方式释放视频录制资源。通过Promise获取返回值。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------------------- | +| Promise\ | 异步释放视频录制资源方法的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + +**示例:** + +```js +// promise +videoRecorder.release().then(() => { + console.info('release videorecorder success'); +}).catch((err) => { + console.info('release videorecorder failed and catch error is ' + err.message); +}); +``` + +### reset9+ + +reset(callback: AsyncCallback\): void; + +异步方式重置视频录制。通过注册回调函数获取返回值。 + +需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | 是 | 异步重置视频录制的回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**示例:** + +```js +// asyncallback +videoRecorder.reset((err) => { + if (err == null) { + console.info('reset videorecorder success'); + } else { + console.info('reset videorecorder failed and error is ' + err.message); + } +}); +``` + +### reset9+ + +reset(): Promise\; + +异步方式重置视频录制。通过Promise获取返回值。 + +需要重新调用[prepare()](#videorecorder_prepare1)和[getInputSurface()](#getinputsurface9)接口才能重新录制。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------- | +| Promise\ | 异步重置视频录制方法的Promise返回值。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | -------------------------------- | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**示例:** + +```js +// promise +videoRecorder.reset().then(() => { + console.info('reset videorecorder success'); +}).catch((err) => { + console.info('reset videorecorder failed and catch error is ' + err.message); +}); +``` + +### on('error')9+ + +on(type: 'error', callback: ErrorCallback): void + +开始订阅视频录制错误事件,当上报error错误事件后,用户需处理error事件,退出录制操作。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':视频录制过程中发生错误,触发该事件。 | +| callback | ErrorCallback | 是 | 录制错误事件回调方法。 | + +**错误码:** + +以下错误码的详细介绍请参见[媒体错误码](../errorcodes/errorcode-media.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------- | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**示例:** + +```js +// 当获取videoRecordState接口出错时通过此订阅事件上报 +videoRecorder.on('error', (error) => { // 设置'error'事件回调 + console.info(`audio error called, error: ${error}`); +}) +``` + +## VideoRecordState9+ + +视频录制的状态机。可通过state属性获取当前状态。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +| 名称 | 类型 | 说明 | +| -------- | ------ | ---------------------- | +| idle | string | 视频录制空闲。 | +| prepared | string | 视频录制参数设置完成。 | +| playing | string | 视频正在录制。 | +| paused | string | 视频暂停录制。 | +| stopped | string | 视频录制停止。 | +| error | string | 错误状态。 | + +## VideoRecorderConfig9+ + +表示视频录制的参数设置。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +| 名称 | 类型 | 必填 | 说明 | +| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioSourceType | [AudioSourceType](#audiosourcetype9) | 是 | 视频录制的音频源类型。 | +| videoSourceType | [VideoSourceType](#videosourcetype9) | 是 | 视频录制的视频源类型。 | +| profile | [VideoRecorderProfile](#videorecorderprofile9) | 是 | 视频录制的profile。 | +| rotation | number | 否 | 录制视频的旋转角度。 | +| location | [Location](#location) | 否 | 录制视频的地理位置。 | +| url | string | 是 | 视频输出URL:fd://xx (fd number)
![](figures/zh-cn_image_url.png) | + +## VideoRecorderProfile9+ + +视频录制的配置文件。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoRecorder + +**系统接口:** 该接口为系统接口 + +| 名称 | 类型 | 必填 | 说明 | +| ---------------- | -------------------------------------------- | ---- | ---------------- | +| audioBitrate | number | 是 | 音频编码比特率。 | +| audioChannels | number | 是 | 音频采集声道数。 | +| audioCodec | [CodecMimeType](#codecmimetype8) | 是 | 音频编码格式。 | +| audioSampleRate | number | 是 | 音频采样率。 | +| fileFormat | [ContainerFormatType](#containerformattype8) | 是 | 文件的容器格式。 | +| videoBitrate | number | 是 | 视频编码比特率。 | +| videoCodec | [CodecMimeType](#codecmimetype8) | 是 | 视频编码格式。 | +| videoFrameWidth | number | 是 | 录制视频帧的宽。 | +| videoFrameHeight | number | 是 | 录制视频帧的高。 | +| videoFrameRate | number | 是 | 录制视频帧率。 | + +## media.createAudioPlayer(deprecated) + +createAudioPlayer(): AudioPlayer + +同步方式创建音频播放实例。 + +> **说明:** +> 从API version 6开始支持,从API version 9开始废弃,建议使用[createAVPlayer](#mediacreateavplayer9)替代。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**返回值:** + +| 类型 | 说明 | +| --------------------------- | ------------------------------------------------------------ | +| [AudioPlayer](#audioplayerdeprecated) | 返回AudioPlayer类实例,失败时返回null。可用于音频播放、暂停、停止等操作。 | + +**示例:** + +```js +let audioPlayer = media.createAudioPlayer(); +``` + +## media.createVideoPlayer(deprecated) + +createVideoPlayer(callback: AsyncCallback\): void + +异步方式创建视频播放实例,通过注册回调函数获取返回值。 + +> **说明:** +> 从API version 8开始支持,从API version 9开始废弃,建议使用[createAVPlayer](#mediacreateavplayer9)替代。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[VideoPlayer](#videoplayerdeprecated)> | 是 | 回调函数。异步返回VideoPlayer实例,失败时返回null。可用于管理和播放视频媒体。 | + +**示例:** + +```js +let videoPlayer + +media.createVideoPlayer((error, video) => { + if (video != null) { + videoPlayer = video; + console.info('video createVideoPlayer success'); + } else { + console.info(`video createVideoPlayer fail, error:${error}`); + } +}); +``` + +## media.createVideoPlayer(deprecated) + +createVideoPlayer(): Promise\ + +异步方式创建视频播放实例,通过Promise获取返回值。 + +> **说明:** +> 从API version 8开始支持,从API version 9开始废弃,建议使用[createAVPlayer](#mediacreateavplayer9-1)替代。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------------------------------ | +| Promise<[VideoPlayer](#videoplayerdeprecated)> | Promise对象。异步返回VideoPlayer实例,失败时返回null。可用于管理和播放视频媒体。 | + +**示例:** + +```js +let videoPlayer + +media.createVideoPlayer().then((video) => { + if (video != null) { + videoPlayer = video; + console.info('video createVideoPlayer success'); + } else { + console.info('video createVideoPlayer fail'); + } +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +## media.createAudioRecorder(deprecated) + +createAudioRecorder(): AudioRecorder + +创建音频录制的实例来控制音频的录制。 +一台设备只允许创建一个录制实例。 + +> **说明:** +> 从API version 8开始支持,从API version 9开始废弃,建议使用[createAVRecorder](#mediacreateavrecorder9)替代。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | ------------------------------------------------------------ | +| [AudioRecorder](#audiorecorderdeprecated) | 返回AudioRecorder类实例,失败时返回null。可用于录制音频媒体。 | + +**示例:** + +```js +let audioRecorder = media.createAudioRecorder(); +``` + +## MediaErrorCode(deprecated) + +媒体服务错误类型枚举。 + +> **说明:** +> 从API version 8开始支持,从API version 9开始废弃,建议使用[媒体错误码](../errorcodes/errorcode-media.md)替代。 + +**系统能力:** SystemCapability.Multimedia.Media.Core + +| 名称 | 值 | 说明 | +| -------------------------- | ---- | -------------------------------------- | +| MSERR_OK | 0 | 表示操作成功。 | +| MSERR_NO_MEMORY | 1 | 表示申请内存失败,系统可能无可用内存。 | +| MSERR_OPERATION_NOT_PERMIT | 2 | 表示无权限执行此操作。 | +| MSERR_INVALID_VAL | 3 | 表示传入入参无效。 | +| MSERR_IO | 4 | 表示发生IO错误。 | +| MSERR_TIMEOUT | 5 | 表示操作超时。 | +| MSERR_UNKNOWN | 6 | 表示未知错误。 | +| MSERR_SERVICE_DIED | 7 | 表示服务端失效。 | +| MSERR_INVALID_STATE | 8 | 表示在当前状态下,不允许执行此操作。 | +| MSERR_UNSUPPORTED | 9 | 表示在当前版本下,不支持此操作。 | + +## AudioPlayer(deprecated) + +> **说明:** +> 从API version 6开始支持,从API version 9开始废弃,建议使用[AVPlayer](#avplayer9)替代。 + +音频播放管理类,用于管理和播放音频媒体。在调用AudioPlayer的方法前,需要先通过[createAudioPlayer()](#mediacreateaudioplayerdeprecated)构建一个AudioPlayer实例。 + +### 属性 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| src | string | 是 | 是 | 音频媒体URI,支持当前主流的音频格式(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
**需要权限:** ohos.permission.READ_MEDIA 或 ohos.permission.INTERNET。 | +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 音频媒体文件描述,使用场景:应用中的音频资源被连续存储在同一个文件中。
**使用示例**:
假设一个连续存储的音乐文件:
音乐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
| +| loop | boolean | 是 | 是 | 音频循环播放属性,设置为'true'表示循环播放。 | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | 是 | 是 | 音频焦点模型。 | +| currentTime | number | 是 | 否 | 音频的当前播放位置,单位为毫秒(ms)。 | +| duration | number | 是 | 否 | 音频时长,单位为毫秒(ms)。 | +| state | [AudioState](#audiostate) | 是 | 否 | 可以查询音频播放的状态,该状态不可作为调用play/pause/stop等状态切换的触发条件。 | + +### play + +play(): void + +开始播放音频资源,需在[dataLoad](#audioplayer_on)事件成功触发后,才能调用。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**示例:** + +```js +audioPlayer.on('play', () => { //设置'play'事件回调 + console.log('audio play success'); +}); +audioPlayer.play(); +``` + +### pause + +pause(): void + +暂停播放音频资源。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**示例:** + +```js +audioPlayer.on('pause', () => { //设置'pause'事件回调 + console.log('audio pause success'); +}); +audioPlayer.pause(); +``` + +### stop + +stop(): void + +停止播放音频资源。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**示例:** + +```js +audioPlayer.on('stop', () => { //设置'stop'事件回调 + console.log('audio stop success'); +}); +audioPlayer.stop(); +``` + +### reset7+ + +reset(): void + +重置播放音频资源。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**示例:** + +```js +audioPlayer.on('reset', () => { //设置'reset'事件回调 + console.log('audio reset success'); +}); +audioPlayer.reset(); +``` + +### seek + +seek(timeMs: number): void + +跳转到指定播放位置。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------------------------------------------------------- | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围[0, duration]。 | + +**示例:** + +```js +audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调 + if (seekDoneTime == null) { + console.info('audio seek fail'); + return; + } + console.log('audio seek success. seekDoneTime: ' + seekDoneTime); +}); +audioPlayer.seek(30000); //seek到30000ms的位置 +``` + +### setVolume + +setVolume(vol: number): void + +设置音量。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | + +**示例:** + +```js +audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 + console.log('audio volumeChange success'); +}); +audioPlayer.setVolume(1); //设置音量到100% +``` + +### release + +release(): void + +释放音频资源。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**示例:** + +```js +audioPlayer.release(); +audioPlayer = undefined; +``` + +### getTrackDescription8+ + +getTrackDescription(callback: AsyncCallback\>): void + +通过回调方式获取音频轨道信息。需在[dataLoad](#audioplayer_on)事件成功触发后,才能调用。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback\> | 是 | 音频轨道信息MediaDescription数组回调方法。 | + +**示例:** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + +audioPlayer.getTrackDescription((error, arrList) => { + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); + } + } else { + console.log(`audio getTrackDescription fail, error:${error}`); + } +}); +``` + +### getTrackDescription8+ + +getTrackDescription(): Promise\> + +通过Promise方式获取音频轨道信息。需在[dataLoad](#audioplayer_on)事件成功触发后,才能调用 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | 音频轨道信息MediaDescription数组Promise返回值。 | + +**示例:** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} +let arrayDescription = null +audioPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('audio getTrackDescription fail'); + } +}).catch((error) => { + console.info(`audio catchCallback, error:${error}`); +}); + +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} +``` + +### on('bufferingUpdate')8+ + +on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void + +开始订阅音频缓存更新事件。仅网络播放支持该订阅事件。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 音频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | +| callback | function | 是 | 音频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | + +**示例:** + +```js +audioPlayer.on('bufferingUpdate', (infoType, value) => { + console.log('audio bufferingInfo type: ' + infoType); + console.log('audio bufferingInfo value: ' + value); +}); +``` + + ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') + +on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void + +开始订阅音频播放事件。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 播放事件回调类型,支持的事件包括:'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'。
- 'play':完成[play()](#audioplayer_play)调用,音频开始播放,触发该事件。
- 'pause':完成[pause()](#audioplayer_pause)调用,音频暂停播放,触发该事件。
- 'stop':完成[stop()](#audioplayer_stop)调用,音频停止播放,触发该事件。
- 'reset':完成[reset()](#audioplayer_reset)调用,播放器重置,触发该事件。
- 'dataLoad':完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。
- 'finish':完成音频播放后触发该事件。
- 'volumeChange':完成[setVolume()](#audioplayer_setvolume)调用,播放音量改变后触发该事件。 | +| callback | () => void | 是 | 播放事件回调方法。 | + +**示例:** + +```js +import fileio from '@ohos.fileio' + +let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例 +audioPlayer.on('dataLoad', () => { //设置'dataLoad'事件回调,src属性设置成功后,触发此回调 + console.info('audio set source success'); + audioPlayer.play(); //开始播放,并触发'play'事件回调 +}); +audioPlayer.on('play', () => { //设置'play'事件回调 + console.info('audio play success'); + audioPlayer.seek(30000); //调用seek方法,并触发'timeUpdate'事件回调 +}); +audioPlayer.on('pause', () => { //设置'pause'事件回调 + console.info('audio pause success'); + audioPlayer.stop(); //停止播放,并触发'stop'事件回调 +}); +audioPlayer.on('reset', () => { //设置'reset'事件回调 + console.info('audio reset success'); + audioPlayer.release(); //释放播放实例资源 + audioPlayer = undefined; +}); +audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调 + if (seekDoneTime == null) { + console.info('audio seek fail'); + return; + } + console.info('audio seek success, and seek time is ' + seekDoneTime); + audioPlayer.setVolume(0.5); //设置音量为50%,并触发'volumeChange'事件回调 +}); +audioPlayer.on('volumeChange', () => { //设置'volumeChange'事件回调 + console.info('audio volumeChange success'); + audioPlayer.pause(); //暂停播放,并触发'pause'事件回调 +}); +audioPlayer.on('finish', () => { //设置'finish'事件回调 + console.info('audio play finish'); + audioPlayer.stop(); //停止播放,并触发'stop'事件回调 +}); +audioPlayer.on('error', (error) => { //设置'error'事件回调 + console.info(`audio error called, error: ${error}`); +}); + +// 用户选择视频设置fd(本地播放) +let fdPath = 'fd://'; +// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" 命令,将其推送到设备上 +let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +fileio.open(path).then((fdValue) => { + fdPath = fdPath + '' + fdValue; + console.info('open fd success fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}).catch((err) => { + console.info('open fd failed err is' + err); +}); +audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调 +``` + +### on('timeUpdate') + +on(type: 'timeUpdate', callback: Callback\): void + +开始订阅音频播放时间更新事件。处于播放状态时,每隔1s上报一次该事件。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 播放事件回调类型,支持的事件包括:'timeUpdate'。
- 'timeUpdate':音频播放时间戳更新,开始播放后自动触发该事件。 | +| callback | Callback\ | 是 | 播放事件回调方法。回调方法入参为更新后的时间戳。 | + +**示例:** + +```js +audioPlayer.on('timeUpdate', (newTime) => { //设置'timeUpdate'事件回调 + if (newTime == null) { + console.info('audio timeUpadate fail'); + return; + } + console.log('audio timeUpadate success. seekDoneTime: ' + newTime); +}); +audioPlayer.play(); //开始播放后,自动触发时间戳更新事件 +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +开始订阅音频播放错误事件,当上报error错误事件后,用户需处理error事件,退出播放操作。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':音频播放中发生错误,触发该事件。 | +| callback | ErrorCallback | 是 | 播放错误事件回调方法。 | + +**示例:** + +```js +audioPlayer.on('error', (error) => { //设置'error'事件回调 + console.info(`audio error called, error: ${error}`); +}); +audioPlayer.setVolume(3); //设置volume为无效值,触发'error'事件 +``` + +## AudioState(deprecated) + +音频播放的状态机。可通过state属性获取当前状态。 + +> **说明:** +> 从API version 6开始支持,从API version 9开始废弃,建议使用[AVPlayerState](#avplayerstate9)替代。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioPlayer + +| 名称 | 类型 | 说明 | +| ------- | ------ | ---------------------------------------------- | +| idle | string | 音频播放空闲,dataload/reset成功后处于此状态。 | +| playing | string | 音频正在播放,play成功后处于此状态。 | +| paused | string | 音频暂停播放,pause成功后处于此状态。 | +| stopped | string | 音频播放停止,stop/播放结束后处于此状态。 | +| error | string | 错误状态。 | + +## VideoPlayer(deprecated) + +> **说明:** +> 从API version 8开始支持,从API version 9开始废弃,建议使用[AVPlayer](#avplayer9)替代。 + +视频播放管理类,用于管理和播放视频媒体。在调用VideoPlayer的方法前,需要先通过[createVideoPlayer()](#createvideoplayer)构建一个VideoPlayer实例。 + +视频播放demo可参考:[视频播放开发指导](../../media/video-playback.md) + +### 属性 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| url8+ | string | 是 | 是 | 视频媒体URL,支持当前主流的视频格式(mp4、mpeg-ts、webm、mkv)。
**支持路径示例**:
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) | 是 | 是 | 视频媒体文件描述,使用场景:应用中的视频资源被连续存储在同一个文件中。
**使用示例**:
假设一个连续存储的音乐文件:
视频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
| +| loop8+ | boolean | 是 | 是 | 视频循环播放属性,设置为'true'表示循环播放。 | +| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式。 | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | 是 | 是 | 音频焦点模型。 | +| currentTime8+ | number | 是 | 否 | 视频的当前播放位置,单位为毫秒(ms)。 | +| duration8+ | number | 是 | 否 | 视频时长,单位为毫秒(ms),返回-1表示直播模式。 | +| state8+ | [VideoPlayState](#videoplayerstate) | 是 | 否 | 视频播放的状态。 | +| width8+ | number | 是 | 否 | 视频宽,单位为像素(px)。 | +| height8+ | number | 是 | 否 | 视频高,单位为像素(px)。 | + +### setDisplaySurface8+ + +setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void + +通过回调方式设置SurfaceId。 + +*注意:SetDisplaySurface需要在设置url和Prepare之间,无音频的视频流必须设置Surface否则Prepare失败。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | -------------------- | ---- | ------------------------- | +| surfaceId | string | 是 | SurfaceId | +| callback | AsyncCallback\ | 是 | 设置SurfaceId的回调方法。 | + +**示例:** + +```js +let surfaceId = null; +videoPlayer.setDisplaySurface(surfaceId, (err) => { + if (err == null) { + console.info('setDisplaySurface success!'); + } else { + console.info('setDisplaySurface fail!'); + } +}); +``` + +### setDisplaySurface8+ + +setDisplaySurface(surfaceId: string): Promise\ + +通过Promise方式设置SurfaceId。 + +*注意:SetDisplaySurface需要在设置url和Prepare之间,无音频的视频流必须设置Surface否则Prepare失败。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------- | +| surfaceId | string | 是 | SurfaceId | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------ | +| Promise\ | 设置SurfaceId的Promise返回值。 | + +**示例:** + +```js +let surfaceId = null; +videoPlayer.setDisplaySurface(surfaceId).then(() => { + console.info('setDisplaySurface success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### prepare8+ + +prepare(callback: AsyncCallback\): void + +通过回调方式准备播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | 是 | 准备播放视频的回调方法。 | + +**示例:** + +```js +videoPlayer.prepare((err) => { + if (err == null) { + console.info('prepare success!'); + } else { + console.info('prepare fail!'); + } +}); +``` + +### prepare8+ + +prepare(): Promise\ + +通过Promise方式准备播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise\ | 准备播放视频的Promise返回值。 | + +**示例:** + +```js +videoPlayer.prepare().then(() => { + console.info('prepare success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### play8+ + +play(callback: AsyncCallback\): void; + +通过回调方式开始播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | 是 | 开始播放视频的回调方法。 | + +**示例:** + +```js +videoPlayer.play((err) => { + if (err == null) { + console.info('play success!'); + } else { + console.info('play fail!'); + } +}); +``` + +### play8+ + +play(): Promise\; + +通过Promise方式开始播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise\ | 开始播放视频的Promise返回值。 | + +**示例:** + +```js +videoPlayer.play().then(() => { + console.info('play success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### pause8+ + +pause(callback: AsyncCallback\): void + +通过回调方式暂停播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | 是 | 暂停播放视频的回调方法。 | + +**示例:** + +```js +videoPlayer.pause((err) => { + if (err == null) { + console.info('pause success!'); + } else { + console.info('pause fail!'); + } +}); +``` + +### pause8+ + +pause(): Promise\ + +通过Promise方式暂停播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise\ | 暂停播放视频的Promise返回值。 | + +**示例:** + +```js +videoPlayer.pause().then(() => { + console.info('pause success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### stop8+ + +stop(callback: AsyncCallback\): void + +通过回调方式停止播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | 是 | 停止播放视频的回调方法。 | + +**示例:** + +```js +videoPlayer.stop((err) => { + if (err == null) { + console.info('stop success!'); + } else { + console.info('stop fail!'); + } +}); +``` + +### stop8+ + +stop(): Promise\ + +通过Promise方式停止播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise\ | 停止播放视频的Promise返回值。 | + +**示例:** + +```js +videoPlayer.stop().then(() => { + console.info('stop success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### reset8+ + +reset(callback: AsyncCallback\): void + +通过回调方式重置播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | 是 | 切换播放视频的回调方法。 | + +**示例:** + +```js +videoPlayer.reset((err) => { + if (err == null) { + console.info('reset success!'); + } else { + console.info('reset fail!'); + } +}); +``` + +### reset8+ + +reset(): Promise\ + +通过Promise方式重置播放视频。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise\ | 切换播放视频的Promise返回值。 | + +**示例:** + +```js +videoPlayer.reset().then(() => { + console.info('reset success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### seek8+ + +seek(timeMs: number, callback: AsyncCallback\): void + +通过回调方式跳转到指定播放位置,默认跳转到指定时间点的上一个关键帧。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | +| callback | AsyncCallback\ | 是 | 跳转到指定播放位置的回调方法。 | + +**示例:** + +```js +let seekTime = 5000; +videoPlayer.seek(seekTime, (err, result) => { + if (err == null) { + console.info('seek success!'); + } else { + console.info('seek fail!'); + } +}); +``` + +### seek8+ + +seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void + +通过回调方式跳转到指定播放位置。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | +| mode | [SeekMode](#seekmode8) | 是 | 跳转模式。 | +| callback | AsyncCallback\ | 是 | 跳转到指定播放位置的回调方法。 | + +**示例:** + +```js +import media from '@ohos.multimedia.media' +let seekTime = 5000; +videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err, result) => { + if (err == null) { + console.info('seek success!'); + } else { + console.info('seek fail!'); + } +}); +``` + +### seek8+ + +seek(timeMs: number, mode?:SeekMode): Promise\ + +通过Promise方式跳转到指定播放位置,如果没有设置mode则跳转到指定时间点的上一个关键帧。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 | +| mode | [SeekMode](#seekmode8) | 否 | 跳转模式。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------- | +| Promise\ | 跳转到指定播放位置的Promise返回值,单位ms。 | + +**示例:** + +```js +import media from '@ohos.multimedia.media' +let seekTime = 5000; +videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime表示seek完成后的时间点 + console.info('seek success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); + +videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => { + console.info('seek success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### setVolume8+ + +setVolume(vol: number, callback: AsyncCallback\): void + +通过回调方式设置音量。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | +| callback | AsyncCallback\ | 是 | 设置音量的回调方法。 | + +**示例:** + +```js +let vol = 0.5; +videoPlayer.setVolume(vol, (err, result) => { + if (err == null) { + console.info('setVolume success!'); + } else { + console.info('setVolume fail!'); + } +}); +``` + +### setVolume8+ + +setVolume(vol: number): Promise\ + +通过Promise方式设置音量。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| vol | number | 是 | 指定的相对音量大小,取值范围为[0.00-1.00],1表示最大音量,即100%。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 设置音量的Promise返回值。 | + +**示例:** + +```js +let vol = 0.5; +videoPlayer.setVolume(vol).then(() => { + console.info('setVolume success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### release8+ + +release(callback: AsyncCallback\): void + +通过回调方式释放视频资源。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | 是 | 释放视频资源的回调方法。 | + +**示例:** + +```js +videoPlayer.release((err) => { + if (err == null) { + console.info('release success!'); + } else { + console.info('release fail!'); + } +}); +``` + +### release8+ + +release(): Promise\ + +通过Promise方式释放视频资源。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------------- | +| Promise\ | 释放视频资源的Promise返回值。 | + +**示例:** + +```js +videoPlayer.release().then(() => { + console.info('release success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### getTrackDescription8+ + +getTrackDescription(callback: AsyncCallback\>): void + +通过回调方式获取视频轨道信息。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback\> | 是 | 视频轨道信息MediaDescription数组回调方法。 | + +**示例:** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } +} + +videoPlayer.getTrackDescription((error, arrList) => { + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); + } + } else { + console.log(`video getTrackDescription fail, error:${error}`); + } +}); +``` + +### getTrackDescription8+ + +getTrackDescription(): Promise\> + +通过Promise方式获取视频轨道信息。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | 视频轨道信息MediaDescription数组Promise返回值。 | + +**示例:** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } +} + +let arrayDescription; +videoPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('video getTrackDescription fail'); + } +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} +``` + +### setSpeed8+ + +setSpeed(speed:number, callback: AsyncCallback\): void + +通过回调方式设置播放速度。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ---------------------------------------------------------- | +| speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 | +| callback | AsyncCallback\ | 是 | 设置播放速度的回调方法。 | + +**示例:** + +```js +import media from '@ohos.multimedia.media' +let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; + +videoPlayer.setSpeed(speed, (err, result) => { + if (err == null) { + console.info('setSpeed success!'); + } else { + console.info('setSpeed fail!'); + } +}); +``` + +### setSpeed8+ + +setSpeed(speed:number): Promise\ + +通过Promise方式设置播放速度。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------------------------------------------- | +| speed | number | 是 | 指定播放视频速度,具体见[PlaybackSpeed](#playbackspeed8)。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | 播放速度Promise返回值,具体见[PlaybackSpeed](#playbackspeed8)。 | + +**示例:** + +```js +import media from '@ohos.multimedia.media' +let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; + +videoPlayer.setSpeed(speed).then(() => { + console.info('setSpeed success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### on('playbackCompleted')8+ + +on(type: 'playbackCompleted', callback: Callback\): void + +开始监听视频播放完成事件。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ----------------------------------------------------------- | +| type | string | 是 | 视频播放完成事件回调类型,支持的事件:'playbackCompleted'。 | +| callback | function | 是 | 视频播放完成事件回调方法。 | + +**示例:** + +```js +videoPlayer.on('playbackCompleted', () => { + console.info('playbackCompleted success!'); +}); +``` + +### on('bufferingUpdate')8+ + +on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void + +开始监听视频缓存更新事件。仅网络播放支持该订阅事件。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 视频缓存事件回调类型,支持的事件:'bufferingUpdate'。 | +| callback | function | 是 | 视频缓存事件回调方法。
[BufferingInfoType](#bufferinginfotype8)为BUFFERING_PERCENT或CACHED_DURATION时,value值有效,否则固定为0。 | + +**示例:** + +```js +videoPlayer.on('bufferingUpdate', (infoType, value) => { + console.log('video bufferingInfo type: ' + infoType); + console.log('video bufferingInfo value: ' + value); +}); +``` + +### on('startRenderFrame')8+ + +on(type: 'startRenderFrame', callback: Callback\): void + +开始监听视频播放首帧送显上报事件。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 视频播放首帧送显上报事件回调类型,支持的事件:'startRenderFrame'。 | +| callback | Callback\ | 是 | 视频播放首帧送显上报事件回调方法。 | + +**示例:** + +```js +videoPlayer.on('startRenderFrame', () => { + console.info('startRenderFrame success!'); +}); +``` + +### on('videoSizeChanged')8+ + +on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void + +开始监听视频播放宽高变化事件。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 视频播放宽高变化事件回调类型,支持的事件:'videoSizeChanged'。 | +| callback | function | 是 | 视频播放宽高变化事件回调方法,width表示宽,height表示高。 | + +**示例:** + +```js +videoPlayer.on('videoSizeChanged', (width, height) => { + console.log('video width is: ' + width); + console.log('video height is: ' + height); +}); +``` + +### on('error')8+ + +on(type: 'error', callback: ErrorCallback): void + +开始监听视频播放错误事件,当上报error错误事件后,用户需处理error事件,退出播放操作。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 播放错误事件回调类型,支持的事件包括:'error'。
- 'error':视频播放中发生错误,触发该事件。 | +| callback | ErrorCallback | 是 | 播放错误事件回调方法。 | + +**示例:** + +```js +videoPlayer.on('error', (error) => { // 设置'error'事件回调 + console.info(`video error called, error: ${error}`); +}); +videoPlayer.url = 'fd://error'; //设置错误的播放地址,触发'error'事件 +``` + +## VideoPlayState(deprecated) + +视频播放的状态机,可通过state属性获取当前状态。 + +> **说明:** +> 从API version 8开始支持,从API version 9开始废弃,建议使用[AVPlayerState](#avplayerstate9)替代。 + +**系统能力:** SystemCapability.Multimedia.Media.VideoPlayer + +| 名称 | 类型 | 说明 | +| -------- | ------ | -------------- | +| idle | string | 视频播放空闲。 | +| prepared | string | 视频播放准备。 | +| playing | string | 视频正在播放。 | +| paused | string | 视频暂停播放。 | +| stopped | string | 视频播放停止。 | +| error | string | 错误状态。 | + +## AudioRecorder(deprecated) + +> **说明:** +> 从API version 6开始支持,从API version 9开始废弃,建议使用[AVRecorder](#avrecorder9)替代。 + +音频录制管理类,用于录制音频媒体。在调用AudioRecorder的方法前,需要先通过[createAudioRecorder()](#mediacreateaudiorecorder) 构建一个AudioRecorder实例。 + +音频录制demo可参考:[音频录制开发指导](../../media/audio-recorder.md) + +### prepare + +prepare(config: AudioRecorderConfig): void + +录音准备。 + +**需要权限:** ohos.permission.MICROPHONE + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| config | [AudioRecorderConfig](#audiorecorderconfigdeprecated) | 是 | 配置录音的相关参数,包括音频输出URI、编码格式、采样率、声道数、输出格式等。 | + +**示例:** + +```js +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://1', // 文件需先由调用者创建,并给予适当的权限 + location : { latitude : 30, longitude : 130}, +} +audioRecorder.on('prepare', () => { //设置'prepare'事件回调 + console.log('prepare success'); +}); +audioRecorder.prepare(audioRecorderConfig); +``` + + +### start + +start(): void + +开始录制,需在[prepare](#audiorecorder_on)事件成功触发后,才能调用start方法。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**示例:** + +```js +audioRecorder.on('start', () => { //设置'start'事件回调 + console.log('audio recorder start success'); +}); +audioRecorder.start(); +``` + +### pause + +pause():void + +暂停录制,需要在[start](#audiorecorder_on)事件成功触发后,才能调用pause方法。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**示例:** + +```js +audioRecorder.on('pause', () => { //设置'pause'事件回调 + console.log('audio recorder pause success'); +}); +audioRecorder.pause(); +``` + +### resume + +resume():void + +恢复录制,需要在[pause](#audiorecorder_on)事件成功触发后,才能调用resume方法。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**示例:** + +```js +audioRecorder.on('resume', () => { //设置'resume'事件回调 + console.log('audio recorder resume success'); +}); +audioRecorder.resume(); +``` + +### stop + +stop(): void + +停止录音。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**示例:** + +```js +audioRecorder.on('stop', () => { //设置'stop'事件回调 + console.log('audio recorder stop success'); +}); +audioRecorder.stop(); +``` + +### release + +release(): void + +释放录音资源。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**示例:** + +```js +audioRecorder.on('release', () => { //设置'release'事件回调 + console.log('audio recorder release success'); +}); +audioRecorder.release(); +audioRecorder = undefined; +``` + +### reset + +reset(): void + +重置录音。 + +进行重置录音之前,需要先调用[stop()](#audiorecorder_stop)停止录音。重置录音之后,需要调用[prepare()](#audiorecorder_prepare)设置录音参数项,才能再次进行录音。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**示例:** + +```js +audioRecorder.on('reset', () => { //设置'reset'事件回调 + console.log('audio recorder reset success'); +}); +audioRecorder.reset(); +``` + +### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset') + +on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void + +开始订阅音频录制事件。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 录制事件回调类型,支持的事件包括:'prepare' \| 'start' \| 'pause' \| ’resume‘ \| 'stop' \| 'release' \| 'reset'。
- 'prepare' :完成[prepare](#audiorecorder_prepare)调用,音频录制参数设置完成,触发该事件。
- 'start' :完成[start](#audiorecorder_start)调用,音频录制开始,触发该事件。
- 'pause': 完成[pause](#audiorecorder_pause)调用,音频暂停录制,触发该事件。
- 'resume': 完成[resume](#audiorecorder_resume)调用,音频恢复录制,触发该事件。
- 'stop' :完成[stop](#audiorecorder_stop)调用,音频停止录制,触发该事件。
- 'release' :完成[release](#audiorecorder_release)调用,音频释放录制资源,触发该事件。
- 'reset':完成[reset](#audiorecorder_reset)调用,音频重置为初始状态,触发该事件。 | +| callback | ()=>void | 是 | 录制事件回调方法。 | + +**示例:** + +```js +let audioRecorder = media.createAudioRecorder(); // 创建一个音频录制实例 +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 + location : { latitude : 30, longitude : 130}, +} +audioRecorder.on('error', (error) => { // 设置'error'事件回调 + console.info(`audio error called, error: ${error}`); +}); +audioRecorder.on('prepare', () => { // 设置'prepare'事件回调 + console.log('prepare success'); + audioRecorder.start(); // 开始录制,并触发'start'事件回调 +}); +audioRecorder.on('start', () => { // 设置'start'事件回调 + console.log('audio recorder start success'); +}); +audioRecorder.on('pause', () => { // 设置'pause'事件回调 + console.log('audio recorder pause success'); +}); +audioRecorder.on('resume', () => { // 设置'resume'事件回调 + console.log('audio recorder resume success'); +}); +audioRecorder.on('stop', () => { // 设置'stop'事件回调 + console.log('audio recorder stop success'); +}); +audioRecorder.on('release', () => { // 设置'release'事件回调 + console.log('audio recorder release success'); +}); +audioRecorder.on('reset', () => { // 设置'reset'事件回调 + console.log('audio recorder reset success'); +}); +audioRecorder.prepare(audioRecorderConfig) // 设置录制参数 ,并触发'prepare'事件回调 +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +开始订阅音频录制错误事件,当上报error错误事件后,用户需处理error事件,退出录制操作。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 录制错误事件回调类型'error'。
- 'error':音频录制过程中发生错误,触发该事件。 | +| callback | ErrorCallback | 是 | 录制错误事件回调方法。 | + +**示例:** + +```js +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // 文件需先由调用者创建,并给予适当的权限 + location : { latitude : 30, longitude : 130}, +} +audioRecorder.on('error', (error) => { // 设置'error'事件回调 + console.info(`audio error called, error: ${error}`); +}); +audioRecorder.prepare(audioRecorderConfig); // prepare不设置参数,触发'error'事件 +``` + +## AudioRecorderConfig(deprecated) + +> **说明:** +> 从API version 6开始支持,从API version 9开始废弃,建议使用[AVRecorderConfig](#avrecorderconfig9)替代。 + +表示音频的录音配置。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +| 名称 | 类型 | 必填 | 说明 | +| ----------------------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioEncoder | [AudioEncoder](#audioencoderdeprecated) | 否 | 音频编码格式,默认设置为AAC_LC。
**说明:** 从API version 8开始废弃,建议使用audioEncoderMime替代。 | +| audioEncodeBitRate | number | 否 | 音频编码比特率,默认值为48000。 | +| audioSampleRate | number | 否 | 音频采集采样率,默认值为48000。 | +| numberOfChannels | number | 否 | 音频采集声道数,默认值为2。 | +| format | [AudioOutputFormat](#audiooutputformatdeprecated) | 否 | 音频输出封装格式,默认设置为MPEG_4。
**说明:** 从API version 8开始废弃,建议使用fileFormat替代。 | +| location | [Location](#location) | 否 | 音频采集的地理位置。 | +| uri | string | 是 | 音频输出URI:fd://xx (fd number)
![](figures/zh-cn_image_url.png)
文件需要由调用者创建,并赋予适当的权限。 | +| audioEncoderMime8+ | [CodecMimeType](#codecmimetype8) | 否 | 音频编码格式。 | +| fileFormat8+ | [ContainerFormatType](#containerformattype8) | 否 | 音频编码格式。 | + +## AudioEncoder(deprecated) + +> **说明:** +> 从API version 6开始支持,从API version 8开始废弃,建议使用[CodecMimeType](#codecmimetype8)替代。 + +表示音频编码格式的枚举。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +| 名称 | 值 | 说明 | +| ------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | 默认编码格式。
仅做接口定义,暂不支持使用。 | +| AMR_NB | 1 | AMR-NB(Adaptive Multi Rate-Narrow Band Speech Codec) 编码格式。
仅做接口定义,暂不支持使用。 | +| AMR_WB | 2 | AMR-WB(Adaptive Multi Rate-Wide Band Speech Codec) 编码格式。
仅做接口定义,暂不支持使用。 | +| AAC_LC | 3 | AAC-LC(Advanced Audio Coding Low Complexity)编码格式。 | +| HE_AAC | 4 | HE_AAC(High-Efficiency Advanced Audio Coding)编码格式。
仅做接口定义,暂不支持使用。 | + +## AudioOutputFormat(deprecated) + +> **说明:** +> 从API version 6开始支持,从API version 8 开始废弃,建议使用[ContainerFormatType](#containerformattype8)替代。 + +表示音频封装格式的枚举。 + +**系统能力:** SystemCapability.Multimedia.Media.AudioRecorder + +| 名称 | 值 | 说明 | +| -------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | 默认封装格式。
仅做接口定义,暂不支持使用。 | +| MPEG_4 | 2 | 封装为MPEG-4格式。 | +| AMR_NB | 3 | 封装为AMR_NB格式。
仅做接口定义,暂不支持使用。 | +| AMR_WB | 4 | 封装为AMR_WB格式。
仅做接口定义,暂不支持使用。 | +| AAC_ADTS | 6 | 封装为ADTS(Audio Data Transport Stream)格式,是AAC音频的传输流格式。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md index 7c53b3cd6e78afc6cc4f8520689bc6c193e8e474..50072a29d3d45636495c043a45be97da0484ee6d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md @@ -8,11 +8,11 @@ ## 导入模块 -```js -import Notification from '@ohos.notificationManager'; +```ts +import notificationManager from '@ohos.notificationManager'; ``` -## Notification.publish +## notificationManager.publish publish(request: NotificationRequest, callback: AsyncCallback\): void @@ -40,7 +40,7 @@ publish(request: NotificationRequest, callback: AsyncCallback\): void **示例:** -```js +```ts //publish回调 function publishCallback(err) { if (err) { @@ -53,7 +53,7 @@ function publishCallback(err) { let notificationRequest = { id: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -61,12 +61,10 @@ let notificationRequest = { } } }; -Notification.publish(notificationRequest, publishCallback); +notificationManager.publish(notificationRequest, publishCallback); ``` - - -## Notification.publish +## notificationManager.publish publish(request: NotificationRequest): Promise\ @@ -93,12 +91,12 @@ publish(request: NotificationRequest): Promise\ **示例:** -```js +```ts // 通知Request对象 let notificationRequest = { notificationId: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -106,13 +104,13 @@ let notificationRequest = { } } }; -Notification.publish(notificationRequest).then(() => { +notificationManager.publish(notificationRequest).then(() => { console.info("publish success"); }); ``` -## Notification.publish +## notificationManager.publish publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void @@ -146,7 +144,7 @@ publish(request: NotificationRequest, userId: number, callback: AsyncCallback\ @@ -205,11 +203,11 @@ publish(request: NotificationRequest, userId: number): Promise\ **示例:** -```js +```ts let notificationRequest = { notificationId: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -220,13 +218,13 @@ let notificationRequest = { let userId = 1; -Notification.publish(notificationRequest, userId).then(() => { +notificationManager.publish(notificationRequest, userId).then(() => { console.info("publish success"); }); ``` -## Notification.cancel +## notificationManager.cancel cancel(id: number, label: string, callback: AsyncCallback\): void @@ -253,7 +251,7 @@ cancel(id: number, label: string, callback: AsyncCallback\): void **示例:** -```js +```ts // cancel回调 function cancelCallback(err) { if (err) { @@ -262,12 +260,10 @@ function cancelCallback(err) { console.info("cancel success"); } } -Notification.cancel(0, "label", cancelCallback); +notificationManager.cancel(0, "label", cancelCallback); ``` - - -## Notification.cancel +## notificationManager.cancel cancel(id: number, label?: string): Promise\ @@ -293,15 +289,13 @@ cancel(id: number, label?: string): Promise\ **示例:** -```js -Notification.cancel(0).then(() => { +```ts +notificationManager.cancel(0).then(() => { console.info("cancel success"); }); ``` - - -## Notification.cancel +## notificationManager.cancel cancel(id: number, callback: AsyncCallback\): void @@ -327,7 +321,7 @@ cancel(id: number, callback: AsyncCallback\): void **示例:** -```js +```ts // cancel回调 function cancelCallback(err) { if (err) { @@ -336,12 +330,10 @@ function cancelCallback(err) { console.info("cancel success"); } } -Notification.cancel(0, cancelCallback); +notificationManager.cancel(0, cancelCallback); ``` - - -## Notification.cancelAll +## notificationManager.cancelAll cancelAll(callback: AsyncCallback\): void @@ -365,7 +357,7 @@ cancelAll(callback: AsyncCallback\): void **示例:** -```js +```ts // cancel回调 function cancelAllCallback(err) { if (err) { @@ -374,12 +366,10 @@ function cancelAllCallback(err) { console.info("cancelAll success"); } } -Notification.cancelAll(cancelAllCallback); +notificationManager.cancelAll(cancelAllCallback); ``` - - -## Notification.cancelAll +## notificationManager.cancelAll cancelAll(): Promise\ @@ -397,15 +387,13 @@ cancelAll(): Promise\ **示例:** -```js -Notification.cancelAll().then(() => { +```ts +notificationManager.cancelAll().then(() => { console.info("cancelAll success"); }); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(slot: NotificationSlot, callback: AsyncCallback\): void @@ -434,7 +422,7 @@ addSlot(slot: NotificationSlot, callback: AsyncCallback\): void **示例:** -```js +```ts // addslot回调 function addSlotCallBack(err) { if (err) { @@ -445,14 +433,12 @@ function addSlotCallBack(err) { } // 通知slot对象 let notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION + type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; -Notification.addSlot(notificationSlot, addSlotCallBack); +notificationManager.addSlot(notificationSlot, addSlotCallBack); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(slot: NotificationSlot): Promise\ @@ -480,19 +466,17 @@ addSlot(slot: NotificationSlot): Promise\ **示例:** -```js +```ts // 通知slot对象 let notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION + type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; -Notification.addSlot(notificationSlot).then(() => { +notificationManager.addSlot(notificationSlot).then(() => { console.info("addSlot success"); }); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(type: SlotType, callback: AsyncCallback\): void @@ -517,7 +501,7 @@ addSlot(type: SlotType, callback: AsyncCallback\): void **示例:** -```js +```ts // addslot回调 function addSlotCallBack(err) { if (err) { @@ -526,12 +510,10 @@ function addSlotCallBack(err) { console.info("addSlot success"); } } -Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack); +notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(type: SlotType): Promise\ @@ -555,15 +537,13 @@ addSlot(type: SlotType): Promise\ **示例:** -```js -Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { +```ts +notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION).then(() => { console.info("addSlot success"); }); ``` - - -## Notification.addSlots +## notificationManager.addSlots addSlots(slots: Array\, callback: AsyncCallback\): void @@ -592,7 +572,7 @@ addSlots(slots: Array\, callback: AsyncCallback\): voi **示例:** -```js +```ts // addSlots回调 function addSlotsCallBack(err) { if (err) { @@ -603,18 +583,16 @@ function addSlotsCallBack(err) { } // 通知slot对象 let notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION + type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; // 通知slot array 对象 let notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; -Notification.addSlots(notificationSlotArray, addSlotsCallBack); +notificationManager.addSlots(notificationSlotArray, addSlotsCallBack); ``` - - -## Notification.addSlots +## notificationManager.addSlots addSlots(slots: Array\): Promise\ @@ -642,23 +620,21 @@ addSlots(slots: Array\): Promise\ **示例:** -```js +```ts // 通知slot对象 let notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION + type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; // 通知slot array 对象 let notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; -Notification.addSlots(notificationSlotArray).then(() => { +notificationManager.addSlots(notificationSlotArray).then(() => { console.info("addSlots success"); }); ``` - - -## Notification.getSlot +## notificationManager.getSlot getSlot(slotType: SlotType, callback: AsyncCallback\): void @@ -683,7 +659,7 @@ getSlot(slotType: SlotType, callback: AsyncCallback\): void **示例:** -```js +```ts // getSlot回调 function getSlotCallback(err,data) { if (err) { @@ -692,13 +668,11 @@ function getSlotCallback(err,data) { console.info("getSlot success"); } } -let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.getSlot(slotType, getSlotCallback); +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.getSlot(slotType, getSlotCallback); ``` - - -## Notification.getSlot +## notificationManager.getSlot getSlot(slotType: SlotType): Promise\ @@ -728,16 +702,14 @@ getSlot(slotType: SlotType): Promise\ **示例:** -```js -let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.getSlot(slotType).then((data) => { +```ts +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.getSlot(slotType).then((data) => { console.info("getSlot success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getSlots +## notificationManager.getSlots getSlots(callback: AsyncCallback>): void @@ -761,7 +733,7 @@ getSlots(callback: AsyncCallback>): void **示例:** -```js +```ts // getSlots回调 function getSlotsCallback(err,data) { if (err) { @@ -770,12 +742,10 @@ function getSlotsCallback(err,data) { console.info("getSlots success"); } } -Notification.getSlots(getSlotsCallback); +notificationManager.getSlots(getSlotsCallback); ``` - - -## Notification.getSlots +## notificationManager.getSlots getSlots(): Promise\> @@ -799,15 +769,13 @@ getSlots(): Promise\> **示例:** -```js -Notification.getSlots().then((data) => { +```ts +notificationManager.getSlots().then((data) => { console.info("getSlots success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.removeSlot +## notificationManager.removeSlot removeSlot(slotType: SlotType, callback: AsyncCallback\): void @@ -832,7 +800,7 @@ removeSlot(slotType: SlotType, callback: AsyncCallback\): void **示例:** -```js +```ts // removeSlot回调 function removeSlotCallback(err) { if (err) { @@ -841,13 +809,11 @@ function removeSlotCallback(err) { console.info("removeSlot success"); } } -let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.removeSlot(slotType,removeSlotCallback); +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.removeSlot(slotType,removeSlotCallback); ``` - - -## Notification.removeSlot +## notificationManager.removeSlot removeSlot(slotType: SlotType): Promise\ @@ -871,16 +837,14 @@ removeSlot(slotType: SlotType): Promise\ **示例:** -```js -let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.removeSlot(slotType).then(() => { +```ts +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.removeSlot(slotType).then(() => { console.info("removeSlot success"); }); ``` - - -## Notification.removeAllSlots +## notificationManager.removeAllSlots removeAllSlots(callback: AsyncCallback\): void @@ -904,7 +868,7 @@ removeAllSlots(callback: AsyncCallback\): void **示例:** -```js +```ts function removeAllCallBack(err) { if (err) { console.info("removeAllSlots failed " + JSON.stringify(err)); @@ -912,12 +876,10 @@ function removeAllCallBack(err) { console.info("removeAllSlots success"); } } -Notification.removeAllSlots(removeAllCallBack); +notificationManager.removeAllSlots(removeAllCallBack); ``` - - -## Notification.removeAllSlots +## notificationManager.removeAllSlots removeAllSlots(): Promise\ @@ -935,15 +897,13 @@ removeAllSlots(): Promise\ **示例:** -```js -Notification.removeAllSlots().then(() => { +```ts +notificationManager.removeAllSlots().then(() => { console.info("removeAllSlots success"); }); ``` - - -## Notification.setNotificationEnable +## notificationManager.setNotificationEnable setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -974,7 +934,7 @@ setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCall **示例:** -```js +```ts function setNotificationEnablenCallback(err) { if (err) { console.info("setNotificationEnablenCallback failed " + JSON.stringify(err)); @@ -985,12 +945,10 @@ function setNotificationEnablenCallback(err) { let bundle = { bundle: "bundleName1", }; -Notification.setNotificationEnable(bundle, false, setNotificationEnablenCallback); +notificationManager.setNotificationEnable(bundle, false, setNotificationEnablenCallback); ``` - - -## Notification.setNotificationEnable +## notificationManager.setNotificationEnable setNotificationEnable(bundle: BundleOption, enable: boolean): Promise\ @@ -1020,18 +978,16 @@ setNotificationEnable(bundle: BundleOption, enable: boolean): Promise\ **示例:** -```js +```ts let bundle = { bundle: "bundleName1", }; -Notification.setNotificationEnable(bundle, false).then(() => { +notificationManager.setNotificationEnable(bundle, false).then(() => { console.info("setNotificationEnable success"); }); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void @@ -1061,7 +1017,7 @@ isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): **示例:** -```js +```ts function isNotificationEnabledCallback(err, data) { if (err) { console.info("isNotificationEnabled failed " + JSON.stringify(err)); @@ -1072,12 +1028,10 @@ function isNotificationEnabledCallback(err, data) { let bundle = { bundle: "bundleName1", }; -Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); +notificationManager.isNotificationEnabled(bundle, isNotificationEnabledCallback); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(bundle: BundleOption): Promise\ @@ -1112,18 +1066,16 @@ isNotificationEnabled(bundle: BundleOption): Promise\ **示例:** -```js +```ts let bundle = { bundle: "bundleName1", }; -Notification.isNotificationEnabled(bundle).then((data) => { +notificationManager.isNotificationEnabled(bundle).then((data) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(callback: AsyncCallback\): void @@ -1151,7 +1103,7 @@ isNotificationEnabled(callback: AsyncCallback\): void **示例:** -```js +```ts function isNotificationEnabledCallback(err, data) { if (err) { console.info("isNotificationEnabled failed " + JSON.stringify(err)); @@ -1160,12 +1112,10 @@ function isNotificationEnabledCallback(err, data) { } } -Notification.isNotificationEnabled(isNotificationEnabledCallback); +notificationManager.isNotificationEnabled(isNotificationEnabledCallback); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(): Promise\ @@ -1200,15 +1150,13 @@ isNotificationEnabled(): Promise\ **示例:** -```js -Notification.isNotificationEnabled().then((data) => { +```ts +notificationManager.isNotificationEnabled().then((data) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.displayBadge +## notificationManager.displayBadge displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -1239,7 +1187,7 @@ displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\ @@ -1285,18 +1231,16 @@ displayBadge(bundle: BundleOption, enable: boolean): Promise\ **示例:** -```js +```ts let bundle = { bundle: "bundleName1", }; -Notification.displayBadge(bundle, false).then(() => { +notificationManager.displayBadge(bundle, false).then(() => { console.info("displayBadge success"); }); ``` - - -## Notification.isBadgeDisplayed +## notificationManager.isBadgeDisplayed isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void @@ -1326,7 +1270,7 @@ isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void **示例:** -```js +```ts function isBadgeDisplayedCallback(err, data) { if (err) { console.info("isBadgeDisplayed failed " + JSON.stringify(err)); @@ -1337,12 +1281,10 @@ function isBadgeDisplayedCallback(err, data) { let bundle = { bundle: "bundleName1", }; -Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); +notificationManager.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); ``` - - -## Notification.isBadgeDisplayed +## notificationManager.isBadgeDisplayed isBadgeDisplayed(bundle: BundleOption): Promise\ @@ -1377,18 +1319,16 @@ isBadgeDisplayed(bundle: BundleOption): Promise\ **示例:** -```js +```ts let bundle = { bundle: "bundleName1", }; -Notification.isBadgeDisplayed(bundle).then((data) => { +notificationManager.isBadgeDisplayed(bundle).then((data) => { console.info("isBadgeDisplayed success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.setSlotByBundle +## notificationManager.setSlotByBundle setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void @@ -1417,11 +1357,9 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCal | 1600003 | Failed to connect service. | | 17700001 | The specified bundle name was not found. | - - **示例:** -```js +```ts function setSlotByBundleCallback(err) { if (err) { console.info("setSlotByBundle failed " + JSON.stringify(err)); @@ -1433,14 +1371,12 @@ let bundle = { bundle: "bundleName1", }; let notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION + type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; -Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); +notificationManager.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); ``` - - -## Notification.setSlotByBundle +## notificationManager.setSlotByBundle setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ @@ -1470,21 +1406,19 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ **示例:** -```js +```ts let bundle = { bundle: "bundleName1", }; let notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION + type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; -Notification.setSlotByBundle(bundle, notificationSlot).then(() => { +notificationManager.setSlotByBundle(bundle, notificationSlot).then(() => { console.info("setSlotByBundle success"); }); ``` - - -## Notification.getSlotsByBundle +## notificationManager.getSlotsByBundle getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void @@ -1514,7 +1448,7 @@ getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback> @@ -1565,18 +1497,16 @@ getSlotsByBundle(bundle: BundleOption): Promise> **示例:** -```js +```ts let bundle = { bundle: "bundleName1", }; -Notification.getSlotsByBundle(bundle).then((data) => { +notificationManager.getSlotsByBundle(bundle).then((data) => { console.info("getSlotsByBundle success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getSlotNumByBundle +## notificationManager.getSlotNumByBundle getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void @@ -1606,7 +1536,7 @@ getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): voi **示例:** -```js +```ts function getSlotNumByBundleCallback(err, data) { if (err) { console.info("getSlotNumByBundle failed " + JSON.stringify(err)); @@ -1617,12 +1547,10 @@ function getSlotNumByBundleCallback(err, data) { let bundle = { bundle: "bundleName1", }; -Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); +notificationManager.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); ``` - - -## Notification.getSlotNumByBundle +## notificationManager.getSlotNumByBundle getSlotNumByBundle(bundle: BundleOption): Promise\ @@ -1657,19 +1585,17 @@ getSlotNumByBundle(bundle: BundleOption): Promise\ **示例:** -```js +```ts let bundle = { bundle: "bundleName1", }; -Notification.getSlotNumByBundle(bundle).then((data) => { +notificationManager.getSlotNumByBundle(bundle).then((data) => { console.info("getSlotNumByBundle success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getAllActiveNotifications +## notificationManager.getAllActiveNotifications getAllActiveNotifications(callback: AsyncCallback>): void @@ -1697,7 +1623,7 @@ getAllActiveNotifications(callback: AsyncCallback>) **示例:** -```js +```ts function getAllActiveNotificationsCallback(err, data) { if (err) { console.info("getAllActiveNotifications failed " + JSON.stringify(err)); @@ -1706,12 +1632,10 @@ function getAllActiveNotificationsCallback(err, data) { } } -Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); +notificationManager.getAllActiveNotifications(getAllActiveNotificationsCallback); ``` - - -## Notification.getAllActiveNotifications +## notificationManager.getAllActiveNotifications getAllActiveNotifications(): Promise\\> @@ -1739,15 +1663,13 @@ getAllActiveNotifications(): Promise\ { +```ts +notificationManager.getAllActiveNotifications().then((data) => { console.info("getAllActiveNotifications success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getActiveNotificationCount +## notificationManager.getActiveNotificationCount getActiveNotificationCount(callback: AsyncCallback\): void @@ -1771,7 +1693,7 @@ getActiveNotificationCount(callback: AsyncCallback\): void **示例:** -```js +```ts function getActiveNotificationCountCallback(err, data) { if (err) { console.info("getActiveNotificationCount failed " + JSON.stringify(err)); @@ -1780,12 +1702,10 @@ function getActiveNotificationCountCallback(err, data) { } } -Notification.getActiveNotificationCount(getActiveNotificationCountCallback); +notificationManager.getActiveNotificationCount(getActiveNotificationCountCallback); ``` - - -## Notification.getActiveNotificationCount +## notificationManager.getActiveNotificationCount getActiveNotificationCount(): Promise\ @@ -1809,15 +1729,13 @@ getActiveNotificationCount(): Promise\ **示例:** -```js -Notification.getActiveNotificationCount().then((data) => { +```ts +notificationManager.getActiveNotificationCount().then((data) => { console.info("getActiveNotificationCount success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getActiveNotifications +## notificationManager.getActiveNotifications getActiveNotifications(callback: AsyncCallback>): void @@ -1841,7 +1759,7 @@ getActiveNotifications(callback: AsyncCallback>): v **示例:** -```js +```ts function getActiveNotificationsCallback(err, data) { if (err) { console.info("getActiveNotifications failed " + JSON.stringify(err)); @@ -1850,12 +1768,10 @@ function getActiveNotificationsCallback(err, data) { } } -Notification.getActiveNotifications(getActiveNotificationsCallback); +notificationManager.getActiveNotifications(getActiveNotificationsCallback); ``` - - -## Notification.getActiveNotifications +## notificationManager.getActiveNotifications getActiveNotifications(): Promise\\> @@ -1879,15 +1795,13 @@ getActiveNotifications(): Promise\ { +```ts +notificationManager.getActiveNotifications().then((data) => { console.info("removeGroupByBundle success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.cancelGroup +## notificationManager.cancelGroup cancelGroup(groupName: string, callback: AsyncCallback\): void @@ -1912,7 +1826,7 @@ cancelGroup(groupName: string, callback: AsyncCallback\): void **示例:** -```js +```ts function cancelGroupCallback(err) { if (err) { console.info("cancelGroup failed " + JSON.stringify(err)); @@ -1923,12 +1837,10 @@ function cancelGroupCallback(err) { let groupName = "GroupName"; -Notification.cancelGroup(groupName, cancelGroupCallback); +notificationManager.cancelGroup(groupName, cancelGroupCallback); ``` - - -## Notification.cancelGroup +## notificationManager.cancelGroup cancelGroup(groupName: string): Promise\ @@ -1952,16 +1864,14 @@ cancelGroup(groupName: string): Promise\ **示例:** -```js +```ts let groupName = "GroupName"; -Notification.cancelGroup(groupName).then(() => { +notificationManager.cancelGroup(groupName).then(() => { console.info("cancelGroup success"); }); ``` - - -## Notification.removeGroupByBundle +## notificationManager.removeGroupByBundle removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void @@ -1992,7 +1902,7 @@ removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCall **示例:** -```js +```ts function removeGroupByBundleCallback(err) { if (err) { console.info("removeGroupByBundle failed " + JSON.stringify(err)); @@ -2004,12 +1914,10 @@ function removeGroupByBundleCallback(err) { let bundleOption = {bundle: "Bundle"}; let groupName = "GroupName"; -Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); +notificationManager.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); ``` - - -## Notification.removeGroupByBundle +## notificationManager.removeGroupByBundle removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ @@ -2039,17 +1947,15 @@ removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ **示例:** -```js +```ts let bundleOption = {bundle: "Bundle"}; let groupName = "GroupName"; -Notification.removeGroupByBundle(bundleOption, groupName).then(() => { +notificationManager.removeGroupByBundle(bundleOption, groupName).then(() => { console.info("removeGroupByBundle success"); }); ``` - - -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): void @@ -2078,7 +1984,7 @@ setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): vo **示例:** -```js +```ts function setDoNotDisturbDateCallback(err) { if (err) { console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2088,17 +1994,15 @@ function setDoNotDisturbDateCallback(err) { } let doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) }; -Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); +notificationManager.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); ``` - - -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ @@ -2126,19 +2030,19 @@ setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ **示例:** -```js +```ts let doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) }; -Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { +notificationManager.setDoNotDisturbDate(doNotDisturbDate).then(() => { console.info("setDoNotDisturbDate success"); }); ``` -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallback\): void @@ -2169,7 +2073,7 @@ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallb **示例:** -```js +```ts function setDoNotDisturbDateCallback(err) { if (err) { console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2179,19 +2083,17 @@ function setDoNotDisturbDateCallback(err) { } let doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) }; let userId = 1; -Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); +notificationManager.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); ``` - - -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ @@ -2221,22 +2123,22 @@ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ **示例:** -```js +```ts let doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) }; let userId = 1; -Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { +notificationManager.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { console.info("setDoNotDisturbDate success"); }); ``` -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(callback: AsyncCallback\): void @@ -2264,7 +2166,7 @@ getDoNotDisturbDate(callback: AsyncCallback\): void **示例:** -```js +```ts function getDoNotDisturbDateCallback(err,data) { if (err) { console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2273,12 +2175,10 @@ function getDoNotDisturbDateCallback(err,data) { } } -Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); +notificationManager.getDoNotDisturbDate(getDoNotDisturbDateCallback); ``` - - -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(): Promise\ @@ -2306,14 +2206,14 @@ getDoNotDisturbDate(): Promise\ **示例:** -```js -Notification.getDoNotDisturbDate().then((data) => { +```ts +notificationManager.getDoNotDisturbDate().then((data) => { console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(userId: number, callback: AsyncCallback\): void @@ -2343,7 +2243,7 @@ getDoNotDisturbDate(userId: number, callback: AsyncCallback\) **示例:** -```js +```ts function getDoNotDisturbDateCallback(err,data) { if (err) { console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2354,12 +2254,10 @@ function getDoNotDisturbDateCallback(err,data) { let userId = 1; -Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); +notificationManager.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); ``` - - -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(userId: number): Promise\ @@ -2394,16 +2292,16 @@ getDoNotDisturbDate(userId: number): Promise\ **示例:** -```js +```ts let userId = 1; -Notification.getDoNotDisturbDate(userId).then((data) => { +notificationManager.getDoNotDisturbDate(userId).then((data) => { console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` -## Notification.supportDoNotDisturbMode +## notificationManager.supportDoNotDisturbMode supportDoNotDisturbMode(callback: AsyncCallback\): void @@ -2431,7 +2329,7 @@ supportDoNotDisturbMode(callback: AsyncCallback\): void **示例:** -```js +```ts function supportDoNotDisturbModeCallback(err,data) { if (err) { console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); @@ -2440,12 +2338,10 @@ function supportDoNotDisturbModeCallback(err,data) { } } -Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); +notificationManager.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); ``` - - -## Notification.supportDoNotDisturbMode +## notificationManager.supportDoNotDisturbMode supportDoNotDisturbMode(): Promise\ @@ -2473,15 +2369,13 @@ supportDoNotDisturbMode(): Promise\ **示例:** -```js -Notification.supportDoNotDisturbMode().then((data) => { +```ts +notificationManager.supportDoNotDisturbMode().then((data) => { console.info("supportDoNotDisturbMode success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.isSupportTemplate +## notificationManager.isSupportTemplate isSupportTemplate(templateName: string, callback: AsyncCallback\): void @@ -2517,12 +2411,10 @@ function isSupportTemplateCallback(err, data) { } } -Notification.isSupportTemplate(templateName, isSupportTemplateCallback); +notificationManager.isSupportTemplate(templateName, isSupportTemplateCallback); ``` - - -## Notification.isSupportTemplate +## notificationManager.isSupportTemplate isSupportTemplate(templateName: string): Promise\ @@ -2556,14 +2448,12 @@ isSupportTemplate(templateName: string): Promise\ ```javascript let templateName = 'process'; -Notification.isSupportTemplate(templateName).then((data) => { +notificationManager.isSupportTemplate(templateName).then((data) => { console.info("isSupportTemplate success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.requestEnableNotification +## notificationManager.requestEnableNotification requestEnableNotification(callback: AsyncCallback\): void @@ -2596,12 +2486,10 @@ function requestEnableNotificationCallback(err) { } }; -Notification.requestEnableNotification(requestEnableNotificationCallback); +notificationManager.requestEnableNotification(requestEnableNotificationCallback); ``` - - -## Notification.requestEnableNotification +## notificationManager.requestEnableNotification requestEnableNotification(): Promise\ @@ -2620,14 +2508,14 @@ requestEnableNotification(): Promise\ **示例:** ```javascript -Notification.requestEnableNotification().then(() => { +notificationManager.requestEnableNotification().then(() => { console.info("requestEnableNotification success"); }); ``` -## Notification.setDistributedEnable +## notificationManager.setDistributedEnable setDistributedEnable(enable: boolean, callback: AsyncCallback\): void @@ -2668,12 +2556,10 @@ function setDistributedEnableCallback() { let enable = true; -Notification.setDistributedEnable(enable, setDistributedEnableCallback); +notificationManager.setDistributedEnable(enable, setDistributedEnableCallback); ``` - - -## Notification.setDistributedEnable +## notificationManager.setDistributedEnable setDistributedEnable(enable: boolean): Promise\ @@ -2705,13 +2591,13 @@ setDistributedEnable(enable: boolean): Promise\ ```javascript let enable = true; -Notification.setDistributedEnable(enable).then(() => { +notificationManager.setDistributedEnable(enable).then(() => { console.info("setDistributedEnable success"); }); ``` -## Notification.isDistributedEnabled +## notificationManager.isDistributedEnabled isDistributedEnabled(callback: AsyncCallback\): void @@ -2745,12 +2631,12 @@ function isDistributedEnabledCallback(err, data) { } }; -Notification.isDistributedEnabled(isDistributedEnabledCallback); +notificationManager.isDistributedEnabled(isDistributedEnabledCallback); ``` -## Notification.isDistributedEnabled +## notificationManager.isDistributedEnabled isDistributedEnabled(): Promise\ @@ -2776,14 +2662,14 @@ isDistributedEnabled(): Promise\ **示例:** ```javascript -Notification.isDistributedEnabled() +notificationManager.isDistributedEnabled() .then((data) => { console.info("isDistributedEnabled success, data: " + JSON.stringify(data)); }); ``` -## Notification.setDistributedEnableByBundle +## notificationManager.setDistributedEnableByBundle setDistributedEnableByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -2830,12 +2716,12 @@ let bundle = { let enable = true -Notification.setDistributedEnableByBundle(bundle, enable, setDistributedEnableByBundleCallback); +notificationManager.setDistributedEnableByBundle(bundle, enable, setDistributedEnableByBundleCallback); ``` -## Notification.setDistributedEnableByBundle +## notificationManager.setDistributedEnableByBundle setDistributedEnableByBundle(bundle: BundleOption, enable: boolean): Promise\ @@ -2873,12 +2759,12 @@ let bundle = { let enable = true -Notification.setDistributedEnableByBundle(bundle, enable).then(() => { - console.info("setDistributedEnableByBundle success"); - }); +notificationManager.setDistributedEnableByBundle(bundle, enable).then(() => { + console.info("setDistributedEnableByBundle success"); +}); ``` -## Notification.isDistributedEnabledByBundle +## notificationManager.isDistributedEnabledByBundle isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\): void @@ -2922,12 +2808,10 @@ let bundle = { bundle: "bundleName1", }; -Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); +notificationManager.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); ``` - - -## Notification.isDistributedEnabledByBundle +## notificationManager.isDistributedEnabledByBundle isDistributedEnabledByBundle(bundle: BundleOption): Promise\ @@ -2968,13 +2852,13 @@ let bundle = { bundle: "bundleName1", }; -Notification.isDistributedEnabledByBundle(bundle).then((data) => { +notificationManager.isDistributedEnabledByBundle(bundle).then((data) => { console.info("isDistributedEnabledByBundle success, data: " + JSON.stringify(data)); }); ``` -## Notification.getDeviceRemindType +## notificationManager.getDeviceRemindType getDeviceRemindType(callback: AsyncCallback\): void @@ -3011,12 +2895,10 @@ function getDeviceRemindTypeCallback(err, data) { } }; -Notification.getDeviceRemindType(getDeviceRemindTypeCallback); +notificationManager.getDeviceRemindType(getDeviceRemindTypeCallback); ``` - - -## Notification.getDeviceRemindType +## notificationManager.getDeviceRemindType getDeviceRemindType(): Promise\ @@ -3045,13 +2927,13 @@ getDeviceRemindType(): Promise\ **示例:** ```javascript -Notification.getDeviceRemindType().then((data) => { +notificationManager.getDeviceRemindType().then((data) => { console.info("getDeviceRemindType success, data: " + JSON.stringify(data)); }); ``` -## Notification.publishAsBundle +## notificationManager.publishAsBundle publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number, callback: AsyncCallback\): void @@ -3086,7 +2968,7 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user **示例:** -```js +```ts //publishAsBundle回调 function callback(err) { if (err) { @@ -3103,7 +2985,7 @@ let userId = 100; let request = { id: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -3112,10 +2994,10 @@ let request = { } }; -Notification.publishAsBundle(request, representativeBundle, userId, callback); +notificationManager.publishAsBundle(request, representativeBundle, userId, callback); ``` -## Notification.publishAsBundle +## notificationManager.publishAsBundle publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number): Promise\ @@ -3150,7 +3032,7 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user **示例:** -```js +```ts // 被代理应用的包名 let representativeBundle = "com.example.demo"; // 用户ID @@ -3159,7 +3041,7 @@ let userId = 100; let request = { id: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -3168,12 +3050,12 @@ let request = { } }; -Notification.publishAsBundle(request, representativeBundle, userId).then(() => { +notificationManager.publishAsBundle(request, representativeBundle, userId).then(() => { console.info("publishAsBundle success"); }); ``` -## Notification.cancelAsBundle +## notificationManager.cancelAsBundle cancelAsBundle(id: number, representativeBundle: string, userId: number, callback: AsyncCallback\): void @@ -3208,7 +3090,7 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number, callbac **示例:** -```js +```ts // cancelAsBundle function cancelAsBundleCallback(err) { if (err) { @@ -3222,10 +3104,10 @@ let representativeBundle = "com.example.demo"; // 用户ID let userId = 100; -Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); +notificationManager.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); ``` -## Notification.cancelAsBundle +## notificationManager.cancelAsBundle cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise\ @@ -3259,18 +3141,18 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number): Promis **示例:** -```js +```ts // 被代理应用的包名 let representativeBundle = "com.example.demo"; // 用户ID let userId = 100; -Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { +notificationManager.cancelAsBundle(0, representativeBundle, userId).then(() => { console.info("cancelAsBundle success"); }); ``` -## Notification.setNotificationEnableSlot +## notificationManager.setNotificationEnableSlot setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback\): void @@ -3302,7 +3184,7 @@ setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, **示例:** -```js +```ts // setNotificationEnableSlot function setNotificationEnableSlotCallback(err) { if (err) { @@ -3312,14 +3194,14 @@ function setNotificationEnableSlotCallback(err) { } }; -Notification.setNotificationEnableSlot( +notificationManager.setNotificationEnableSlot( { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, + notificationManager.SlotType.SOCIAL_COMMUNICATION, true, setNotificationEnableSlotCallback); ``` -## Notification.setNotificationEnableSlot +## notificationManager.setNotificationEnableSlot setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise\ @@ -3350,17 +3232,17 @@ setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean) **示例:** -```js +```ts // setNotificationEnableSlot -Notification.setNotificationEnableSlot( +notificationManager.setNotificationEnableSlot( { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, + notificationManager.SlotType.SOCIAL_COMMUNICATION, true).then(() => { console.info("setNotificationEnableSlot success"); }); ``` -## Notification.isNotificationSlotEnabled +## notificationManager.isNotificationSlotEnabled isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback\): void @@ -3391,7 +3273,7 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncC **示例:** -```js +```ts // isNotificationSlotEnabled function getEnableSlotCallback(err, data) { if (err) { @@ -3401,13 +3283,13 @@ function getEnableSlotCallback(err, data) { } }; -Notification.isNotificationSlotEnabled( +notificationManager.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, + notificationManager.SlotType.SOCIAL_COMMUNICATION, getEnableSlotCallback); ``` -## Notification.isNotificationSlotEnabled +## notificationManager.isNotificationSlotEnabled isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ @@ -3443,16 +3325,16 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ { +notificationManager.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, + notificationManager.SlotType.SOCIAL_COMMUNICATION).then((data) => { console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); }); ``` -## Notification.setSyncNotificationEnabledWithoutApp +## notificationManager.setSyncNotificationEnabledWithoutApp setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: AsyncCallback\): void @@ -3483,7 +3365,7 @@ setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: **示例:** -```js +```ts let userId = 100; let enable = true; @@ -3495,11 +3377,11 @@ function callback(err) { } } -Notification.setSyncNotificationEnabledWithoutApp(userId, enable, callback); +notificationManager.setSyncNotificationEnabledWithoutApp(userId, enable, callback); ``` -## Notification.setSyncNotificationEnabledWithoutApp +## notificationManager.setSyncNotificationEnabledWithoutApp setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\ @@ -3535,11 +3417,11 @@ setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\< **示例:** -```js +```ts let userId = 100; let enable = true; -Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { +notificationManager.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { console.info('setSyncNotificationEnabledWithoutApp success'); }).catch((err) => { console.info('setSyncNotificationEnabledWithoutApp, err:' + JSON.stringify(err)); @@ -3547,7 +3429,7 @@ Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { ``` -## Notification.getSyncNotificationEnabledWithoutApp +## notificationManager.getSyncNotificationEnabledWithoutApp getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void @@ -3577,7 +3459,7 @@ getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\ @@ -3627,21 +3509,16 @@ getSyncNotificationEnabledWithoutApp(userId: number): Promise\ **示例:** -```js +```ts let userId = 100; -Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { +notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => { console.info('getSyncNotificationEnabledWithoutApp, data:' + data); }).catch((err) => { console.info('getSyncNotificationEnabledWithoutApp, err:' + err); }); - .catch((err) => { - console.info('getSyncNotificationEnabledWithoutApp, err:', err); - }); ``` - - ## DoNotDisturbDate **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification @@ -3654,8 +3531,6 @@ Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { | begin | Date | 是 | 是 | 免打扰设置的起点时间。 | | end | Date | 是 | 是 | 免打扰设置的终点时间。 | - - ## DoNotDisturbType **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification diff --git a/zh-cn/application-dev/reference/apis/js-apis-router.md b/zh-cn/application-dev/reference/apis/js-apis-router.md index c53ab60fd9e87d85f752233495ae74c39372b062..fb47d3bf1013fb5e21e1c2369f02a8ecbabf7814 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -47,25 +47,21 @@ pushUrl(options: RouterOptions): Promise<void> **示例:** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); }) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; ``` ## router.pushUrl9+ @@ -96,25 +92,21 @@ pushUrl(options: RouterOptions, callback: AsyncCallback<void>): void **示例:** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } - } - }, (err) => { - if (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - return; +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - console.info('pushUrl success'); - }); -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.pushUrl9+ @@ -135,7 +127,7 @@ pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> | 类型 | 说明 | | ------------------- | --------- | -| Promise<void> | 异常返回结果 | +| Promise<void> | 异常返回结果。 | **错误码:** @@ -150,25 +142,21 @@ pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> **示例:** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - }, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.pushUrl9+ @@ -185,7 +173,7 @@ pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<voi | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | 是 | 跳转页面描述信息。 | | mode | [RouterMode](#routermode9) | 是 | 跳转页面使用的模式。 | -| callback | AsyncCallback<void> | 是 | 异常响应回调。 | +| callback | AsyncCallback<void> | 是 | 异常响应回调。 | **错误码:** @@ -200,25 +188,21 @@ pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<voi **示例:** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } - } - }, router.RouterMode.Standard, (err) => { - if (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - return; +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - console.info('pushUrl success'); - }); -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); +}) ``` ## router.replaceUrl9+ @@ -253,22 +237,18 @@ replaceUrl(options: RouterOptions): Promise<void> **示例:** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); }) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; ``` ## router.replaceUrl9+ @@ -284,7 +264,7 @@ replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ------------------ | | options | [RouterOptions](#routeroptions) | 是 | 替换页面描述信息。 | -| callback | AsyncCallback<void> | 是 | 异常响应回调。 | +| callback | AsyncCallback<void> | 是 | 异常响应回调。 | **错误码:** @@ -298,22 +278,18 @@ replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void **示例:** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } - }, (err) => { - if (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - return; - } - console.info('replaceUrl success'); - }); -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); +}) ``` ## router.replaceUrl9+ @@ -350,22 +326,18 @@ replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void> **示例:** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } - }, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.replaceUrl9+ @@ -382,7 +354,7 @@ replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback< | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | 是 | 替换页面描述信息。 | | mode | [RouterMode](#routermode9) | 是 | 跳转页面使用的模式。 | -| callback | AsyncCallback<void> | 是 | 异常响应回调。 | +| callback | AsyncCallback<void> | 是 | 异常响应回调。 | **错误码:** @@ -396,22 +368,19 @@ replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback< **示例:** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } - }, router.RouterMode.Standard, (err) => { - if (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - return; - } - console.info('replaceUrl success'); - }); -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); +}); + ``` ## router.back @@ -571,9 +540,9 @@ getParams(): Object **返回值:** -| 类型 | 说明 | -| ------ | ----------------- | -| Object | 发起跳转的页面往当前页传入的参数。 | +| 类型 | 说明 | +| ------ | ---------------------------------- | +| object | 发起跳转的页面往当前页传入的参数。 | **示例:** @@ -636,7 +605,7 @@ export default { ### 基于TS扩展的声明式开发范式 ```ts -// 通过router.push跳转至目标页携带params参数 +// 通过router.pushUrl跳转至目标页携带params参数 import router from '@ohos.router' @Entry diff --git a/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md b/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md index cc3bb710fece0df42ef6c372aa349156953abd10..5bbab366210ab5c920f97732f24d33e47f037468 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md +++ b/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @@ -226,7 +226,7 @@ screenlock.lock().then((data) => { onSystemEvent(callback: Callback<SystemEvent>): boolean -注册锁屏相关的系统事件。 +注册锁屏相关的系统事件,仅系统锁屏应用可调用。 **系统能力:** SystemCapability.MiscServices.ScreenLock diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-notification.md b/zh-cn/application-dev/reference/apis/js-apis-system-notification.md index 56b7b9504fe0f1429b326ba9dd61c65f03d7dca5..90e659026163849de506824f05de742aa919db44 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-notification.md @@ -9,7 +9,7 @@ ## 导入模块 -``` +```ts import notification from '@system.notification'; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-router.md b/zh-cn/application-dev/reference/apis/js-apis-system-router.md index 7a3d9399029f974f996ecd04f75f121f1e94e81d..85d9bb0e2f3cb6053688da9413fd5a0e58d90f28 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-router.md @@ -395,6 +395,6 @@ export default { ## ParamsInterface -| 名称 | 参数类型 | 说明 | -| ------------- | ------ | ------- | -| [key: string] | Object | 路由参数列表。 | +| 名称 | 参数类型 | 说明 | +| ------------- | -------- | -------------- | +| [key: string] | object | 路由参数列表。 | 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 3add4b31bc7a98cb81029334d4e6ae31461a3f40..7f662943e812c30633716158082c73c2c28fa23a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md +++ b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md @@ -1,6 +1,12 @@ # @ohos.taskpool(使用任务池) -taskpool作用是为应用程序提供一个多线程的运行环境,可以降低整体资源的消耗、提高系统的整体性能,且用户无需关心线程实例的生命周期。 +任务池(taskpool)作用是为应用程序提供一个多线程的运行环境,降低整体资源的消耗、提高系统的整体性能,且您无需关心线程实例的生命周期。您可以使用任务池API创建后台任务(Task),并对所创建的任务进行如任务执行、任务取消的操作。理论上您可以使用任务池API创建数量不受限制的任务,但是出于内存因素不建议您这样做。此外,不建议您在任务中执行阻塞操作,特别是无限期阻塞操作,长时间的阻塞操作占据工作线程,可能会阻塞其他任务调度,影响您的应用性能。 + +您所创建的同一优先级任务的执行顺序可以由您决定,任务真实执行的顺序与您调用任务池API提供的任务执行接口顺序一致。任务默认优先级是MEDIUM。(任务优先级机制暂未支持) + +当同一时间待执行的任务数量大于任务池工作线程数量,任务池会根据负载均衡机制进行扩容,增加工作线程数量,减少整体等待时长。同样,当执行的任务数量减少,工作线程数量大于执行任务数量,部分工作线程处于空闲状态,任务池会根据负载均衡机制进行缩容,减少工作线程数量。(负载均衡机制暂未支持) + +任务池API以数字形式返回错误码。有关各个错误码的更多信息,请参阅文档[语言基础类库错误码](../errorcodes/errorcode-utils.md)。 > **说明:**
> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -37,10 +43,10 @@ Task的构造函数。 **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | ------------------------ | -| func | Function | 是 | 任务执行需要传入函数。 | -| args | unknown[] | 否 | 任务执行传入函数的参数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | -------------------------------------------------------------------- | +| func | Function | 是 | 任务执行需要传入函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 | +| args | unknown[] | 否 | 任务执行传入函数的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。 | **错误码:** @@ -65,10 +71,10 @@ let task = new taskpool.Task(func, "this is my first Task"); **系统能力:** SystemCapability.Utils.Lang -| 名称 | 类型 | 可读 | 可写 | 说明 | -| --------- | --------- | ---- | ---- | ---------------------------- | -| function | Function | 是 | 是 | 创建任务时需要传入的函数。 | -| arguments | unknown[] | 是 | 是 | 创建任务传入函数所需的参数。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- | +| function | Function | 是 | 是 | 创建任务时需要传入的函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 | +| arguments | unknown[] | 是 | 是 | 创建任务传入函数所需的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。 | ## taskpool.execute @@ -80,10 +86,10 @@ execute(func: Function, ...args: unknown[]): Promise\ **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | ---------------------------- | -| func | Function | 是 | 执行的逻辑需要传入函数。 | -| args | unknown[] | 否 | 执行逻辑的函数所需要的参数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| func | Function | 是 | 执行的逻辑需要传入函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 | +| args | unknown[] | 否 | 执行逻辑的函数所需要的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。 | **返回值:** @@ -190,4 +196,48 @@ function func(args) { let task = new taskpool.Task(func, "this is first Task"); let value = taskpool.execute(task); taskpool.cancel(task); +``` + +## 其他说明 + +### 序列化支持类型 +序列化支持类型包括:All Primitive Type(不包括symbol)、Date、String、RegExp、Array、Map、Set、Object、ArrayBuffer、TypedArray。 + +### 注意事项 +taskpool任务只支持引用入参传递或者import的变量,不支持使用闭包变量。 + +```js +// 1. 引用入参传递 +function func(args) { + "use concurrent" + console.log("func: " + args); + return args; +} + +let task = new taskpool.Task(func, "create task, then execute"); +let val1 = taskpool.execute(task); + +let val2 = taskpool.execute(func, "execute task by func"); +``` + +```js +// 2. 引用import变量 + +// b.ts +export var c = 2000; + +// a.ts +import { c } from './b' + +function test(a) { + "use concurrent" + console.log(a); + console.log(c); + return a; +} + +let task = new taskpool.Task(test, "create task, then execute"); +let val1 = taskpool.execute(task); + +let val2 = taskpool.execute(test, "execute task by func"); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-uitest.md b/zh-cn/application-dev/reference/apis/js-apis-uitest.md index 14a5dbb5d99f57f4ed84d0693d1bf055cc3131b3..2feec76275e6c49a61c8ebe6ef3dbd796234efac 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uitest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uitest.md @@ -70,12 +70,12 @@ import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern **系统能力**:SystemCapability.Test.UiTest -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------- | ------ | ---- | ---- | ------------------------- | -| leftX | number | 是 | 否 | 控件边框的左上角的X坐标。 | -| topY | number | 是 | 否 | 控件边框的左上角的Y坐标。 | -| rightX | number | 是 | 否 | 控件边框的右下角的X坐标。 | -| bottomY | number | 是 | 否 | 控件边框的右下角的Y坐标。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ------------------------- | +| left | number | 是 | 否 | 控件边框的左上角的X坐标。 | +| top | number | 是 | 否 | 控件边框的左上角的Y坐标。 | +| right | number | 是 | 否 | 控件边框的右下角的X坐标。 | +| bottom | number | 是 | 否 | 控件边框的右下角的Y坐标。 | ## WindowMode9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-uri.md b/zh-cn/application-dev/reference/apis/js-apis-uri.md index 57115ef96bff2cba26703eea847cc863910273ba..6cc9eef1eec4ebd8bc4a69a2cf7a1814150d1100 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uri.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uri.md @@ -35,7 +35,7 @@ import uri from '@ohos.uri' 标准uri定义由以下三个部分组成 [scheme:]scheme-specific-part[#fragment] -- Scheme: 协议名,必填。例如http、https、ftp、datashare、dataability等。 +- scheme: 协议名,根据需要填写。例如http、https、ftp、datashare、dataability等。 - scheme-specific-part: URI的特定解码方案特定部分,由[//][authority][path][?query]组成,根据需要填写。 - authority: URI的解码权限组件部分。由[userinfo@]host[:port]组成,根据需要填写。 - userinfo: 用户信息,根据需要填写。 @@ -226,7 +226,9 @@ checkIsAbsolute(): boolean ```js const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080?query=pppppp'); -uriInstance.checkIsAbsolute(); +console.log(uriInstance.checkIsAbsolute()); // true +const uriInstance1 = new uri.URI('xxx.com/suppliers.htm'); +console.log(uriInstance1.checkIsAbsolute()); // false ``` @@ -248,6 +250,7 @@ normalize(): URI ```js const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); +console.log(uriInstance.path); // /path/path1/../path2/./path3 let uriInstance1 = uriInstance.normalize(); -uriInstance1.path; +console.log(uriInstance1.path); // /path/path2/path3 ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-url.md b/zh-cn/application-dev/reference/apis/js-apis-url.md index ec114be507312696f8b629de996949f11cb82f2f..bf8455c9ba1840f357a8ddd7d1abc36d02187264 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-url.md +++ b/zh-cn/application-dev/reference/apis/js-apis-url.md @@ -369,7 +369,7 @@ console.log(params.toString()); ### 属性 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang +**系统能力:** SystemCapability.Utils.Lang | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | @@ -432,7 +432,7 @@ URL的无参构造函数。parseURL调用后返回一个URL对象,不单独使 **系统能力:** SystemCapability.Utils.Lang ### parseURL9+ - + static parseURL(url : string, base?: string | URL): URL URL静态成员函数。 @@ -514,7 +514,7 @@ URLSearchParams的构造函数。 > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+](#constructor9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.constructor9+](#constructor9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -542,7 +542,7 @@ append(name: string, value: string): void > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.append9+](#append9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.append9+](#append9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -569,7 +569,7 @@ delete(name: string): void > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.delete9+](#delete9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.delete9+](#delete9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -595,7 +595,7 @@ getAll(name: string): string[] > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.getAll9+](#getall9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.getAll9+](#getall9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -628,7 +628,7 @@ entries(): IterableIterator<[string, string]> > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.entries9+](#entries9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.entries9+](#entries9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -656,7 +656,7 @@ forEach(callbackFn: (value: string, key: string, searchParams: this) => void, th > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.forEach9+](#foreach9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.forEach9+](#foreach9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -693,7 +693,7 @@ get(name: string): string | null > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.get9+](#get9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.get9+](#get9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -727,7 +727,7 @@ has(name: string): boolean > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.has9+](#has9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.has9+](#has9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -760,7 +760,7 @@ set(name: string, value: string): void > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.set9+](#set9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.set9+](#set9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -788,7 +788,7 @@ sort(): void > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.sort9+](#sort9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.sort9+](#sort9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -809,7 +809,7 @@ keys(): IterableIterator<string> > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.keys9+](#keys9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.keys9+](#keys9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -837,7 +837,7 @@ values(): IterableIterator<string> > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams9+.values9+](#values9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.values9+](#values9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -865,7 +865,7 @@ for (var value of searchParams.values()) { > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[[Symbol.iterator]9+](#symboliterator9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.[Symbol.iterator]9+](#symboliterator9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -892,7 +892,7 @@ toString(): string > **说明:** > -> 从API version 7开始支持,从API version 9开始废弃,建议使用[tostring9+](#tostring9)替代。 +> 从API version 7开始支持,从API version 9开始废弃,建议使用[URLParams.tostring9+](#tostring9)替代。 **系统能力:** SystemCapability.Utils.Lang diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index 82942c94a9cc534b530c80aeac22556455a702fc..c50d6b23af161c2bbd9c58dc9e04a9b0fdbaea17 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -497,6 +497,7 @@ decode(input: Uint8Array, options?: { stream?: false }): string | -------- | -------- | -------- | -------- | -------- | | encoding | string | 是 | 否 | 编码格式,默认值是utf-8。 | + ### constructor constructor() @@ -3358,7 +3359,7 @@ constructor(capacity?: number) > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.constructor9+](#constructor9-3)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3382,7 +3383,7 @@ updateCapacity(newCapacity: number): void > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[updateCapacity9+](#updatecapacity9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.updateCapacity9+](#updatecapacity9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3407,7 +3408,7 @@ toString(): string > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[toString9+](#tostring9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.toString9+](#tostring9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3435,7 +3436,7 @@ getCapacity(): number > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getCapacity9+](#getcapacity9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.getCapacity9+](#getcapacity9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3459,7 +3460,7 @@ clear(): void > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[clear9+](#clear9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.clear9+](#clear9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3480,7 +3481,7 @@ getCreateCount(): number > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getCreateCount9+](#getcreatecount9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.getCreateCount9+](#getcreatecount9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3506,7 +3507,7 @@ getMissCount(): number > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getMissCount9+](#getmisscount9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.getMissCount9+](#getmisscount9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3533,7 +3534,7 @@ getRemovalCount(): number > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getRemovalCount9+](#getremovalcount9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.getRemovalCount9+](#getremovalcount9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3561,7 +3562,7 @@ getMatchCount(): number > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getMatchCount9+](#getmatchcount9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.getMatchCount9+](#getmatchcount9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3588,7 +3589,7 @@ getPutCount(): number > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getPutCount9+](#getputcount9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.getPutCount9+](#getputcount9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3614,7 +3615,7 @@ isEmpty(): boolean > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[isEmpty9+](#isempty9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.isEmpty9+](#isempty9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3640,7 +3641,7 @@ get(key: K): V | undefined > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[get9+](#get9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.get9+](#get9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3672,7 +3673,7 @@ put(key: K,value: V): V > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[put9+](#put9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.put9+](#put9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3704,7 +3705,7 @@ values(): V[] > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[values9+](#values9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.values9+](#values9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3732,7 +3733,7 @@ keys(): K[] > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[keys9+](#keys9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.keys9+](#keys9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3743,6 +3744,7 @@ keys(): K[] | K [] | 按升序返回当前缓冲区中所有键的列表,从最近访问到最近最少访问。 | **示例:** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -3757,7 +3759,7 @@ remove(key: K): V | undefined > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[remove9+](#remove9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.remove9+](#remove9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3788,7 +3790,7 @@ afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[afterRemoval9+](#afterremoval9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.afterRemoval9+](#afterremoval9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3832,7 +3834,7 @@ contains(key: K): boolean > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[contains9+](#contains9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.contains9+](#contains9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3864,7 +3866,7 @@ createDefault(key: K): V > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[createDefault9+](#createdefault9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.createDefault9+](#createdefault9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3895,7 +3897,7 @@ entries(): IterableIterator<[K,V]> > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[entries9+](#entries9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.entries9+](#entries9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3921,7 +3923,7 @@ entries(): IterableIterator<[K,V]> > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[Symbol.iterator9+](#symboliterator9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[LRUCache.Symbol.iterator9+](#symboliterator9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3953,7 +3955,7 @@ constructor(lowerObj: ScopeType, upperObj: ScopeType) > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.constructor9+](#constructor9-4)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -3980,7 +3982,7 @@ toString(): string > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[toString9+](#tostring9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.toString9+](#tostring9-1)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4007,7 +4009,7 @@ intersect(range: Scope): Scope > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[intersect9+](#intersect9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.intersect9+](#intersect9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4043,7 +4045,7 @@ intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[intersect9+](#intersect9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.intersect9+](#intersect9-1)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4079,7 +4081,7 @@ getUpper(): ScopeType > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getUpper9+](#getupper9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.getUpper9+](#getupper9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4106,7 +4108,7 @@ getLower(): ScopeType > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[getLower9+](#getlower9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.getLower9+](#getlower9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4133,7 +4135,7 @@ expand(lowerObj: ScopeType,upperObj: ScopeType): Scope > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[expand9+](#expand9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.expand9+](#expand9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4169,7 +4171,7 @@ expand(range: Scope): Scope > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[expand9+](#expand9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.expand9+](#expand9-1)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4205,7 +4207,7 @@ expand(value: ScopeType): Scope > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[expand9+](#expand9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.expand9+](#expand9-2)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4239,7 +4241,7 @@ contains(value: ScopeType): boolean > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[contains9+](#contains9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.contains9+](#contains9-1)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4273,7 +4275,7 @@ contains(range: Scope): boolean > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[contains9+](#contains9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.contains9+](#contains9-2)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4310,7 +4312,7 @@ clamp(value: ScopeType): ScopeType > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[clamp9+](#clamp9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[ScopeHelper.clamp9+](#clamp9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4351,7 +4353,7 @@ Base64的构造函数。 > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[Base64Helper.constructor9+](#constructor9-5)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4369,7 +4371,7 @@ encodeSync(src: Uint8Array): Uint8Array > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[encodeSync9+](#encodesync9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[Base64Helper.encodeSync9+](#encodesync9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4401,7 +4403,7 @@ encodeToStringSync(src: Uint8Array): string > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[encodeToStringSync9+](#encodetostringsync9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[Base64Helper.encodeToStringSync9+](#encodetostringsync9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4433,7 +4435,7 @@ decodeSync(src: Uint8Array | string): Uint8Array > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[decodeSync9+](#decodesync9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[Base64Helper.decodeSync9+](#decodesync9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4465,7 +4467,7 @@ encode(src: Uint8Array): Promise<Uint8Array> > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[encode9+](#encode9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[Base64Helper.encode9+](#encode9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4502,7 +4504,7 @@ encodeToString(src: Uint8Array): Promise<string> > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[encodeToString9+](#encodetostring9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[Base64Helper.encodeToString9+](#encodetostring9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4537,7 +4539,7 @@ decode(src: Uint8Array | string): Promise<Uint8Array> > **说明:** > -> 从API version 8开始支持,从API version 9开始废弃,建议使用[decode9+](#decode9)替代。 +> 从API version 8开始支持,从API version 9开始废弃,建议使用[Base64Helper.decode9+](#decode9)替代。 **系统能力:** SystemCapability.Utils.Lang @@ -4565,5 +4567,3 @@ decode(src: Uint8Array | string): Promise<Uint8Array> } }) ``` - - \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index fece8591420ed5a252dafd7d08e1704dd87f4eaf..70e2b7854890a1ffc9cb9063f12b4444a9210438 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -54,7 +54,7 @@ import window from '@ohos.window'; | ---------- | -------------------------- | -- | ----------------------------------- | | name | string | 是 | 窗口名字。 | | windowType | [WindowType](#windowtype7) | 是 | 窗口类型。 | -| ctx | BaseContext | 否 | 当前应用上下文信息。
FA模型的Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的Context定义见[ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)。不设置,则默认为空。
当Context为[ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)时,创建系统窗口。 | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | 否 | 当前应用上下文信息。不设置,则默认为空。
FA模型下不需要使用该参数,即可创建子窗口。
Stage模型下需要使用该参数,用于创建系统窗口。 | | displayId | number | 否 | 当前物理屏幕id。不设置,则默认为-1。 | | parentId | number | 否 | 父窗口id。不设置,则默认为-1。 | @@ -430,7 +430,7 @@ getLastWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | -- | ---------------------------------------- | -| ctx | BaseContext | 是 | 当前应用上下文信息。
FA模型的Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的Context定义见[Context](js-apis-ability-context.md)。 | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 当前应用上下文信息。 | | callback | AsyncCallback<[Window](#window)> | 是 | 回调函数。返回当前应用内最后显示的窗口对象。 | **错误码:** @@ -472,7 +472,7 @@ getLastWindow(ctx: BaseContext): Promise<Window> | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | 是 | 当前应用上下文信息。
FA模型的Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的Context定义见[Context](js-apis-ability-context.md)。 | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 当前应用上下文信息。 | **返回值:** @@ -897,9 +897,7 @@ promise.then((data)=> { create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback<Window>): void -创建子窗口,使用callback异步回调,其中Context详见[Context](js-apis-inner-app-context.md)。 - -从API version 9开始,当Context为[ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)时,创建系统窗口,使用callback异步回调。 +创建系统窗口,使用callback异步回调。 > **说明:** > @@ -909,12 +907,12 @@ create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback&l **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | 是 | 当前应用上下文信息。
FA模型的Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的Context定义见[ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)。 | -| id | string | 是 | 窗口id。 | -| type | [WindowType](#windowtype7) | 是 | 窗口类型。 | -| callback | AsyncCallback<[Window](#window)> | 是 | 回调函数。返回当前创建的子窗口对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------ | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 当前应用上下文信息。 | +| id | string | 是 | 窗口id。 | +| type | [WindowType](#windowtype7) | 是 | 窗口类型。 | +| callback | AsyncCallback<[Window](#window)> | 是 | 回调函数。返回当前创建的子窗口对象。 | **示例:** @@ -935,9 +933,7 @@ window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> -创建子窗口,使用Promise异步回调,其中Context详见[Context](js-apis-inner-app-context.md)。 - -从API version 9开始,当Context为[ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)时,创建系统窗口,使用Promise异步回调。 +创建系统窗口,使用Promise异步回调。 > **说明:** > @@ -949,7 +945,7 @@ create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | 是 | 当前应用上下文信息。
FA模型的Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的Context定义见[ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)。 | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 当前应用上下文信息。 | | id | string | 是 | 窗口id。 | | type | [WindowType](#windowtype7) | 是 | 窗口类型。 | @@ -1125,7 +1121,7 @@ getTopWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | 是 | 当前应用上下文信息。
FA模型的Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的Context定义见[Context](js-apis-ability-context.md)。 | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 当前应用上下文信息。 | | callback | AsyncCallback<[Window](#window)> | 是 | 回调函数。返回当前应用内最后显示的窗口对象。 | **示例:** @@ -1158,7 +1154,7 @@ getTopWindow(ctx: BaseContext): Promise<Window> | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | 是 | 当前应用上下文信息。
FA模型的Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的Context定义见[Context](js-apis-ability-context.md)。 | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 当前应用上下文信息。 | **返回值:** diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animateTo.gif b/zh-cn/application-dev/reference/arkui-ts/figures/animateTo.gif deleted file mode 100644 index 8755e2bc014f3843f8798acae725eeb0fee11f54..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/animateTo.gif and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent1.png b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent1.png new file mode 100644 index 0000000000000000000000000000000000000000..b2aa53b14b112434bb736d2dc2f301bac3b46043 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent1.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent2.png b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent2.png new file mode 100644 index 0000000000000000000000000000000000000000..c348c9305503698fab2f6b401450048a653e581a Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent2.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent3.png b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent3.png new file mode 100644 index 0000000000000000000000000000000000000000..b53d8f308a879d4b4ce84db7adac1289c8b85cfa Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent3.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent4.png b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent4.png new file mode 100644 index 0000000000000000000000000000000000000000..a93f8390861d3638a35de13f38e2ab51816b8083 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/animationComponent4.png differ 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 533a958fc0b8bc20a029de65d4204e72219f22b7..bc6a54e414a7fff721138d60240d8f28cdaf3335 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 @@ -354,9 +354,9 @@ struct ImageExample3 { ### 渲染沙箱路径图片 ```ts -import fileio from '@ohos.fileio' -import fs from '@ohos.file.fs' -import context from '@ohos.application.context' +import fileio from '@ohos.fileio'; +import fs from '@ohos.file.fs'; +import context from '@ohos.app.ability.context'; @Entry @Component diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md index 0fd6256dbc68f335f45591a20d7d20f957eb8a58..9da948e8a38d4c71379caf8624a04fe5ad536f08 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -1,6 +1,6 @@ # ListItem -用来展示列表具体item,宽度默认充满List组件,必须配合List来使用。 +用来展示列表具体item,必须配合List来使用。 > **说明:** > diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md index e45219eff3297eb33ebc4b1e0f0485338b7266e9..bcef3272e6a2ce23274f876eba6bf4b18faac93a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -131,7 +131,7 @@ scrollToIndex(value: number): void > **说明:** > -> 仅支持list组件。 +> 仅支持Grid、list、WaterFlow组件。 **参数:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md index b8ec7ae00273c1ca6b671dd24dc6f67fe90b8760..f61a0286729dd0b62396baf06aa74e0269eb811f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md @@ -60,4 +60,20 @@ struct TransitionExample { } ``` -![animateTo](figures/animateTo.gif) \ No newline at end of file +示意图: + +图片完全显示时: + +![animationComponent1](figures/animationComponent1.png) + +图片消失时配置顺时针旋转180°的过渡效果: + +![animationComponent3](figures/animationComponent3.png) + +图片完全消失时: + +![animationComponent2](figures/animationComponent2.png) + +图片显示时配置横向放大一倍的过渡效果: + +![animationComponent4](figures/animationComponent4.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md b/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md index 98a19c118a66b4b556ae269e216f33ebdb0a0828..3f1379132174d07f163410c14c42e8c001367fe1 100644 --- a/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md +++ b/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md @@ -13,113 +13,113 @@ OpenHarmony的Native API组件对Node-API的接口进行了重新实现,底层 ## Native API组件扩展的符号列表 -|符号类型|符号名|备注| +|符号类型|符号名|说明| | --- | --- | --- | -|FUNC|napi_run_script_path|运行JavaScript文件| +|FUNC|napi_run_script_path|运行JavaScript文件。| **标准库中导出的符号列表** -|符号类型|符号名|备注| +|符号类型|符号名|说明| | --- | --- | --- | -|FUNC|napi_module_register|| -|FUNC|napi_get_last_error_info|| -|FUNC|napi_throw|| -|FUNC|napi_throw_error|| -|FUNC|napi_throw_type_error|| -|FUNC|napi_throw_range_error|| -|FUNC|napi_is_error|| -|FUNC|napi_create_error|| -|FUNC|napi_create_type_error|| -|FUNC|napi_create_range_error|| -|FUNC|napi_get_and_clear_last_exception|| -|FUNC|napi_is_exception_pending|| -|FUNC|napi_fatal_error|| -|FUNC|napi_open_handle_scope|| -|FUNC|napi_close_handle_scope|| -|FUNC|napi_open_escapable_handle_scope|| -|FUNC|napi_close_escapable_handle_scope|| -|FUNC|napi_escape_handle|| -|FUNC|napi_create_reference|| -|FUNC|napi_delete_reference|| -|FUNC|napi_reference_ref|| -|FUNC|napi_reference_unref|| -|FUNC|napi_get_reference_value|| -|FUNC|napi_create_array|| -|FUNC|napi_create_array_with_length|| -|FUNC|napi_create_arraybuffer|| -|FUNC|napi_create_external|| -|FUNC|napi_create_external_arraybuffer|| -|FUNC|napi_create_object|| -|FUNC|napi_create_symbol|| -|FUNC|napi_create_typedarray|| -|FUNC|napi_create_dataview|| -|FUNC|napi_create_int32|| -|FUNC|napi_create_uint32|| -|FUNC|napi_create_int64|| -|FUNC|napi_create_double|| -|FUNC|napi_create_string_latin1|| -|FUNC|napi_create_string_utf8|| -|FUNC|napi_get_array_length|| -|FUNC|napi_get_arraybuffer_info|| -|FUNC|napi_get_prototype|| -|FUNC|napi_get_typedarray_info|| -|FUNC|napi_get_dataview_info|| -|FUNC|napi_get_value_bool|| -|FUNC|napi_get_value_double|| -|FUNC|napi_get_value_external|| -|FUNC|napi_get_value_int32|| -|FUNC|napi_get_value_int64|| -|FUNC|napi_get_value_string_latin1|| -|FUNC|napi_get_value_string_utf8|| -|FUNC|napi_get_value_uint32|| -|FUNC|napi_get_boolean|| -|FUNC|napi_get_global|| -|FUNC|napi_get_null|| -|FUNC|napi_get_undefined|| -|FUNC|napi_coerce_to_bool|| -|FUNC|napi_coerce_to_number|| -|FUNC|napi_coerce_to_object|| -|FUNC|napi_coerce_to_string|| -|FUNC|napi_typeof|| -|FUNC|napi_instanceof|| -|FUNC|napi_is_array|| -|FUNC|napi_is_arraybuffer|| -|FUNC|napi_is_typedarray|| -|FUNC|napi_is_dataview|| -|FUNC|napi_is_date|| -|FUNC|napi_strict_equals|| -|FUNC|napi_get_property_names|| -|FUNC|napi_set_property|| -|FUNC|napi_get_property|| -|FUNC|napi_has_property|| -|FUNC|napi_delete_property|| -|FUNC|napi_has_own_property|| -|FUNC|napi_set_named_property|| -|FUNC|napi_get_named_property|| -|FUNC|napi_has_named_property|| -|FUNC|napi_set_element|| -|FUNC|napi_get_element|| -|FUNC|napi_has_element|| -|FUNC|napi_delete_element|| -|FUNC|napi_define_properties|| -|FUNC|napi_call_function|| -|FUNC|napi_create_function|| -|FUNC|napi_get_cb_info|| -|FUNC|napi_get_new_target|| -|FUNC|napi_new_instance|| -|FUNC|napi_define_class|| -|FUNC|napi_wrap|| -|FUNC|napi_unwrap|| -|FUNC|napi_remove_wrap|| -|FUNC|napi_create_async_work|| -|FUNC|napi_delete_async_work|| -|FUNC|napi_queue_async_work|| -|FUNC|napi_cancel_async_work|| -|FUNC|napi_get_node_version|| -|FUNC|napi_get_version|| -|FUNC|napi_create_promise|| -|FUNC|napi_resolve_deferred|| -|FUNC|napi_reject_deferred|| -|FUNC|napi_is_promise|| -|FUNC|napi_run_script|| -|FUNC|napi_get_uv_event_loop|| \ No newline at end of file +|FUNC|napi_module_register|napi native模块注册接口。| +|FUNC|napi_get_last_error_info|获取`napi_extended_error_info`结构体,其中包含最近一次出现的error信息。| +|FUNC|napi_throw|抛出一个js value。| +|FUNC|napi_throw_error|抛出一个带文本信息的js `Error`。| +|FUNC|napi_throw_type_error|抛出一个带文本信息的js `TypeError`。| +|FUNC|napi_throw_range_error|抛出一个带文本信息的js `RangeError`。| +|FUNC|napi_is_error|判断`napi_value`是否表示为一个error对象。| +|FUNC|napi_create_error|创建并获取一个带文本信息的js `Error`。| +|FUNC|napi_create_type_error|创建并获取一个带文本信息的js `TypeError`。| +|FUNC|napi_create_range_error|创建并获取一个带文本信息的js `RangeError`。| +|FUNC|napi_get_and_clear_last_exception|获取并清除最近一次出现的异常。| +|FUNC|napi_is_exception_pending|判断是否出现了异常。| +|FUNC|napi_fatal_error|引发致命错误以立即终止进程。| +|FUNC|napi_open_handle_scope|创建一个上下文环境使用。| +|FUNC|napi_close_handle_scope|关闭传入的上下文环境,关闭后,全部在其中声明的引用都将被关闭。| +|FUNC|napi_open_escapable_handle_scope|创建出一个可逃逸的handel scope,可将范围内声明的值返回到父作用域。| +|FUNC|napi_close_escapable_handle_scope|关闭传入的可逃逸的handel scope。| +|FUNC|napi_escape_handle|提升传入的js object的生命周期到其父作用域。| +|FUNC|napi_create_reference|为`Object`创建一个reference,以延长其生命周期。调用者需要自己管理reference生命周期。| +|FUNC|napi_delete_reference|删除传入的reference。| +|FUNC|napi_reference_ref|增加传入的reference的引用计数,并获取该计数。| +|FUNC|napi_reference_unref|减少传入的reference的引用计数,并获取该计数。| +|FUNC|napi_get_reference_value|获取与reference相关联的js `Object`。| +|FUNC|napi_create_array|创建并获取一个js `Array`。| +|FUNC|napi_create_array_with_length|创建并获取一个指定长度的js `Array`。| +|FUNC|napi_create_arraybuffer|创建并获取一个指定大小的js `ArrayBuffer`。| +|FUNC|napi_create_external|分配一个附加有外部数据的js value。| +|FUNC|napi_create_external_arraybuffer|分配一个附加有外部数据的js `ArrayBuffer`。| +|FUNC|napi_create_object|创建一个默认的js `Object`。| +|FUNC|napi_create_symbol|创建一个js `Symbol`。| +|FUNC|napi_create_typedarray|通过现有的`ArrayBuffer`创建一个js `TypeArray`。| +|FUNC|napi_create_dataview|通过现有的`ArrayBuffer`创建一个js `DataView`。| +|FUNC|napi_create_int32|通过一个C的`int32_t`数据创建js `Number`。| +|FUNC|napi_create_uint32|通过一个C的`uint32_t`数据创建js `Number`。| +|FUNC|napi_create_int64|通过一个C的`int64_t`数据创建js `Number`。| +|FUNC|napi_create_double|通过一个C的`double`数据创建js `Number`。| +|FUNC|napi_create_string_latin1|通过ISO-8859-1编码的C字符串数据创建js `String`。| +|FUNC|napi_create_string_utf8|通过UTF8编码的C字符串数据创建js `String`。| +|FUNC|napi_get_array_length|获取array的length。| +|FUNC|napi_get_arraybuffer_info|获取`ArrayBuffer`的底层data buffer及其长度。| +|FUNC|napi_get_prototype|获取给定js `Object`的`prototype`。| +|FUNC|napi_get_typedarray_info|获取给定`TypedArray`的各种属性。| +|FUNC|napi_get_dataview_info|获取给定`DataView`的各种属性。| +|FUNC|napi_get_value_bool|获取给定js `Boolean`对应的C bool值。| +|FUNC|napi_get_value_double|获取给定js `Number`对应的C double值。| +|FUNC|napi_get_value_external|获取先前通过napi_create_external()传递的外部数据指针。| +|FUNC|napi_get_value_int32|获取给定js `Number`对应的C int32值。| +|FUNC|napi_get_value_int64|获取给定js `Number`对应的C int64值。| +|FUNC|napi_get_value_string_latin1|获取给定js vaule对应的ISO-8859-1编码的字符串。| +|FUNC|napi_get_value_string_utf8|获取给定js vaule对应的UTF8编码的字符串。| +|FUNC|napi_get_value_uint32|获取给定js `Number`对应的C uint32值。| +|FUNC|napi_get_boolean|根据给定的C boolean值,获取js bool对象。| +|FUNC|napi_get_global|获取`global`对象。| +|FUNC|napi_get_null|获取`null`对象。| +|FUNC|napi_get_undefined|获取`undefined`对象。| +|FUNC|napi_coerce_to_bool|将给定的js value强转成js `Boolean`。| +|FUNC|napi_coerce_to_number|将给定的js value强转成js `Number`。| +|FUNC|napi_coerce_to_object|将给定的js value强转成js `Object`。| +|FUNC|napi_coerce_to_string|将给定的js value强转成js `String`。| +|FUNC|napi_typeof|获取给定js value的js type。| +|FUNC|napi_instanceof|判断给定object是否为给定constructor的实例。| +|FUNC|napi_is_array|判断给定js value是否为array。| +|FUNC|napi_is_arraybuffer|判断给定js value是否为`ArrayBuffer`。| +|FUNC|napi_is_typedarray|判断给定js value是否表示一个`TypedArray`。| +|FUNC|napi_is_dataview|判断给定js value是否表示一个`DataView`。| +|FUNC|napi_is_date|判断给定js value是否为js `Date`对象。| +|FUNC|napi_strict_equals|判断给定的两个js value是否严格相等。| +|FUNC|napi_get_property_names|以字符串数组的形式获取对象的可枚举属性的名称。| +|FUNC|napi_set_property|对给定`Object`设置属性。| +|FUNC|napi_get_property|获取给定`Object`的给定属性。| +|FUNC|napi_has_property|判断给定对象中是否存在给定属性。| +|FUNC|napi_delete_property|尝试从给定`Object`中删除给定`key`属性。| +|FUNC|napi_has_own_property|判断给定`Object`中是否有名为`key`的own property。| +|FUNC|napi_set_named_property|对给定`Object`设置一个给定名称的属性。| +|FUNC|napi_get_named_property|获取给定`Object`中指定名称的属性。| +|FUNC|napi_has_named_property|判断给定`Object`中是否有给定名称的属性。| +|FUNC|napi_set_element|在给定`Object`的指定索引处,设置元素。| +|FUNC|napi_get_element|获取给定`Object`指定索引处的元素。| +|FUNC|napi_has_element|若给定`Object`的指定索引处拥有属性,获取该元素。| +|FUNC|napi_delete_element|尝试删除给定`Object`的指定索引处的元素。| +|FUNC|napi_define_properties|批量的向给定`Object`中定义属性。| +|FUNC|napi_call_function|在Native方法中调用js function,即native call js。| +|FUNC|napi_create_function|创建native方法给js使用,以便于js call native。| +|FUNC|napi_get_cb_info|从给定的callback info中获取有关调用的详细信息,如参数和this指针。| +|FUNC|napi_get_new_target|获取构造函数调用的`new.target`。| +|FUNC|napi_new_instance|通过给定的构造函数,构建一个实例。| +|FUNC|napi_define_class|定义与C++类相对应的JavaScript类。| +|FUNC|napi_wrap|在js object上绑定一个native对象实例。| +|FUNC|napi_unwrap|从js object上获取先前绑定的native对象实例。| +|FUNC|napi_remove_wrap|从js object上获取先前绑定的native对象实例,并解除绑定。| +|FUNC|napi_create_async_work|创建一个异步工作对象。| +|FUNC|napi_delete_async_work|释放先前创建的异步工作对象。| +|FUNC|napi_queue_async_work|将异步工作对象加到队列,由底层去调度执行。| +|FUNC|napi_cancel_async_work|取消入队的异步任务。| +|FUNC|napi_get_node_version|获取node的版本信息。| +|FUNC|napi_get_version|获取Node运行时支持的最高 N-API 版本。| +|FUNC|napi_create_promise|创建一个延迟对象和js promise。| +|FUNC|napi_resolve_deferred|resolve与js promise对象关联的延迟函数。| +|FUNC|napi_reject_deferred|reject与js promise对象关联的延迟函数。| +|FUNC|napi_is_promise|判断给定js value是否为promise对象。| +|FUNC|napi_run_script|执行一段js代码。| +|FUNC|napi_get_uv_event_loop|获取当前libuv loop实例。| \ No newline at end of file diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index c27b4375c105919ea40b395758644d006421022a..189cba7a454da7e6802571b3172fe78e0d319398 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -924,6 +924,16 @@ **ACL使能**:TRUE +## ohos.permission.ENTERPRISE_RESET_DEVICE + +允许设备管理员恢复设备出厂设置。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + ## ohos.permission.NFC_TAG 允许应用读取Tag卡片。 diff --git a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md index f64d06c713b3e238844313ea548fc85099e75d45..31775e425e6d57093087e558121eb4e5c73c6016 100644 --- a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md +++ b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md @@ -202,7 +202,7 @@ function stopContinuousTask() { try { backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { + }).catch((error) => { console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); }); } catch (error) { diff --git a/zh-cn/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png b/zh-cn/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png index dbee17acbad2189a9a2d3cedb9c32242fb002866..57520a106c4dc4806866d78516939f29cb33ee9e 100644 Binary files a/zh-cn/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png and b/zh-cn/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png differ diff --git a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md index e7b758b696f84fde52f2d6d4aa7f6e0e882011d1..615e256f96f323f97b71bef57605f335f29143e5 100644 --- a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md +++ b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md @@ -2,7 +2,8 @@ ## 场景介绍 -应用要执行对实时性要求不高的任务或持久性任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间,[WorkSchedulerExtensionAbility](./workscheduler-extensionability.md)提供了延迟任务回调拓展能力。延迟任务调度约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束)。 +应用要执行对实时性要求不高的任务或持久性任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间,[WorkSchedulerExtensionAbility](./workscheduler-extensionability.md)提供了延迟任务回调拓展能力,注册延迟任务后需要实现延迟任务回调拓展能力。 +延迟任务调度约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束)。 ## 接口说明 diff --git a/zh-cn/application-dev/task-management/workscheduler-extensionability.md b/zh-cn/application-dev/task-management/workscheduler-extensionability.md index 97367f1b99481c807fc0873707da49743f7f0c3d..d10153b178d007819d0b32ec0454bf1eb209d38e 100644 --- a/zh-cn/application-dev/task-management/workscheduler-extensionability.md +++ b/zh-cn/application-dev/task-management/workscheduler-extensionability.md @@ -1,6 +1,6 @@ # 延迟任务回调能力开发指导(WorkSchedulerExtensionAbility) -对于实时性要求不高的任务或持久性任务,可以使用延迟调度任务,该机制会在应用满足应用设定条件(包括网络类型、充电类型、存储状态、电池状态、定时状态)时,根据系统当前状态,由系统统一决策调度时间。 +对于实时性要求不高的任务或持久性任务,可以使用延迟任务,该机制会在应用满足应用设定条件(包括网络类型、充电类型、存储状态、电池状态、定时状态)时,根据系统当前状态,由系统统一决策调度时间。 WorkSchedulerExtensionAbility提供了延迟任务回调能力,在延迟任务开始和结束时,系统会调用回调接口来处理任务逻辑,开发者可在回调接口里面编写自己的任务逻辑。 @@ -17,7 +17,7 @@ WorkSchedulerExtensionAbility提供了延迟任务回调能力,在延迟任务 ## 接口说明 -WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见[接口文档](../reference/apis/js-apis-app-form-formExtensionAbility.md)。 +WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见[接口文档](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md)。 | 接口名 | 描述 | | -------- | -------- | @@ -122,7 +122,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 bundleName: '', abilityName: '' } - // 注册延迟调度任务 + // 注册延迟任务 startWork(bundleName: string, abilityName: string) { this.workInfo.bundleName = bundleName this.workInfo.abilityName = abilityName @@ -137,7 +137,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 } } - // 停止延迟调度任务 + // 停止延迟任务 stopWork(bundleName: string, abilityName: string) { this.workInfo.bundleName = bundleName this.workInfo.abilityName = abilityName diff --git a/zh-cn/application-dev/ui/arkui-overview.md b/zh-cn/application-dev/ui/arkui-overview.md index 7fa89a6eac39ce7be21dc7cca64f85b83723f419..f788b416e46528ccebe5a5c8f84693ee74cbb619 100644 --- a/zh-cn/application-dev/ui/arkui-overview.md +++ b/zh-cn/application-dev/ui/arkui-overview.md @@ -50,11 +50,10 @@ OpenHarmony提供了FA模型与Stage模型两种[应用模型](../application-mo **Stage模型:** -| 类型 | UI开发范式 | 说明 | -| ---- | -------- | ---------------------------------------- | -| 应用 | 类web开发范式 | 当前不支持 | -| | 声明式开发范式 | UI开发语言:ArkTS
业务入口:应用模型基于ohos.application.Ability/ExtensionAbility等派生
业务逻辑语言:ts | -| 服务卡片 | 类web开发范式 | UI开发语言:卡片显示使用hml+css+json(action)
业务入口:从FormExtensionAbility派生
业务逻辑语言:ts | -| | 声明式开发范式 | 当前不支持 | - +| 类型 | UI开发范式 | 说明 | +| -------- | -------------- | ------------------------------------------------------------ | +| 应用 | 类web开发范式 | 当前不支持 | +| | 声明式开发范式 | UI开发语言:ArkTS
业务入口:应用模型基于ohos.app.ability.UIAbility/ExtensionAbility等派生
业务逻辑语言:ts | +| 服务卡片 | 类web开发范式 | UI开发语言:卡片显示使用hml+css+json(action)
业务入口:从FormExtensionAbility派生
业务逻辑语言:ts | +| | 声明式开发范式 | 当前不支持 | diff --git a/zh-cn/application-dev/ui/ui-ts-building-data-model.md b/zh-cn/application-dev/ui/ui-ts-building-data-model.md index 4d516a2b3fa81a482ebaf5337efd7c080871bd07..c2fe6aa7c739a19db3a450a17f055150cf5d28b9 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-data-model.md +++ b/zh-cn/application-dev/ui/ui-ts-building-data-model.md @@ -59,7 +59,7 @@ ] ``` - 实际开发中,开发者可以自定义更多的数据资源,当食物资源很多时,建议使用数据懒加载LazyForEach。 + 实际开发中,开发者可以自定义更多的数据资源,当食物资源很多时,建议使用[数据懒加载LazyForEach](../quick-start/arkts-rendering-control.md#数据懒加载)。 5. 创建initializeOnStartUp方法来初始化FoodData的数组。在FoodDataModels.ets中使用了定义在FoodData.ets的FoodData和Category,所以要将FoodData.ets的FoodData类export,在FoodDataModels.ets内import FoodData和Category。 ```ts diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md index 565bdddd400c9a2fb32714855fdce94830292ea9..e8eeba071e205b26db55880fb5f4720e8402c696 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -27,12 +27,12 @@ 栅格系统以设备的水平宽度(屏幕密度像素值,单位vp)作为断点依据,定义设备的宽度类型,形成了一套断点规则。开发者可根据需求在不同的断点区间实现不同的页面布局效果。 栅格系统默认断点将设备宽度分为xs、sm、md、lg四类,尺寸范围如下: -| 断点名称 | 取值范围(vp)| -| --------| ------ | -| xs | [0, 320) | -| sm | [320, 520) | -| md | [520, 840) | -| lg | [840, +∞) | +| 断点名称 | 取值范围(vp)| +| --------| ------ | +| xs | [0, 320) | +| sm | [320, 520) | +| md | [520, 840) | +| lg | [840, +∞) | 在GridRow新栅格组件中,允许开发者使用breakpoints自定义修改断点的取值范围,最多支持6个断点,除了默认的四个断点外, 还可以启用xl,xxl两个断点,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的布局设置。 @@ -88,10 +88,10 @@ GridRow({ }.backgroundColor(color) }) } -``` + ``` ![](figures/breakpoints.gif) - + ### 栅格布局的总列数 @@ -333,8 +333,8 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ### order - 栅格子组件的序号,决定子组件排列次序。当子组件不设置order或者设置相同的order, 子组件按照代码顺序展示。当子组件设置不同的order时,order较大的组件在前,较小的在后。 - 当子组件部分设置order,部分不设置order时,未设置order的子组件依次排序靠前,设置了order的子组件按照数值从大到小排列。 + 栅格子组件的序号,决定子组件排列次序。当子组件不设置order或者设置相同的order, 子组件按照代码顺序展示。当子组件设置不同的order时,order较小的组件在前,较大的在后。 + 当子组件部分设置order,部分不设置order时,未设置order的子组件依次排序靠前,设置了order的子组件按照数值从小到大排列。 - 当类型为number时,子组件在任何尺寸下排序次序一致。 diff --git a/zh-cn/application-dev/windowmanager/application-window-fa.md b/zh-cn/application-dev/windowmanager/application-window-fa.md index a652a09d2b82f5ce5dd890659a9c59747c6db738..53473d510dee38df38f3782562c53d0cead6c6cc 100644 --- a/zh-cn/application-dev/windowmanager/application-window-fa.md +++ b/zh-cn/application-dev/windowmanager/application-window-fa.md @@ -54,7 +54,7 @@ let windowClass = null; // 方式一:创建子窗口。 - let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP, ctx: this.context}; + let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP}; window.createWindow(config, (err, data) => { if (err.code) { console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); @@ -72,8 +72,8 @@ console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data)); windowClass = data; }); - ``` - +``` + 2. 设置子窗口属性。 子窗口创建成功后,可以改变其大小、位置等,还可以根据应用需要设置窗口背景色、亮度等属性。 diff --git a/zh-cn/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md index 8c8a5aae28c6ab7ea0af2676909cf8d454865d70..47cd5be52f8e4ba5ea2598df1fdb5a5f8a34b794 100644 --- a/zh-cn/application-dev/windowmanager/application-window-stage.md +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -320,7 +320,7 @@ export default class EntryAbility extends UIAbility { ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + import ExtensionContext from '@ohos.app.ability.ServiceExtensionAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { diff --git a/zh-cn/application-dev/windowmanager/system-window-stage.md b/zh-cn/application-dev/windowmanager/system-window-stage.md index 19acc8b34b35f8e77cb5b7fdf857f85154955d65..58011ceea1a651473c615c4f621999128d592a7b 100644 --- a/zh-cn/application-dev/windowmanager/system-window-stage.md +++ b/zh-cn/application-dev/windowmanager/system-window-stage.md @@ -58,7 +58,7 @@ 当不再需要音量条窗口时,可根据具体实现逻辑,使用`hide`接口或`destroyWindow`接口对其进行隐藏或销毁。 ```ts -import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; +import ExtensionContext from '@ohos.app.ability.ServiceExtensionAbility'; import window from '@ohos.window'; export default class ServiceExtensionAbility1 extends ExtensionContext { diff --git a/zh-cn/device-dev/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index 70b4388b06ad3712b5ee41f6f210f6de8c4f4117..6830f1c25d24f603a0a5d78a2123bca96ea98c9d 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -136,7 +136,7 @@ - [魔法键使用方法](kernel-small-debug-shell-magickey.md) - [用户态异常信息说明](kernel-small-debug-shell-error.md) - [Trace调测](kernel-small-debug-trace.md) - - [Perf调测](kernel-mini-memory-perf.md) + - [Perf调测](kernel-small-debug-perf.md) - [LMS调测](kernel-small-memory-lms.md) - [进程调测](kernel-small-debug-process-cpu.md) - 内核态内存调测 diff --git a/zh-cn/device-dev/kernel/kernel-mini-extend-cpup.md b/zh-cn/device-dev/kernel/kernel-mini-extend-cpup.md index 3bb9218ea72bd6dbf5c6e27c94bed739c0f2063c..275c839d1fe923debfc957b4ca4a97c37ec9198e 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-extend-cpup.md +++ b/zh-cn/device-dev/kernel/kernel-mini-extend-cpup.md @@ -51,16 +51,19 @@ OpenHarmony LiteOS-M提供以下两种CPU占用率的信息查询: | 输出任务CPU占用率 | LOS_CpupUsageMonitor:输出任务历史CPU占用率 | | 获取中断CPU占用率 | LOS_GetAllIrqCpuUsage:获取所有中断CPU占用率 | - ## 开发流程 +在kernel/liteos_m目录下执行 make menuconfig 命令配置"Kernel->Enable Cpup"中打开YES开启任务cpup; + +开启后出现新选项“Enable Cpup include irq”打开YES开启中断cpup。 + CPU占用率的典型开发流程: 1. 调用获取系统CPU占用率函数LOS_SysCpuUsage。 2. 调用获取系统历史CPU占用率函数LOS_HistorySysCpuUsage。 -3. 调用获取指定任务CPU使占用率函数LOS_TaskCpuUsage。 +3. 调用获取指定任务CPU占用率函数LOS_TaskCpuUsage。 - 若任务已创建,则关中断,正常获取,恢复中断; - 若任务未创建,则返回错误码; @@ -95,7 +98,7 @@ CPU占用率的典型开发流程: 前提条件: -在target_config.h中将LOSCFG_BASE_CORE_CPUP配置项打开。 +在kernel/liteos_m目录下执行 make menuconfig命令配置"Kernel->Enable Cpup"中开启任务cpup: 代码实现如下: diff --git a/zh-cn/device-dev/kernel/kernel-mini-extend-file.md b/zh-cn/device-dev/kernel/kernel-mini-extend-file.md index 0a5015d388901e4ae112063fd46dccbc85f3f394..0302a6c6b129d86037be9adeaa27e7c6a24335de 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-extend-file.md +++ b/zh-cn/device-dev/kernel/kernel-mini-extend-file.md @@ -168,13 +168,11 @@ mount接口:int mount(const char *source, const char *target, const char *file > - 读写指针未分离,例如以O_APPEND(追加写)方式打开文件后,读指针也在文件尾,从头读文件前需要用户手动置位。 > - 暂不支持文件与目录的权限管理。 > - stat及fstat接口暂不支持查询修改时间、创建时间和最后访问时间。微软FAT协议不支持1980年以前的时间。 -> > - FATFS分区挂载与卸载: > - 支持以只读属性挂载分区。当mount函数的入参为MS_RDONLY时,所有的带有写入的接口,如write、mkdir、unlink,以及非O_RDONLY属性的open,将均被拒绝。 > - mount支持通过MS_REMOUNT标记修改已挂载分区的权限。 > - 在umount操作前,需确保所有目录及文件全部关闭。 > - umount2支持通过MNT_FORCE参数强制关闭所有文件与文件夹并umount,但可能造成数据丢失,请谨慎使用。 -> > - FATFS支持重新划分存储设备分区、格式化分区,对应接口为fatfs_fdisk与fatfs_format: > - 在fatfs_format操作之前,若需要格式化的分区已挂载,需确保分区中的所有目录及文件全部关闭,并且分区umount。 > - 在fatfs_fdisk操作前,需要该设备中的所有分区均已umount。 @@ -213,6 +211,10 @@ mount接口:int mount(const char *source, const char *target, const char *file 系统已将设备分区挂载到目录,qemu默认已挂载system。 + 在kernel/liteos_m目录下执行 make menuconfig 命令配置"FileSystem->Enable FS VFS"开启FS功能; + + 开启FS后出现新选项“Enable FAT”开启FAT。 + **代码实现如下:** 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleFatfs。 @@ -425,6 +427,10 @@ blockCount 可以被擦除的块数量,这取决于块设备的容量及擦除 系统已将设备分区挂载到目录,qemu默认已挂载/littlefs。 +在kernel/liteos_m目录下执行 make menuconfig 命令配置"FileSystem->Enable FS VFS"开启FS功能; + +开启FS后出现新选项“Enable Little FS”开启littlefs。 + 代码实现如下: 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleLittlefs。 diff --git a/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md b/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md index ce156e668c41cec304b1d5e51ed05cf173ec50b1..079491ec6fab028f210a24647ed92ec2c52e4326 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md +++ b/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md @@ -185,7 +185,9 @@ node size LR[0] LR[1] LR[2] 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数MemLeakTest。 -qemu中进行验证时,由于代码段位置特殊需调整ld文件_stext位置到text段的起始位置 +qemu平台运行时需确保target_config.h 中对应的LOSCFG_MEM_FREE_BY_TASKID为0。 + +由于打开内存检测后,部分平台有其他任务运行,会频繁调用内存相关打印如:psp, start = xxxxx, end = xxxxxxx,请忽略打印或删除OsStackAddrGet函数中调用的打印即可。 ``` @@ -311,6 +313,10 @@ LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK:开关宏,默认关闭;若打开这 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数MemIntegrityTest。 +qemu平台运行时需确保target_config.h 中对应的LOSCFG_MEM_FREE_BY_TASKID为0。 + +由于执行时主动触发异常,执行结束后需要重启qemu(例如打开一个新的终端界面输入killall qemu-system-arm) + ``` #include @@ -344,7 +350,7 @@ memory used but magic num wrong, magic num = 0x0 /* 被破坏节点和其前节点关键字段信息,分别为其前节点地址、节点的魔鬼数字、节点的sizeAndFlag;可以看出被破坏节点的魔鬼数字字段被清零,符合用例场景 */ broken node head: 0x2103d7e8 0x0 0x80000020, prev node head: 0x2103c7cc 0xabcddcba 0x80000020 - /* 节点的LR信息需要开启内存检测功能才有有效输出 */ + /* 节点的LR信息需要开启前文的内存泄漏检测功能才有有效输出 */ broken node head LR info: LR[0]:0x2101906c LR[1]:0x0 diff --git a/zh-cn/device-dev/kernel/kernel-mini-memory-trace.md b/zh-cn/device-dev/kernel/kernel-mini-memory-trace.md index 79c580868721f3dc2994c4693f822cb71e585b55..a50b89c619b13944c85e65ad6e06cd72c4c37243 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-memory-trace.md +++ b/zh-cn/device-dev/kernel/kernel-mini-memory-trace.md @@ -246,6 +246,8 @@ Index Time(cycles) EventType CurTask Identity params 6 0x3706f804 0x45 0x1 0x0 0x1f 0x4 0x0 7 0x37070e59 0x45 0x0 0x1 0x0 0x8 0x1f ***TraceInfo end*** + +根据实际运行环境,上文中的数据会有差异,非固定结果 ``` 输出的事件信息包括:发生时间、事件类型、事件发生在哪个任务中、事件操作的主体对象、事件的其他参数。 diff --git a/zh-cn/device-dev/kernel/kernel-small-apx-library.md b/zh-cn/device-dev/kernel/kernel-small-apx-library.md index 0f06476a3449c2eabed63351c9d6c26fe611d0d6..58bca463e0917145fd0fa437f854d9f4725fd16b 100644 --- a/zh-cn/device-dev/kernel/kernel-small-apx-library.md +++ b/zh-cn/device-dev/kernel/kernel-small-apx-library.md @@ -24,7 +24,7 @@ musl libc库支持POSIX标准,涉及的系统调用相关接口由OpenHarmony #### 编程示例 -本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数testcase 或新建文件由主函数调用 +本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数ExamplePosix。 示例代码如下: @@ -33,12 +33,6 @@ musl libc库支持POSIX标准,涉及的系统调用相关接口由OpenHarmony #include #include -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif /* __cplusplus */ -#endif /* __cplusplus */ - #define THREAD_NUM 3 int g_startNum = 0; /* 启动的线程数 */ int g_wakenNum = 0; /* 唤醒的线程数 */ @@ -48,10 +42,8 @@ struct testdata { pthread_cond_t cond; } g_td; -/* - * 子线程入口函数 - */ -static void *ChildThreadFunc(void *arg) +/* 子线程入口函数 */ +static VOID *ChildThreadFunc(VOID *arg) { int rc; pthread_t self = pthread_self(); @@ -59,7 +51,7 @@ static void *ChildThreadFunc(void *arg) /* 获取mutex锁 */ rc = pthread_mutex_lock(&g_td.mutex); if (rc != 0) { - printf("ERROR:take mutex lock failed, error code is %d!\n", rc); + dprintf("ERROR:take mutex lock failed, error code is %d!\n", rc); goto EXIT; } @@ -69,7 +61,7 @@ static void *ChildThreadFunc(void *arg) /* 等待cond条件变量 */ rc = pthread_cond_wait(&g_td.cond, &g_td.mutex); if (rc != 0) { - printf("ERROR: pthread condition wait failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition wait failed, error code is %d!\n", rc); (void)pthread_mutex_unlock(&g_td.mutex); goto EXIT; } @@ -77,7 +69,7 @@ static void *ChildThreadFunc(void *arg) /* 尝试获取mutex锁,正常场景,此处无法获取锁 */ rc = pthread_mutex_trylock(&g_td.mutex); if (rc == 0) { - printf("ERROR: mutex gets an abnormal lock!\n"); + dprintf("ERROR: mutex gets an abnormal lock!\n"); goto EXIT; } @@ -87,14 +79,14 @@ static void *ChildThreadFunc(void *arg) /* 释放mutex锁 */ rc = pthread_mutex_unlock(&g_td.mutex); if (rc != 0) { - printf("ERROR: mutex release failed, error code is %d!\n", rc); + dprintf("ERROR: mutex release failed, error code is %d!\n", rc); goto EXIT; } EXIT: return NULL; } -static int testcase(void) +static int ExamplePosix(VOID) { int i, rc; pthread_t thread[THREAD_NUM]; @@ -102,14 +94,14 @@ static int testcase(void) /* 初始化mutex锁 */ rc = pthread_mutex_init(&g_td.mutex, NULL); if (rc != 0) { - printf("ERROR: mutex init failed, error code is %d!\n", rc); + dprintf("ERROR: mutex init failed, error code is %d!\n", rc); goto ERROROUT; } /* 初始化cond条件变量 */ rc = pthread_cond_init(&g_td.cond, NULL); if (rc != 0) { - printf("ERROR: pthread condition init failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition init failed, error code is %d!\n", rc); goto ERROROUT; } @@ -117,10 +109,11 @@ static int testcase(void) for (i = 0; i < THREAD_NUM; i++) { rc = pthread_create(&thread[i], NULL, ChildThreadFunc, NULL); if (rc != 0) { - printf("ERROR: pthread create failed, error code is %d!\n", rc); + dprintf("ERROR: pthread create failed, error code is %d!\n", rc); goto ERROROUT; } } + dprintf("pthread_create ok\n"); /* 等待所有子线程都完成mutex锁的获取 */ while (g_startNum < THREAD_NUM) { @@ -130,14 +123,14 @@ static int testcase(void) /* 获取mutex锁,确保所有子线程都阻塞在pthread_cond_wait上 */ rc = pthread_mutex_lock(&g_td.mutex); if (rc != 0) { - printf("ERROR: mutex lock failed, error code is %d\n", rc); + dprintf("ERROR: mutex lock failed, error code is %d\n", rc); goto ERROROUT; } /* 释放mutex锁 */ rc = pthread_mutex_unlock(&g_td.mutex); if (rc != 0) { - printf("ERROR: mutex unlock failed, error code is %d!\n", rc); + dprintf("ERROR: mutex unlock failed, error code is %d!\n", rc); goto ERROROUT; } @@ -145,7 +138,7 @@ static int testcase(void) /* 在cond条件变量上广播信号 */ rc = pthread_cond_signal(&g_td.cond); if (rc != 0) { - printf("ERROR: pthread condition failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition failed, error code is %d!\n", rc); goto ERROROUT; } } @@ -154,52 +147,42 @@ static int testcase(void) /* 检查是否所有子线程都已被唤醒 */ if (g_wakenNum != THREAD_NUM) { - printf("ERROR: not all threads awaken, only %d thread(s) awaken!\n", g_wakenNum); + dprintf("ERROR: not all threads awaken, only %d thread(s) awaken!\n", g_wakenNum); goto ERROROUT; } + dprintf("all threads awaked\n"); /* join所有子线程,即等待其结束 */ for (i = 0; i < THREAD_NUM; i++) { rc = pthread_join(thread[i], NULL); if (rc != 0) { - printf("ERROR: pthread join failed, error code is %d!\n", rc); + dprintf("ERROR: pthread join failed, error code is %d!\n", rc); goto ERROROUT; } } + dprintf("all threads join ok\n"); /* 销毁cond条件变量 */ rc = pthread_cond_destroy(&g_td.cond); if (rc != 0) { - printf("ERROR: pthread condition destroy failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition destroy failed, error code is %d!\n", rc); goto ERROROUT; } return 0; ERROROUT: return -1; } +``` -/* - * 示例代码主函数 - */ -int main(int argc, char *argv[]) -{ - int rc; +#### 验证结果 - /* 启动测试函数 */ - rc = testcase(); - if (rc != 0) { - printf("ERROR: testcase failed!\n"); - } + 输出结果如下: - return 0; -} -#ifdef __cplusplus -#if __cplusplus -} -#endif /* __cplusplus */ -#endif /* __cplusplus */ ``` - +pthread_create ok +all threads awaked +all threads join ok +``` ## 与Linux标准库差异 @@ -217,20 +200,17 @@ int main(int argc, char *argv[]) ### 内存 -**h2与Linux mmap的差异** +**与Linux mmap的差异** mmap接口原型为:void \*mmap (void \*addr, size_t length, int prot, int flags, int fd, off_t offset)。 其中,参数fd的生命周期实现与Linux glibc存在差异。具体体现在,glibc在成功调用mmap进行映射后,可以立即释放fd句柄。在OpenHarmony内核中,不允许用户在映射成功后立即关闭相关fd,只允许在取消映射munmap后再进行fd的close操作。如果用户不进行fd的close操作,操作系统将在进程退出时对该fd进行回收。 - -**h2代码举例** +**代码举例** Linux目前支持的情况如下: - - ``` int main(int argc, char *argv[]) { @@ -247,7 +227,7 @@ int main(int argc, char *argv[]) perror("mmap"); exit(EXIT_FAILURE); } - close(fd); /* OpenHarmony does not support closing fd immediately after the mapping is successful. */ + close(fd); /* OpenHarmony does not support closing fd immediately after the mapping is successful. */ ... exit(EXIT_SUCCESS); } @@ -255,7 +235,7 @@ int main(int argc, char *argv[]) OpenHarmony支持的情况如下: - + ``` int main(int argc, char *argv[]) { @@ -274,7 +254,7 @@ int main(int argc, char *argv[]) } ... munmap(addr, length); - close(fd); /* Close fd after the munmap is canceled. */ + close(fd); /* Close fd after the munmap is canceled. */ exit(EXIT_SUCCESS); } ``` diff --git a/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md b/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md index c5f5f696c388e861a4ecf215dbd8b9ee9e3d0179..e88c74b265ede038ef78fc675ebbe2335a2b78ff 100644 --- a/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md +++ b/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md @@ -31,7 +31,7 @@ OpenHarmony LiteOS-A的事件模块提供的事件,具有如下特点: ### 事件控制块 - + ``` /** * 事件控制块数据结构 @@ -144,21 +144,21 @@ UINT32 g_testTaskId; EVENT_CB_S g_exampleEvent; /* 等待的事件类型 */ -#define EVENT_WAIT 0x00000001 - +#define EVENT_WAIT 0x00000001 +#define EVENT_TIMEOUT 500 /* 用例任务入口函数 */ VOID Example_Event(VOID) { UINT32 event; /* 超时等待方式读事件,超时时间为100 ticks, 若100 ticks后未读取到指定事件,读事件超时,任务直接唤醒 */ - printf("Example_Event wait event 0x%x \n", EVENT_WAIT); + dprintf("Example_Event wait event 0x%x \n", EVENT_WAIT); - event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, 100); + event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, EVENT_TIMEOUT); if (event == EVENT_WAIT) { - printf("Example_Event,read event :0x%x\n", event); + dprintf("Example_Event,read event :0x%x\n", event); } else { - printf("Example_Event,read event timeout\n"); + dprintf("Example_Event,read event timeout\n"); } } @@ -170,7 +170,7 @@ UINT32 Example_EventEntry(VOID) /* 事件初始化 */ ret = LOS_EventInit(&g_exampleEvent); if (ret != LOS_OK) { - printf("init event failed .\n"); + dprintf("init event failed .\n"); return -1; } @@ -182,30 +182,23 @@ UINT32 Example_EventEntry(VOID) task1.usTaskPrio = 5; ret = LOS_TaskCreate(&g_testTaskId, &task1); if (ret != LOS_OK) { - printf("task create failed.\n"); + dprintf("task create failed.\n"); return LOS_NOK; } /* 写g_testTaskId 等待事件 */ - printf("Example_TaskEntry write event.\n"); + dprintf("Example_TaskEntry write event.\n"); ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT); if (ret != LOS_OK) { - printf("event write failed.\n"); + dprintf("event write failed.\n"); return LOS_NOK; } /* 清标志位 */ - printf("EventMask:%d\n", g_exampleEvent.uwEventID); + dprintf("EventMask:%d\n", g_exampleEvent.uwEventID); LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID); - printf("EventMask:%d\n", g_exampleEvent.uwEventID); - - /* 删除任务 */ - ret = LOS_TaskDelete(g_testTaskId); - if (ret != LOS_OK) { - printf("task delete failed.\n"); - return LOS_NOK; - } + dprintf("EventMask:%d\n", g_exampleEvent.uwEventID); return LOS_OK; } @@ -216,7 +209,7 @@ UINT32 Example_EventEntry(VOID) 编译运行得到的结果为: - + ``` Example_Event wait event 0x1 Example_TaskEntry write event. diff --git a/zh-cn/device-dev/kernel/kernel-small-basic-trans-mutex.md b/zh-cn/device-dev/kernel/kernel-small-basic-trans-mutex.md index cfa4fdba5ea9cb2f6ac2b4126d8fe9058b2728fb..34a11809784b79c61dbeebbadbe086d216bc60ce 100644 --- a/zh-cn/device-dev/kernel/kernel-small-basic-trans-mutex.md +++ b/zh-cn/device-dev/kernel/kernel-small-basic-trans-mutex.md @@ -104,13 +104,13 @@ 本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数Example_MutexEntry。 示例代码如下: - + ``` #include #include "los_mux.h" /* 互斥锁 */ -LosMux g_testMux; +LosMux g_testMutex; /* 任务ID */ UINT32 g_testTaskId01; UINT32 g_testTaskId02; @@ -118,48 +118,49 @@ UINT32 g_testTaskId02; VOID Example_MutexTask1(VOID) { UINT32 ret; + LOS_TaskDelay(50); - printf("task1 try to get mutex, wait 10 ticks.\n"); + dprintf("task1 try to get mutex, wait 10 ticks.\n"); /* 申请互斥锁 */ - ret = LOS_MuxLock(&g_testMux, 10); + ret = LOS_MuxLock(&g_testMutex, 10); if (ret == LOS_OK) { - printf("task1 get mutex g_testMux.\n"); + dprintf("task1 get mutex g_testMux.\n"); /* 释放互斥锁 */ - LOS_MuxUnlock(&g_testMux); + LOS_MuxUnlock(&g_testMutex); return; - } - if (ret == LOS_ETIMEDOUT ) { - printf("task1 timeout and try to get mutex, wait forever.\n"); - /* 申请互斥锁 */ - ret = LOS_MuxLock(&g_testMux, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("task1 wait forever, get mutex g_testMux.\n"); - /* 释放互斥锁 */ - LOS_MuxUnlock(&g_testMux); - /* 删除互斥锁 */ - LOS_MuxDestroy(&g_testMux); - printf("task1 post and delete mutex g_testMux.\n"); - return; - } + } + if (ret == LOS_ETIMEDOUT) { + dprintf("task1 timeout and try to get mutex, wait forever.\n"); + /* 申请互斥锁 */ + ret = LOS_MuxLock(&g_testMutex, LOS_WAIT_FOREVER); + if (ret == LOS_OK) { + dprintf("task1 wait forever, get mutex g_testMux.\n"); + /* 释放互斥锁 */ + LOS_MuxUnlock(&g_testMutex); + /* 删除互斥锁 */ + LOS_MuxDestroy(&g_testMutex); + dprintf("task1 post and delete mutex g_testMux.\n"); + return; + } } return; } VOID Example_MutexTask2(VOID) { - printf("task2 try to get mutex, wait forever.\n"); + dprintf("task2 try to get mutex, wait forever.\n"); /* 申请互斥锁 */ - (VOID)LOS_MuxLock(&g_testMux, LOS_WAIT_FOREVER); + (VOID)LOS_MuxLock(&g_testMutex, LOS_WAIT_FOREVER); - printf("task2 get mutex g_testMux and suspend 100 ticks.\n"); + dprintf("task2 get mutex g_testMux and suspend 100 ticks.\n"); /* 任务休眠100Ticks */ LOS_TaskDelay(100); - printf("task2 resumed and post the g_testMux\n"); + dprintf("task2 resumed and post the g_testMux\n"); /* 释放互斥锁 */ - LOS_MuxUnlock(&g_testMux); + LOS_MuxUnlock(&g_testMutex); return; } @@ -170,7 +171,7 @@ UINT32 Example_MutexEntry(VOID) TSK_INIT_PARAM_S task2; /* 初始化互斥锁 */ - LOS_MuxInit(&g_testMux, NULL); + LOS_MuxInit(&g_testMutex, NULL); /* 锁任务调度 */ LOS_TaskLock(); @@ -183,7 +184,7 @@ UINT32 Example_MutexEntry(VOID) task1.usTaskPrio = 5; ret = LOS_TaskCreate(&g_testTaskId01, &task1); if (ret != LOS_OK) { - printf("task1 create failed.\n"); + dprintf("task1 create failed.\n"); return LOS_NOK; } @@ -195,7 +196,7 @@ UINT32 Example_MutexEntry(VOID) task2.usTaskPrio = 4; ret = LOS_TaskCreate(&g_testTaskId02, &task2); if (ret != LOS_OK) { - printf("task2 create failed.\n"); + dprintf("task2 create failed.\n"); return LOS_NOK; } @@ -210,11 +211,11 @@ UINT32 Example_MutexEntry(VOID) 编译运行得到的结果为: - + ``` -task1 try to get mutex, wait 10 ticks. task2 try to get mutex, wait forever. task2 get mutex g_testMux and suspend 100 ticks. +task1 try to get mutex, wait 10 ticks. task1 timeout and try to get mutex, wait forever. task2 resumed and post the g_testMux task1 wait forever, get mutex g_testMux. diff --git a/zh-cn/device-dev/kernel/kernel-small-basic-trans-queue.md b/zh-cn/device-dev/kernel/kernel-small-basic-trans-queue.md index 30003b1eb5c286093b479c79a8670e07838e8545..28c7569cd2512f74a1243c0bd684b5037def56e0 100644 --- a/zh-cn/device-dev/kernel/kernel-small-basic-trans-queue.md +++ b/zh-cn/device-dev/kernel/kernel-small-basic-trans-queue.md @@ -31,7 +31,7 @@ ### 队列控制块 - + ``` /** * 队列控制块数据结构 @@ -137,7 +137,9 @@ typedef struct { ### 编程示例 -本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数ExampleQueue。 +本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数ExampleQueue, + +为方便用户观察,建议调用ExampleQueue前先调用 LOS_Msleep(5000) 进行短时间延时,避免其他打印过多。 示例代码如下: @@ -155,7 +157,7 @@ VOID SendEntry(VOID) ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0); if(ret != LOS_OK) { - printf("send message failure, error: %x\n", ret); + dprintf("send message failure, error: %x\n", ret); } } @@ -165,30 +167,36 @@ VOID RecvEntry(VOID) CHAR readBuf[BUFFER_LEN] = {0}; UINT32 readLen = BUFFER_LEN; - //休眠1s - usleep(1000000); + LOS_Msleep(1000); ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0); if(ret != LOS_OK) { - printf("recv message failure, error: %x\n", ret); + dprintf("recv message failure, error: %x\n", ret); } - printf("recv message: %s\n", readBuf); + dprintf("recv message: %s\n", readBuf); ret = LOS_QueueDelete(g_queue); if(ret != LOS_OK) { - printf("delete the queue failure, error: %x\n", ret); + dprintf("delete the queue failure, error: %x\n", ret); } - printf("delete the queue success!\n"); + dprintf("delete the queue success!\n"); } UINT32 ExampleQueue(VOID) { - printf("start queue example\n"); + dprintf("start queue example\n"); UINT32 ret = 0; UINT32 task1, task2; TSK_INIT_PARAM_S initParam = {0}; + ret = LOS_QueueCreate("queue", 5, &g_queue, 0, 50); + if(ret != LOS_OK) { + dprintf("create queue failure, error: %x\n", ret); + } + + dprintf("create the queue success!\n"); + initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; initParam.usTaskPrio = 9; initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; @@ -197,7 +205,8 @@ UINT32 ExampleQueue(VOID) LOS_TaskLock(); ret = LOS_TaskCreate(&task1, &initParam); if(ret != LOS_OK) { - printf("create task1 failed, error: %x\n", ret); + dprintf("create task1 failed, error: %x\n", ret); + LOS_QueueDelete(g_queue); return ret; } @@ -205,17 +214,13 @@ UINT32 ExampleQueue(VOID) initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; ret = LOS_TaskCreate(&task2, &initParam); if(ret != LOS_OK) { - printf("create task2 failed, error: %x\n", ret); + dprintf("create task2 failed, error: %x\n", ret); + LOS_QueueDelete(g_queue); return ret; } - ret = LOS_QueueCreate("queue", 5, &g_queue, 0, 50); - if(ret != LOS_OK) { - printf("create queue failure, error: %x\n", ret); - } - - printf("create the queue success!\n"); LOS_TaskUnlock(); + LOS_Msleep(5000); return ret; } ``` @@ -225,9 +230,9 @@ UINT32 ExampleQueue(VOID) 编译运行得到的结果为: - + ``` -start test example +start queue example create the queue success! recv message: test message delete the queue success! diff --git a/zh-cn/device-dev/kernel/kernel-small-basic-trans-semaphore.md b/zh-cn/device-dev/kernel/kernel-small-basic-trans-semaphore.md index de95e53e7c38dab8a9f720652bfb9eac3e6e0da7..b15369f207ef711d378a57bc3f537467fda2db1e 100644 --- a/zh-cn/device-dev/kernel/kernel-small-basic-trans-semaphore.md +++ b/zh-cn/device-dev/kernel/kernel-small-basic-trans-semaphore.md @@ -22,7 +22,7 @@ **信号量控制块** - + ``` /** * 信号量控制块数据结构 @@ -129,7 +129,8 @@ static UINT32 g_testTaskId01; static UINT32 g_testTaskId02; /* 测试任务优先级 */ -#define TASK_PRIO_TEST 5 +#define TASK_PRIO_LOW 5 +#define TASK_PRIO_HI 4 /* 信号量结构体id */ static UINT32 g_semId; @@ -138,11 +139,10 @@ VOID ExampleSemTask1(VOID) { UINT32 ret; - printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); + dprintf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); /* 定时阻塞模式申请信号量,定时时间为10ticks */ ret = LOS_SemPend(g_semId, 10); - /* 申请到信号量 */ if (ret == LOS_OK) { LOS_SemPost(g_semId); @@ -150,12 +150,13 @@ VOID ExampleSemTask1(VOID) } /* 定时时间到,未申请到信号量 */ if (ret == LOS_ERRNO_SEM_TIMEOUT) { - printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); + dprintf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); /*永久阻塞模式申请信号量*/ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - printf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); + dprintf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); if (ret == LOS_OK) { + dprintf("ExampleSemTask1 post sem g_semId.\n"); LOS_SemPost(g_semId); return; } @@ -165,19 +166,18 @@ VOID ExampleSemTask1(VOID) VOID ExampleSemTask2(VOID) { UINT32 ret; - printf("ExampleSemTask2 try get sem g_semId wait forever.\n"); + dprintf("ExampleSemTask2 try get sem g_semId wait forever.\n"); /* 永久阻塞模式申请信号量 */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); + dprintf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); } /* 任务休眠20 ticks */ LOS_TaskDelay(20); - printf("ExampleSemTask2 post sem g_semId.\n"); + dprintf("ExampleSemTask2 post sem g_semId.\n"); /* 释放信号量 */ LOS_SemPost(g_semId); return; @@ -200,10 +200,10 @@ UINT32 ExampleSem(VOID) task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1; task1.pcName = "TestTask1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = TASK_PRIO_TEST; + task1.usTaskPrio = TASK_PRIO_LOW; ret = LOS_TaskCreate(&g_testTaskId01, &task1); if (ret != LOS_OK) { - printf("task1 create failed .\n"); + dprintf("task1 create failed .\n"); return LOS_NOK; } @@ -212,16 +212,19 @@ UINT32 ExampleSem(VOID) task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2; task2.pcName = "TestTask2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task2.usTaskPrio = (TASK_PRIO_TEST - 1); + task2.usTaskPrio = TASK_PRIO_HI; ret = LOS_TaskCreate(&g_testTaskId02, &task2); if (ret != LOS_OK) { - printf("task2 create failed.\n"); + dprintf("task2 create failed.\n"); return LOS_NOK; } /* 解锁任务调度 */ LOS_TaskUnlock(); + /* 任务休眠400 ticks */ + LOS_TaskDelay(400); + ret = LOS_SemPost(g_semId); /* 任务休眠400 ticks */ @@ -238,12 +241,13 @@ UINT32 ExampleSem(VOID) 编译运行得到的结果为: - + ``` ExampleSemTask2 try get sem g_semId wait forever. -ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 try get sem g_semId, timeout 10 ticks. ExampleSemTask1 timeout and try get sem g_semId wait forever. +ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask2 post sem g_semId. ExampleSemTask1 wait_forever and get sem g_semId. +ExampleSemTask1 post sem g_semId. ``` diff --git a/zh-cn/device-dev/kernel/kernel-small-debug-memory-info.md b/zh-cn/device-dev/kernel/kernel-small-debug-memory-info.md index 26a01840b82ee9836f48d19587fcc4292cf07b09..bad2be2d79deed987460895029a11df7463b97cb 100644 --- a/zh-cn/device-dev/kernel/kernel-small-debug-memory-info.md +++ b/zh-cn/device-dev/kernel/kernel-small-debug-memory-info.md @@ -14,7 +14,7 @@ ## 功能配置 -LOSCFG_MEM_WATERLINE:开关宏,默认关闭;若需要打开这个功能,可以在配置项中开启“Debug-> Enable memory pool waterline or not”。如需获取内存水线,需要打开该配置。 +LOSCFG_MEM_WATERLINE:开关宏,默认关闭;若需要打开这个功能,可以在配置项中开启“Debug-> Enable MEM Debug-> Enable memory pool waterline or not”。如需获取内存水线,需要打开该配置。 ## 开发指导 @@ -55,8 +55,9 @@ typedef struct { **示例代码** - 该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。 - 代码实现如下: +本演示代码在 . kernel /liteos_a/testsuites /kernel /src /osTest.c中编译验证,在TestTaskEntry中调用验证入口函数MemTest。 + +代码实现如下: ```c #include @@ -69,14 +70,14 @@ void MemInfoTaskFunc(void) { LOS_MEM_POOL_STATUS poolStatus = {0}; - /* pool为要统计信息的内存地址,此处以OS_SYS_MEM_ADDR为例 */ + /* pool为要统计信息的内存地址,此处以OS_SYS_MEM_ADDR为例 */ void *pool = OS_SYS_MEM_ADDR; LOS_MemInfoGet(pool, &poolStatus); /* 算出内存池当前的碎片率百分比 */ unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize; /* 算出内存池当前的使用率百分比 */ unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool); - printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, poolStatus.totalFreeSize, poolStatus.usageWaterLine); + dprintf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, poolStatus.totalFreeSize, poolStatus.usageWaterLine); } int MemTest(void) @@ -90,7 +91,7 @@ int MemTest(void) taskStatus.usTaskPrio = 10; ret = LOS_TaskCreate(&taskID, &taskStatus); if (ret != LOS_OK) { - printf("task create failed\n"); + dprintf("task create failed\n"); return LOS_NOK; } return LOS_OK; @@ -103,7 +104,7 @@ int MemTest(void) 编译运行输出的结果如下: - +根据实际运行环境,数据会有差异 ``` usage = 22, fragment = 3, maxFreeSize = 49056, totalFreeSize = 50132, waterLine = 1414 diff --git a/zh-cn/device-dev/kernel/kernel-small-debug-memory-leak.md b/zh-cn/device-dev/kernel/kernel-small-debug-memory-leak.md index 2bf89f37c1344da25d77bab943f1775c14b1ef75..97a08f31900427e34bb285509cd4dde83da25753 100644 --- a/zh-cn/device-dev/kernel/kernel-small-debug-memory-leak.md +++ b/zh-cn/device-dev/kernel/kernel-small-debug-memory-leak.md @@ -8,7 +8,7 @@ ## 功能配置 -1. LOSCFG_MEM_LEAKCHECK:开关宏,默认关闭;如需要打开这个功能,可以在配置项中开启“Debug-> Enable Function call stack of Mem operation recorded”。 +1. LOSCFG_MEM_LEAKCHECK:开关宏,默认关闭;如需要打开这个功能,可以在配置项中开启“Debug-> Enable MEM Debug-> Enable Function call stack of Mem operation recorded”。 2. LOS_RECORD_LR_CNT:记录的LR层数,默认3层;每层LR消耗sizeof(void \*)字节数的内存。 @@ -61,8 +61,10 @@ node size LR[0] LR[1] LR[2] **示例代码** +本演示代码在 . kernel /liteos_a/testsuites /kernel /src /osTest.c中编译验证,在TestTaskEntry中调用验证入口函数MemLeakTest。 + +为了方便展示建议创建新的内存池,需要在target_config.h 中定义 LOSCFG_MEM_MUL_POOL -该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试. 代码实现如下: ```c @@ -71,12 +73,24 @@ node size LR[0] LR[1] LR[2] #include "los_memory.h" #include "los_config.h" +#define TEST_NEW_POOL_SIZE 2000 +#define TEST_MALLOC_SIZE 8 + void MemLeakTest(void) { - OsMemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); - void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); - void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); - OsMemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); + VOID *pool = NULL; + + /* 由于原内存池分配过多, 为了方便展示, 创建新的内存池 */ + pool = LOS_MemAlloc(OS_SYS_MEM_ADDR, TEST_NEW_POOL_SIZE); + (VOID)LOS_MemInit(pool, TEST_NEW_POOL_SIZE); + + OsMemUsedNodeShow(pool); + void *ptr1 = LOS_MemAlloc(pool, TEST_MALLOC_SIZE); + void *ptr2 = LOS_MemAlloc(pool, TEST_MALLOC_SIZE); + OsMemUsedNodeShow(pool); + + /* 释放内存池 */ + (VOID)LOS_MemDeInit(pool); } ``` @@ -87,51 +101,50 @@ void MemLeakTest(void) 编译运行输出log如下: ``` -node size LR[0] LR[1] LR[2] -0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc -0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc -0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e -0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a -0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 - -node size LR[0] LR[1] LR[2] -0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc -0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc -0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e -0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a -0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 -0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +/* 第一次OsMemUsedNodeShow打印,由于该内存池未分配,所以无内存节点 */ +node LR[0] LR[1] LR[2] + + +/* 第二次OsMemUsedNodeShow打印,有两个新的内存节点 */ +node LR[0] LR[1] LR[2] +0x00402e0d90: 0x004009f040 0x0040037614 0x0040005480 +0x00402e0db0: 0x004009f04c 0x0040037614 0x0040005480 + ``` 对比两次log,差异如下,这些内存节点就是疑似泄漏的内存块: ``` -0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +0x00402e0d90: 0x004009f040 0x0040037614 0x0040005480 +0x00402e0db0: 0x004009f04c 0x0040037614 0x0040005480 ``` 部分汇编文件如下: ``` - MemLeakTest: - 0x80041d4: 0xb510 PUSH {R4, LR} - 0x80041d6: 0x4ca8 LDR.N R4, [PC, #0x2a0] ; g_memStart - 0x80041d8: 0x0020 MOVS R0, R4 - 0x80041da: 0xf7fd 0xf93e BL LOS_MemUsedNodeShow ; 0x800145a - 0x80041de: 0x2108 MOVS R1, #8 - 0x80041e0: 0x0020 MOVS R0, R4 - 0x80041e2: 0xf7fd 0xfbd9 BL LOS_MemAlloc ; 0x8001998 - 0x80041e6: 0x2108 MOVS R1, #8 - 0x80041e8: 0x0020 MOVS R0, R4 - 0x80041ea: 0xf7fd 0xfbd5 BL LOS_MemAlloc ; 0x8001998 - 0x80041ee: 0x0020 MOVS R0, R4 - 0x80041f0: 0xf7fd 0xf933 BL LOS_MemUsedNodeShow ; 0x800145a - 0x80041f4: 0xbd10 POP {R4, PC} - 0x80041f6: 0x0000 MOVS R0, R0 +4009f014: 7d 1e a0 e3 mov r1, #2000 +4009f018: 00 00 90 e5 ldr r0, [r0] +4009f01c: 67 7a fe eb bl #-398948 +4009f020: 7d 1e a0 e3 mov r1, #2000 +4009f024: 00 40 a0 e1 mov r4, r0 +4009f028: c7 79 fe eb bl #-399588 +4009f02c: 04 00 a0 e1 mov r0, r4 +4009f030: 43 78 fe eb bl #-401140 +4009f034: 04 00 a0 e1 mov r0, r4 +4009f038: 08 10 a0 e3 mov r1, #8 +4009f03c: 5f 7a fe eb bl #-398980 +4009f040: 04 00 a0 e1 mov r0, r4 +4009f044: 08 10 a0 e3 mov r1, #8 +4009f048: 5c 7a fe eb bl #-398992 +4009f04c: 04 00 a0 e1 mov r0, r4 +4009f050: 3b 78 fe eb bl #-401172 +4009f054: 3c 00 9f e5 ldr r0, [pc, #60] +4009f058: 40 b8 fe eb bl #-335616 +4009f05c: 04 00 a0 e1 mov r0, r4 +4009f060: 2c 7a fe eb bl #-399184 ``` -其中,通过查找0x080041ee,就可以发现该内存节点是在MemLeakTest接口里申请的且是没有释放的。 +其中,通过查找0x4009f040,就可以发现该内存节点是在MemLeakTest接口里申请的且是没有释放的。 diff --git a/zh-cn/device-dev/kernel/kernel-mini-memory-perf.md b/zh-cn/device-dev/kernel/kernel-small-debug-perf.md similarity index 51% rename from zh-cn/device-dev/kernel/kernel-mini-memory-perf.md rename to zh-cn/device-dev/kernel/kernel-small-debug-perf.md index bb16cd80a5a72e77cb63e84eb1e0e1fdc382f6dd..d0fd27d409de6dbbf7d5a9e565a731306409aa54 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-memory-perf.md +++ b/zh-cn/device-dev/kernel/kernel-small-debug-perf.md @@ -17,9 +17,6 @@ Perf提供2种工作模式,计数模式和采样模式。 ## 接口说明 - -### 内核态 - OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细信息可以查看[API](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h)参考。 **表1** Perf模块接口说明 @@ -63,30 +60,6 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细 刷cache接口视具体的平台自行配置。 -### 用户态 - - -新增perf字符设备,位于"/dev/perf",通过对设备节点的read\write\ioctl,实现用户态perf的读写和控制: - - -- read: 用户态读取perf记录数据 - -- write: 用户态采样事件配置 - -- ioctl: 用户态Perf控制操作,包括 - - ```c - #define PERF_IOC_MAGIC 'T' - #define PERF_START _IO(PERF_IOC_MAGIC, 1) - #define PERF_STOP _IO(PERF_IOC_MAGIC, 2) - ``` - - 分别对应Perf启动(LOS_PerfStart)、停止(LOS_PerfStop) - - -具体的使用方法参见[用户态编程实例](#用户态编程实例)。 - - ## 开发指导 @@ -140,14 +113,33 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细 #### 内核态示例代码 -前提条件:在menuconfig菜单中完成perf模块的配置。 +前提条件:在menuconfig菜单中完成perf模块的配置, 并勾选Enable Hook Feature,Enable Software Events for Sampling。 -该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。 +为方便学习,本演示代码直接在 . kernel /liteos_a/testsuites /kernel /src /osTest.c中编译验证即可。 - 实例代码如下: +实例代码如下: ```c #include "los_perf.h" +#define TEST_MALLOC_SIZE 200 +#define TEST_TIME 5 + +/* 验证函数中进行malloc和free */ +VOID test(VOID) +{ + VOID *p = NULL; + int i; + for (i = 0; i < TEST_TIME; i++) { + p = LOS_MemAlloc(m_aucSysMem1, TEST_MALLOC_SIZE); + if (p == NULL) { + PRINT_ERR("test alloc failed\n"); + return; + } + + (VOID)LOS_MemFree(m_aucSysMem1, p); + } +} + STATIC VOID OsPrintBuff(const CHAR *buf, UINT32 num) { UINT32 i = 0; @@ -167,12 +159,18 @@ STATIC VOID perfTestHwEvent(VOID) UINT32 ret; CHAR *buf = NULL; UINT32 len; + + //LOS_PerfInit(NULL, 0); + + PerfConfigAttr attr = { .eventsCfg = { - .type = PERF_EVENT_TYPE_HW, + .type = PERF_EVENT_TYPE_SW, .events = { - [0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF}, - [1] = {PERF_COUNT_HW_BRANCH_INSTRUCTIONS, 0xFFFFFF00}, + [0] = {PERF_COUNT_SW_TASK_SWITCH, 0xff}, /* 抓取调度 */ + [1] = {PERF_COUNT_SW_MEM_ALLOC, 0xff}, /* 抓取内存分配 */ + + PERF_COUNT_SW_TASK_SWITCH }, .eventsNr = 2, .predivided = 1, /* cycle counter increase every 64 cycles */ @@ -207,20 +205,20 @@ STATIC VOID perfTestHwEvent(VOID) OsPrintBuff(buf, len); /* print data */ (VOID)LOS_MemFree(m_aucSysMem1, buf); } + UINT32 Example_Perf_test(VOID) { UINT32 ret; - TSK_INIT_PARAM_S perfTestTask; + TSK_INIT_PARAM_S perfTestTask = {0}; + UINT32 taskID; /* 创建用于perf测试的任务 */ - memset(&perfTestTask, 0, sizeof(TSK_INIT_PARAM_S)); perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent; perfTestTask.pcName = "TestPerfTsk"; /* 测试任务名称 */ - perfTestTask.uwStackSize = 0x800; // 0x8000: perf test task stack size + perfTestTask.uwStackSize = 0x1000; // 0x8000: perf test task stack size perfTestTask.usTaskPrio = 5; // 5: perf test task priority - perfTestTask.uwResved = LOS_TASK_STATUS_DETACHED; - ret = LOS_TaskCreate(&g_perfTestTaskId, &perfTestTask); + ret = LOS_TaskCreate(&taskID, &perfTestTask); if (ret != LOS_OK) { - PRINT_ERR("PerfTestTask create failed.\n"); + PRINT_ERR("PerfTestTask create failed. 0x%x\n", ret); return LOS_NOK; } return LOS_OK; @@ -234,13 +232,29 @@ LOS_MODULE_INIT(perfTestHwEvent, LOS_INIT_LEVEL_KMOD_EXTENDED); 输出结果如下: ``` ---------count mode---------- -[EMG] [cycles] eventType: 0xff: 5466989440 -[EMG] [branches] eventType: 0xc: 602166445 -------- sample mode---------- -[EMG] dump section data, addr: 0x8000000 length: 0x800000 -num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ... -hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 +type: 2 +events[0]: 1, 0xff +events[1]: 3, 0xff +predivided: 1 +sampleType: 0x60 +needSample: 0 +------count mode------ +[task switch] eventType: 0x1 [core 0]: 0 +[mem alloc] eventType: 0x3 [core 0]: 5 +time used: 0.005000(s) +--------sample mode------ +type: 2 +events[0]: 1, 0xff +events[1]: 3, 0xff +predivided: 1 +sampleType: 0x60 +needSample: 1 +dump perf data, addr: 0x402c3e6c length: 0x5000 +time used: 0.000000(s) +num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 +hex: 00 ffffffef ffffffef ffffffef 02 00 00 00 14 00 00 00 60 00 00 00 02 00 00 00 + +根据实际运行环境,过程打印会有差异 ``` - 针对计数模式,系统在perf stop后会打印: @@ -254,184 +268,3 @@ hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 用户可以通过JTAG口导出该片内存,再使用IDE线下工具解析。 或者通过LOS_PerfDataRead将数据读到指定地址,进行查看或进一步处理。示例中OsPrintBuff为测试接口,其按字节打印Read到的采样数据,num表示第几个字节,hex表示该字节中的数值。 - - -### 用户态开发流程 - -通过在menuconfig配置"Driver->Enable PERF DRIVER",开启Perf驱动。该配置仅在内核Enable Perf Feature后,才可在Driver的选项中可见。 - -1. 打开“/dev/perf”字符文件,进行读写和IOCTL操作; - -2. 系统提供用户态的perf命令,该命令位于/bin目录下,cd bin 后可执行如下命令: - - ./perf start [id] 启动perf采样, id 为可选项,默认值为0 - - ./perf stop 停止perf采样 - - ./perf read <nBytes> 从采样缓冲区中读取nBytes数据并打印内容 - - ./perf list 罗列-e支持的具体事件 - - ./perf stat/record [option] <command> 计数/采样模式命令 - - option可选如下: - - -e,配置采样事件。可使用./perf list 中罗列的同类型事件。 - - -p,配置事件采样周期。 - - -o,指定perf采样数据结果保存的文件路径。 - - -t,任务Id过滤(白名单),只采取指定任务中的上下文。如果不指定改参数,则默认采集所有的任务。 - - -s,配置采样的具体上下文类型,可查阅los_perf.h中定义的PerfSampleType。 - - -P,进程Id过滤(白名单),只采取指定进程中的上下文。如果不指定改参数,则默认采集所有进程。 - - -d,是否进行分频(事件每发生64次累计+1),该选项仅在硬件cycle事件上生效。 - - command 为待统计的子程序。 - -用户态命令行的典型使用方法如下: - -./perf list 查看可使用的事件列表, 输出如下: - - -``` -cycles [Hardware event] -instruction [Hardware event] -dcache [Hardware event] -dcache-miss [Hardware event] -icache [Hardware event] -icache-miss [Hardware event] -branch [Hardware event] -branch-miss [Hardware event] -clock [Timed event] -task-switch [Software event] -irq-in [Software event] -mem-alloc [Software event] -mux-pend [Software event] -``` - -./perf stat -e cycles os_dump, 输出如下: - - -``` -type: 0 -events[0]: 255, 0xffff -predivided: 0 -sampleType: 0x0 -needSample: 0 -usage os_dump [--help | -l | SERVICE] - --help: shows this help - -l: only list services, do not dump them - SERVICE: dumps only service SERVICE -time used: 0.058000(s) -[cycles] eventType: 0xff [core 0]: 21720647 -[cycles] eventType: 0xff [core 1]: 13583830 -``` - -./perf record -e cycles os_dump, 输出如下: - - -``` -type: 0 -events[0]: 255, 0xffff -predivided: 0 -sampleType: 0x60 -needSample: 1 -usage os_dump [--help | -l | SERVICE] - --help: shows this help - -l: only list services, do not dump them - SERVICE: dumps only service SERVICE -dump perf data, addr: 0x408643d8 length: 0x5000 -time used: 0.059000(s) -save perf data success at /storage/data/perf.data -``` - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 在进行./perf stat/record命令后,用户可多次执行./perf start 和 ./perf stop进行采样, 采样的事件配置为最近一次执行./perfstat/record 中设置的参数。 - - -#### 用户态编程实例 - -本实例实现如下功能: - -1. 打开perf字符设备。 - -2. 写perf配置事件。 - -3. 启动perf。 - -4. 停止perf。 - -5. 读取perf采样数据。 - - -#### 用户态示例代码 - - 实例代码如下: - -```c -#include "fcntl.h" -#include "user_copy.h" -#include "sys/ioctl.h" -#include "fs/driver.h" -#include "los_dev_perf.h" -#include "los_perf.h" -#include "los_init.h" -/* perf ioctl */ -#define PERF_IOC_MAGIC 'T' -#define PERF_START _IO(PERF_IOC_MAGIC, 1) -#define PERF_STOP _IO(PERF_IOC_MAGIC, 2) - -int main(int argc, char **argv) -{ - char *buf = NULL; - ssize_t len; - int fd = open("/dev/perf", O_RDWR); - if (fd == -1) { - printf("Perf open failed.\n"); - exit(EXIT_FAILURE); - } - PerfConfigAttr attr = { - .eventsCfg = { -#ifdef LOSCFG_PERF_HW_PMU - .type = PERF_EVENT_TYPE_HW, - .events = { - [0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF}, - }, -#elif defined LOSCFG_PERF_TIMED_PMU - .type = PERF_EVENT_TYPE_TIMED, - .events = { - [0] = {PERF_COUNT_CPU_CLOCK, 100}, - }, -#elif defined LOSCFG_PERF_SW_PMU - .type = PERF_EVENT_TYPE_SW, - .events = { - [0] = {PERF_COUNT_SW_TASK_SWITCH, 1}, - }, -#endif - .eventsNr = 1, /* 1 event */ - .predivided = 0, - }, - .taskIds = {0}, - .taskIdsNr = 0, - .processIds = {0}, - .processIdsNr = 0, - .needSample = 1, - .sampleType = PERF_RECORD_IP | PERF_RECORD_CALLCHAIN, - }; - (void)write(fd, &attr, sizeof(PerfConfigAttr)); /* perf config */ - ioctl(fd, PERF_START, NULL); /* perf start */ - test(); - ioctl(fd, PERF_STOP, NULL); /* perf stop */ - buf = (char *)malloc(LOSCFG_PERF_BUFFER_SIZE); - if (buf == NULL) { - printf("no memory for read perf 0x%x\n", LOSCFG_PERF_BUFFER_SIZE); - return -1; - } - len = read(fd, buf, LOSCFG_PERF_BUFFER_SIZE); - OsPrintBuff(buf, len); /* print data */ - free(buf); - close(fd); - return 0; -} -``` - - -#### 用户态结果验证 - - 输出结果如下 - -``` -[EMG] dump section data, addr: 0x8000000 length: 0x800000 -num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ... -hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 -``` diff --git a/zh-cn/device-dev/kernel/kernel-small-debug-process-cpu.md b/zh-cn/device-dev/kernel/kernel-small-debug-process-cpu.md index dc21d9c19cbfbe24347826a853e96cddf8b19f0b..0da63e4873506c9ae019e5e2affaae47cbe15d92 100644 --- a/zh-cn/device-dev/kernel/kernel-small-debug-process-cpu.md +++ b/zh-cn/device-dev/kernel/kernel-small-debug-process-cpu.md @@ -103,7 +103,7 @@ CPU占用率的典型开发流程: **示例代码** -该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。 +本演示代码在 . kernel /liteos_a/testsuites /kernel /src /osTest.c中编译验证,在TestTaskEntry中调用验证入口函数CpupTest。 代码实现如下: @@ -114,12 +114,13 @@ CPU占用率的典型开发流程: UINT32 g_cpuTestTaskID; VOID ExampleCpup(VOID) { - printf("entry cpup test example\n"); - while (1) { + int i = 0; + dprintf("entry cpup test example\n"); + for (i = 0; i < 10; i++) { usleep(100); // 100: delay for 100ms } } -UINT32 ItCpupTest(VOID) +UINT32 CpupTest(VOID) { UINT32 ret; UINT32 cpupUse; @@ -138,12 +139,12 @@ UINT32 ItCpupTest(VOID) usleep(100); // 100: delay for 100ms /* 获取当前系统历史CPU占用率 */ - cpupUse = LOS_HistorySysCpuUsage(CPU_LESS_THAN_1S); - printf("the history system cpu usage in all time:%u.%u\n", + cpupUse = LOS_HistorySysCpuUsage(CPUP_LAST_ONE_SECONDS); + dprintf("the history system cpu usage in all time:%u.%u\n", cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); /* 获取指定任务的CPU占用率,该测试例程中指定的任务为以上创建的cpup测试任务 */ - cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPU_LESS_THAN_1S); - printf("cpu usage of the cpupTestTask in all time:\n TaskID: %d\n usage: %u.%u\n", + cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPUP_LAST_ONE_SECONDS); + dprintf("cpu usage of the cpupTestTask in all time:\n TaskID: %d\n usage: %u.%u\n", g_cpuTestTaskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); return LOS_OK; } @@ -158,4 +159,6 @@ UINT32 ItCpupTest(VOID) entry cpup test example the history system cpu usage in all time: 3.0 cpu usage of the cpupTestTask in all time: TaskID:10 usage: 0.0 + +根据实际运行环境,打印会有差异 ``` diff --git a/zh-cn/device-dev/kernel/kernel-small-start-kernel.md b/zh-cn/device-dev/kernel/kernel-small-start-kernel.md index b3c404db571376ac13c774c4c711313f4822485d..4e6910d864289a9438b4da677ad9121f540e9052 100644 --- a/zh-cn/device-dev/kernel/kernel-small-start-kernel.md +++ b/zh-cn/device-dev/kernel/kernel-small-start-kernel.md @@ -34,38 +34,35 @@ 新增一个内核模块,需要在内核初始化时进行该模块的初始化,则通过内核启动框架将该模块的初始化函数注册进内核启动流程中。 +为方便学习,本演示代码直接在 . kernel /liteos_a/testsuites /kernel /src /osTest.c中编译验证即可。 **示例代码** - - ```c /* 内核启动框架头文件 */ #include "los_init.h" -...... /* 新增模块的初始化函数 */ unsigned int OsSampleModInit(void) { PRINTK("OsSampleModInit SUCCESS!\n"); - ...... } -...... + /* 在启动框架的目标层级中注册新增模块 */ LOS_MODULE_INIT(OsSampleModInit, LOS_INIT_LEVEL_KMOD_EXTENDED); ``` - **结果验证** - - ``` + main core booting up... + +/* 根据实际运行环境,过程打印会有差异 */ +...... + +/* 打印测试代码新增模块初始化函数 */ OsSampleModInit SUCCESS! -releasing 1 secondary cores -cpu 1 entering scheduler -cpu 0 entering scheduler ``` diff --git a/zh-cn/device-dev/kernel/kernel-small-start-user.md b/zh-cn/device-dev/kernel/kernel-small-start-user.md index ffef4f2e6e98ca0ab771278e8d324dd21639237b..98aae2d70f84c258cdfeb936f131662b20d12ed4 100644 --- a/zh-cn/device-dev/kernel/kernel-small-start-user.md +++ b/zh-cn/device-dev/kernel/kernel-small-start-user.md @@ -27,7 +27,7 @@ LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args) } ``` -> 上述启动代码在 kernel/liteos_a/kernel/user/src/los_user_init.c 中,g_initPath 根据启动设置的不同,其值为 /dev/shm/init 或 /bin/init。 +> 上述启动代码已在 kernel/liteos_a/kernel/user/src/los_user_init.c 中,g_initPath 根据启动设置的不同,其值为 /dev/shm/init 或 /bin/init。 系统启动阶段,OsUserInitProcess启动init进程。具体过程如下: diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index 32d43d93b21bc8ad5cdfe87edb04590682503f51..145ddb7b481de8709acd0bc856058d791d333b65 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -290,7 +290,7 @@ - [魔法键使用方法](kernel/kernel-small-debug-shell-magickey.md) - [用户态异常信息说明](kernel/kernel-small-debug-shell-error.md) - [Trace调测](kernel/kernel-small-debug-trace.md) - - [Perf调测](kernel/kernel-mini-memory-perf.md) + - [Perf调测](kernel/kernel-small-debug-perf.md) - [LMS调测](kernel/kernel-small-memory-lms.md) - [进程调测](kernel/kernel-small-debug-process-cpu.md) - 内核态内存调测 diff --git "a/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" index b28f930b1bda7d024df928465943d587126dc544..383fff4ce6aa3be54a37bf51e936dfae2a6527b9 100755 --- "a/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" @@ -56,7 +56,7 @@ ``` /base/global -├── i18n_standard # 国际化框架代码仓 +├── i18n # 国际化框架代码仓 │ ├── frameworks # 国际化框架核心代码 │ ├── interfaces # 国际化框架接口 │ │ ├── js # 国际化框架JavaScript接口 @@ -78,7 +78,7 @@ [global\_i18n\_lite](https://gitee.com/openharmony/global_i18n_lite) -[global\_i18n\_standard](https://gitee.com/openharmony/global_i18n_standard) +[global\_i18n](https://gitee.com/openharmony/global_i18n) [global\_resmgr\_lite](https://gitee.com/openharmony/global_resmgr_lite) diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md new file mode 100644 index 0000000000000000000000000000000000000000..9bafd21ac6fb7ae6c2c408565476ece681a45c4d --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md @@ -0,0 +1,150 @@ +# OpenHarmony 3.1.5 Release + + +## 版本概述 + +当前版本在OpenHarmony 3.1.4 Release的基础上,修复了内存泄漏及linux kernel等开源组件的安全漏洞,增强了系统安全性。修复了部分系统稳定性的issue,增强了系统稳定性。更新配套的SDK版本,修复了预览器相关的问题。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.1.5 Release | NA | +| Full SDK | Ohos_sdk_full 3.1.11.5 (API Version 8 Relese) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md)。 | +| Public SDK | Ohos_sdk_public 3.1.11.5 (API Version 8 Release) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
DevEco Studio 3.0 Beta4版本起,通过DevEco Studio获取的SDK默认为Public SDK。 | +| HUAWEI DevEco Studio(可选) | 3.1 Preview for OpenHarmony | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 3.0 Release | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee账号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)** + +通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.5-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**方式二** + +通过repo + https 下载。 + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.5-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + +**表2** 获取源码路径 + +| 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/OpenHarmony-v3.1.5-Release.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/OpenHarmony-v3.1.5-Release.tar.gz.sha256) | +| Hi3516标准系统解决方案(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_hi3516.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_hi3516.tar.gz.sha256) | +| RK3568标准系统解决方案(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_rk3568.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_rk3568.tar.gz.sha256) | +| Hi3861轻量系统解决方案(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_pegasus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_pegasus.tar.gz.sha256) | +| Hi3516小型系统解决方案-LiteOS(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus.tar.gz.sha256) | +| Hi3516小型系统解决方案-Linux(二进制) | 3.1.5 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus_linux.tar.gz.sha256) | +| 标准系统Full SDK包(Mac) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-full.tar.gz.sha256) | +| 标准系统Full SDK包(Windows\Linux) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-full.tar.gz.sha256) | +| 标准系统Public SDK包(Mac) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-public.tar.gz.sha256) | +| 标准系统Public SDK包(Windows\Linux) | 3.1.11.4 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-public.tar.gz.sha256) | + + +## 更新说明 + +本版本在OpenHarmony 3.1.4 Release的基础上有如下变更。 + + +### 特性变更 + +本次版本无新增特性及变更。 + +### API变更 + +3.1.5 Release对比3.1.4 Release API接口无变更。 + + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +### 修复缺陷列表 + +**表3** 修复缺陷issue列表 + +| 子系统 | 问题描述 | +| -------------- | ------------------------------------------------------------ | +| SDK子系统 | 修复了预览器相关的一些问题。 | +| 网络管理子系统 | 进程com.ohos.netmanagersocket下线程1.ui出现了异常栈libconnection.z.so([I5IXWZ](https://gitee.com/openharmony/communication_netmanager_base/issues/I5IXWZ)) | +| Misc子系统 | request.download 下载时概率不上报complete事件([I5WZC6](https://gitee.com/openharmony/request_request/issues/I5WZC6)) | +| DFX子系统 | hdcd低概率出现cpp_crash([I65P94](https://gitee.com/openharmony/developtools_hdc/issues/I65P94)) | +| Arkui子系统 | 修复获焦组件通用属性异常的问题([I64YLA](https://gitee.com/openharmony/arkui_ace_engine/issues/I64YLA)) | + + + + +### 修复安全漏洞列表 + +**表4** 修复安全问题列表 + +| ISSUE | 问题描述 | 修复链接 | +| -------- | -------- | -------- | +| I5UHSG | 修复组件das u-boot上的CVE-2022-2347安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_u-boot/pulls/62) | +| I5UI3F/I5VGDV | 修复组件kernel_linux_5.10上的CVE-2022-3303、CVE-2022-42703、CVE-2022-20422、CVE-2022-41222、CVE-2022-3239、CVE-2022-20423、CVE-2022-41850安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_expat/pulls/23) | +| I5XU3W | 修复组件kernel_linux_5.10上的CVE-2022-3586、CVE-2022-3625、CVE-2022-42432、CVE-2022-3633、CVE-2022-3635、CVE-2022-3629、CVE-2022-3623、CVE-2022-3646、CVE-2022-3621、CVE-2022-3567、CVE-2022-43750、CVE-2022-3545、CVE-2022-2978、CVE-2022-3523、CVE-2022-2602、CVE-2022-3628安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/541) | +| I5XUCJ | 修复组件kernel_linux_5.10上的CVE-2022-40768、CVE-2022-3577、CVE-2022-20409、CVE-2022-3566、CVE-2022-3606、CVE-2022-3564、CVE-2022-3649安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/505) | +| I5VGIU | 修复组件kernel_linux_5.10上的CVE-2022-3169安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/553) | +| I63VFW | 修复组件kernel_linux_5.10上的CVE-2022-41858安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/569) | +| I63VG7 | 修复组件kernel_linux_5.10上的CVE-2022-45934、CVE-2022-4129、CVE-2022-4378、CVE-2022-3108、CVE-2022-47518、CVE-2022-47521、CVE-2022-47519、CVE-2022-47520安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/586) | +| I66ZCI | 修复组件kernel_linux_5.10上的CVE-2022-3105、CVE-2022-3104、CVE-2022-3115、CVE-2022-3113、CVE-2022-3112安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/579) | +| I66ZHX | 修复组件kernel_linux_5.10上的CVE-2022-3111安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/584) | +| I66ZKM | 修复组件kernel_linux_5.10上的CVE-2022-3107安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/590) | +| I65T2H | 修复组件kernel_linux_5.10上的CVE-2022-20566安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/582) | +| I61HGX | 修复组件kernel_linux_5.10上的CVE-2022-42895、CVE-2022-42896安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/545) | +| I652LY | 修复组件kernel_linux_5.10上的CVE-2022-4139安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/567) | +| I65R2K | 修复组件python上的CVE-2022-42919安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/36) | +| I65R59 | 修复组件python上的CVE-2022-45061安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/37) | +| I65UJ8 | 修复组件python上的CVE-2022-45061安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/35) | +| I60GOT | 修复组件pixman上的CVE-2022-37454安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_pixman/pulls/11) | +| I5Z39U | 修复组件curl上的CVE-2022-32221、CVE-2022-42915、CVE-2022-42916安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_curl/pulls/91) | +| I61I8F | 修复组件ntfs-3g上的CVE-2022-40284安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_ntfs-3g/pulls/33) | +| I63V9Z | 修复组件libxml2上的CVE-2022-40303、CVE-2022-40304安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_libxml2/pulls/31) | diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md index 23f4ce5addb9e28937c2ca0033159fd160515eaf..44cfb4d87f548d6f399b822afd2b586d34584577 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-container.md @@ -2,8 +2,8 @@ OpenHarmony 3.2.10.1(Mr)版本相较于OpenHarmony 3.2.beta4版本,container子系统的API变更如下 -## cl.commonlibrary.1 错误码及信息变更 -commonlibrary子系统中ArrayList、List、LinkedList、Stack、Queue、Deque、PlainArray、LightWeightMap、LightWeightSet、HashMap、HashSet、TreeMap、TreeSet类的接口抛出的错误码及信息变更: +## cl.公共基础类库子系统.1 错误码及信息变更 +公共基础类库子系统子系统中ArrayList、List、LinkedList、Stack、Queue、Deque、PlainArray、LightWeightMap、LightWeightSet、HashMap、HashSet、TreeMap、TreeSet类的接口抛出的错误码及信息变更: 变更后的错误码详细介绍请参见[语言基础类库错误码](../../../application-dev/reference/errorcodes/errorcode-utils.md)。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-distributeddatamgr.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-distributeddatamgr.md index 71eb53fd2197c49afaf5bef27d214d075760cd54..8273daea910b4b07c5e8930e1a64910a673af1c9 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-distributeddatamgr.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-distributeddatamgr.md @@ -76,8 +76,8 @@ function getRdbStoreV9(context: Context, config: StoreConfigV9, version: number) ``` 从@ohos.data.rdb.d.ts 迁移至@ohos.data.relationalStore.d.ts: ``` -function getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback): void; -function getRdbStore(context: Context, config: StoreConfig, version: number): Promise; +function getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback): void; +function getRdbStore(context: Context, config: StoreConfig): Promise; ``` **适配指导** diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-media.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-media.md new file mode 100644 index 0000000000000000000000000000000000000000..1d1fadf9dbee56c3538e4462ee7936a364ec4445 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-media.md @@ -0,0 +1,312 @@ +# 媒体子系统ChangeLog + +## cl.media.1 播放功能接口变更 + +新增音视频播放接口[AVPlayer](../../../application-dev/reference/apis/js-apis-media.md#avplayer9)9+, 升级了状态机和错误码,推荐用户使用。旧版音频播放接口[AudioPlayer](../../../application-dev/reference/apis/js-apis-media.md#audioplayer)6+和视频播放接口[VideoPlayer](../../../application-dev/reference/apis/js-apis-media.md#videoplayer)8+停止维护。 + +**变更影响** + +原有的接口暂时可继续使用,但是停止维护,建议使用新接口进行开发。 + +**关键的接口/组件变更** + +新增接口如下: + +| 类名 | 新增接口声明 | +| -------------- | ------------------------------------------------------------ | +| media | createAVPlayer(callback: AsyncCallback\): void | +| media | createAVPlayer() : Promise\ | +| media.AVPlayer | interface AVPlayer | +| media.AVPlayer | videoScaleType ?: VideoScaleType | +| media.AVPlayer | url ?: string | +| media.AVPlayer | surfaceId ?: string | +| media.AVPlayer | stop(callback: AsyncCallback\): void | +| media.AVPlayer | stop(): Promise\ | +| media.AVPlayer | setVolume(volume: number): void | +| media.AVPlayer | setSpeed(speed: PlaybackSpeed): void | +| media.AVPlayer | setBitrate(bitrate: number): void | +| media.AVPlayer | seek(timeMs: number, mode?:SeekMode): void | +| media.AVPlayer | reset(callback: AsyncCallback\): void | +| media.AVPlayer | reset(): Promise\ | +| media.AVPlayer | release(callback: AsyncCallback\): void | +| media.AVPlayer | release(): Promise\ | +| media.AVPlayer | readonly width: number | +| media.AVPlayer | readonly state: AVPlayerState | +| media.AVPlayer | readonly height: number | +| media.AVPlayer | readonly duration: number | +| media.AVPlayer | readonly currentTime: number | +| media.AVPlayer | prepare(callback: AsyncCallback\): void | +| media.AVPlayer | prepare(): Promise\ | +| media.AVPlayer | play(callback: AsyncCallback\): void | +| media.AVPlayer | play(): Promise\ | +| media.AVPlayer | pause(callback: AsyncCallback\): void | +| media.AVPlayer | pause(): Promise\ | +| media.AVPlayer | on(type: 'volumeChange', callback: Callback\): void | +| media.AVPlayer | on(type: 'videoSizeChange', callback: (width: number, height: number) => void): void | +| media.AVPlayer | on(type: 'timeUpdate', callback: Callback\): void | +| media.AVPlayer | on(type: 'stateChange', callback: (state: AVPlayerState, reason: StateChangeReason) => void): void | +| media.AVPlayer | on(type: 'startRenderFrame', callback: Callback\): void | +| media.AVPlayer | on(type: 'speedDone', callback: Callback\): void | +| media.AVPlayer | on(type: 'seekDone', callback: Callback\): void | +| media.AVPlayer | on(type: 'error', callback: ErrorCallback): void | +| media.AVPlayer | on(type: 'endOfStream', callback: Callback\): void | +| media.AVPlayer | on(type: 'durationUpdate', callback: Callback\): void | +| media.AVPlayer | on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void | +| media.AVPlayer | on(type: 'bitrateDone', callback: Callback\): void | +| media.AVPlayer | on(type: 'availableBitrates', callback: (bitrates: Array\) => void): void | +| media.AVPlayer | on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void | +| media.AVPlayer | off(type: 'volumeChange'): void | +| media.AVPlayer | off(type: 'videoSizeChange'): void | +| media.AVPlayer | off(type: 'timeUpdate'): void | +| media.AVPlayer | off(type: 'stateChange'): void | +| media.AVPlayer | off(type: 'startRenderFrame'): void | +| media.AVPlayer | off(type: 'speedDone'): void | +| media.AVPlayer | off(type: 'seekDone'): void | +| media.AVPlayer | off(type: 'error'): void | +| media.AVPlayer | off(type: 'endOfStream'): void | +| media.AVPlayer | off(type: 'durationUpdate'): void | +| media.AVPlayer | off(type: 'bufferingUpdate'): void | +| media.AVPlayer | off(type: 'bitrateDone'): void | +| media.AVPlayer | off(type: 'availableBitrates'): void | +| media.AVPlayer | off(type: 'audioInterrupt'): void | +| media.AVPlayer | loop: boolean | +| media.AVPlayer | getTrackDescription(callback: AsyncCallback\>): void | +| media.AVPlayer | getTrackDescription() : Promise\> | +| media.AVPlayer | fdSrc ?: AVFileDescriptor | +| media.AVPlayer | audioInterruptMode ?: audio.InterruptMode | +| unnamed | type AVPlayerState = 'idle' \| 'initialized' \| 'prepared' \| 'playing' \| 'paused' \| 'completed' \| 'stopped' \| 'released' \| 'error' | + +停止维护接口如下: + +| 类名 | 停止维护接口声明 | +| ----------------- | ------------------------------------------------------------ | +| media | createVideoPlayer(callback: AsyncCallback\): void | +| media | createVideoPlayer() : Promise\ | +| media | createAudioPlayer(): AudioPlayer | +| media.AudioPlayer | interface AudioPlayer | +| media.AudioPlayer | play(): void | +| media.AudioPlayer | release(): void | +| media.AudioPlayer | audioInterruptMode ?: audio.InterruptMode | +| media.AudioPlayer | fdSrc: AVFileDescriptor | +| media.AudioPlayer | seek(timeMs: number): void | +| media.AudioPlayer | readonly duration: number | +| media.AudioPlayer | loop: boolean | +| media.AudioPlayer | readonly state: AudioState | +| media.AudioPlayer | getTrackDescription(callback: AsyncCallback\>): void | +| media.AudioPlayer | getTrackDescription() : Promise\> | +| media.AudioPlayer | on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void | +| media.AudioPlayer | on(type: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange', callback: () => void): void | +| media.AudioPlayer | on(type: 'timeUpdate', callback: Callback\): void | +| media.AudioPlayer | on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void | +| media.AudioPlayer | on(type: 'error', callback: ErrorCallback): void | +| media.AudioPlayer | setVolume(vol: number): void | +| media.AudioPlayer | pause(): void | +| media.AudioPlayer | readonly currentTime: number | +| media.AudioPlayer | stop(): void | +| media.AudioPlayer | reset(): void | +| media.AudioPlayer | src: string | +| media.VideoPlayer | interface VideoPlayer | +| media.VideoPlayer | play(callback: AsyncCallback\): void | +| media.VideoPlayer | play(): Promise\ | +| media.VideoPlayer | prepare(callback: AsyncCallback\): void | +| media.VideoPlayer | prepare(): Promise\ | +| media.VideoPlayer | release(callback: AsyncCallback\): void | +| media.VideoPlayer | release(): Promise\ | +| media.VideoPlayer | audioInterruptMode ?: audio.InterruptMode | +| media.VideoPlayer | fdSrc: AVFileDescriptor | +| media.VideoPlayer | seek(timeMs: number, callback: AsyncCallback\): void | +| media.VideoPlayer | seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void | +| media.VideoPlayer | seek(timeMs: number, mode?:SeekMode): Promise\ | +| media.VideoPlayer | readonly duration: number | +| media.VideoPlayer | loop: boolean | +| media.VideoPlayer | videoScaleType ?: VideoScaleType | +| media.VideoPlayer | readonly state: VideoPlayState | +| media.VideoPlayer | getTrackDescription(callback: AsyncCallback\>): void | +| media.VideoPlayer | getTrackDescription() : Promise\> | +| media.VideoPlayer | readonly height: number | +| media.VideoPlayer | on(type: 'playbackCompleted', callback: Callback\): void | +| media.VideoPlayer | on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void | +| media.VideoPlayer | on(type: 'startRenderFrame', callback: Callback\): void | +| media.VideoPlayer | on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void | +| media.VideoPlayer | on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void | +| media.VideoPlayer | on(type: 'error', callback: ErrorCallback): void | +| media.VideoPlayer | setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void | +| media.VideoPlayer | setDisplaySurface(surfaceId: string): Promise\ | +| media.VideoPlayer | setVolume(vol: number, callback: AsyncCallback\): void | +| media.VideoPlayer | setVolume(vol: number): Promise\ | +| media.VideoPlayer | url: string | +| media.VideoPlayer | pause(callback: AsyncCallback\): void | +| media.VideoPlayer | pause(): Promise\ | +| media.VideoPlayer | readonly currentTime: number | +| media.VideoPlayer | setSpeed(speed:number, callback: AsyncCallback\): void | +| media.VideoPlayer | setSpeed(speed:number): Promise\ | +| media.VideoPlayer | stop(callback: AsyncCallback\): void | +| media.VideoPlayer | stop(): Promise\ | +| media.VideoPlayer | readonly width: number | +| media.VideoPlayer | reset(callback: AsyncCallback\): void | +| media.VideoPlayer | reset(): Promise\ | +| unnamed | type AudioState = 'idle' \| 'playing' \| 'paused' \| 'stopped' \| 'error' | +| unnamed | type VideoPlayState = 'idle' \| 'prepared' \| 'playing' \| 'paused' \| 'stopped' \| 'error' | + +**适配指导** + +请参考各接口的[API参考](../../../application-dev/reference/apis/js-apis-media.md) + +## cl.media.2 录制功能接口变更 + +新增音视频录制接口[AVRecorder](../../../application-dev/reference/apis/js-apis-media.md#avrecorder9)9+, 升级了状态机和错误码,推荐用户使用。旧版音频录制接口[AudioRecorder](../../../application-dev/reference/apis/js-apis-media.md#audiorecorder)6+和视频录制接口[VideoRecorder](../../../application-dev/reference/apis/js-apis-media.md#videorecorder9)9+停止维护。 + +新旧录制接口共用的[AudioSourceType](../../../application-dev/reference/apis/js-apis-media.md#audiosourcetype9)和[VideoSourceType](../../../application-dev/reference/apis/js-apis-media.md#videosourcetype9)接口,变更为非系统接口。 + +**变更影响** + +原有的接口[AudioRecorder](../../../application-dev/reference/apis/js-apis-media.md#audiorecorder)6+和[VideoRecorder](../../../application-dev/reference/apis/js-apis-media.md#videorecorder9)9+暂时可继续使用,但是停止维护,建议使用新接口进行开发[AVRecorder](../../../application-dev/reference/apis/js-apis-media.md#avrecorder9)9+。 + +**关键的接口/组件变更** + +新增接口如下: + +| 类名 | 新增接口声明 | +| ----------------------- | ------------------------------------------------------------ | +| media | createAVRecorder(callback: AsyncCallback\): void | +| media | createAVRecorder() : Promise\ | +| media.AVRecorder | interface AVRecorder | +| media.AVRecorder | prepare(config: AVRecorderConfig, callback: AsyncCallback\): void | +| media.AVRecorder | prepare(config: AVRecorderConfig): Promise\ | +| media.AVRecorder | release(callback: AsyncCallback\): void | +| media.AVRecorder | release(): Promise\ | +| media.AVRecorder | readonly state: AVRecorderState | +| media.AVRecorder | on(type: 'stateChange', callback: (state: AVRecorderState, reason: StateChangeReason) => void): void | +| media.AVRecorder | on(type: 'error', callback: ErrorCallback): void | +| media.AVRecorder | resume(callback: AsyncCallback\): void | +| media.AVRecorder | resume(): Promise\ | +| media.AVRecorder | start(callback: AsyncCallback\): void | +| media.AVRecorder | start(): Promise\ | +| media.AVRecorder | off(type: 'stateChange'): void | +| media.AVRecorder | off(type: 'error'): void | +| media.AVRecorder | pause(callback: AsyncCallback\): void | +| media.AVRecorder | pause(): Promise\ | +| media.AVRecorder | stop(callback: AsyncCallback\): void | +| media.AVRecorder | stop(): Promise\ | +| media.AVRecorder | reset(callback: AsyncCallback\): void | +| media.AVRecorder | reset(): Promise\ | +| media.AVRecorder | getInputSurface(callback: AsyncCallback\): void | +| media.AVRecorder | getInputSurface(): Promise\ | +| media.AVRecorderConfig | videoSourceType?: VideoSourceType | +| media.AVRecorderConfig | audioSourceType?: AudioSourceType | +| media.AVRecorderConfig | profile: AVRecorderProfile | +| media.AVRecorderConfig | rotation?: number | +| media.AVRecorderConfig | url: string | +| media.AVRecorderConfig | location?: Location | +| media.AVRecorderConfig | interface AVRecorderConfig | +| media.AVRecorderProfile | videoBitrate?: number | +| media.AVRecorderProfile | videoCodec?: CodecMimeType | +| media.AVRecorderProfile | audioCodec?: CodecMimeType | +| media.AVRecorderProfile | videoFrameRate?: number | +| media.AVRecorderProfile | videoFrameHeight?: number | +| media.AVRecorderProfile | audioSampleRate?: number | +| media.AVRecorderProfile | audioBitrate?: number | +| media.AVRecorderProfile | videoFrameWidth?: number | +| media.AVRecorderProfile | audioChannels?: number | +| media.AVRecorderProfile | fileFormat: ContainerFormatType | +| media.AVRecorderProfile | interface AVRecorderProfile | +| unnamed | type AVRecorderState = 'idle' \| 'prepared' \| 'started' \| 'paused' \| 'stopped' \| 'released' \| 'error' | + +停止维护接口如下: + +| 类名 | 停止维护接口声明 | +| -------------------------- | ------------------------------------------------------------ | +| media | createVideoRecorder(callback: AsyncCallback\): void | +| media | createVideoRecorder(): Promise\ | +| media | createAudioRecorder(): AudioRecorder | +| media.AudioRecorder | interface AudioRecorder | +| media.AudioRecorder | prepare(config: AudioRecorderConfig): void | +| media.AudioRecorder | release(): void | +| media.AudioRecorder | on(type: 'prepare' \| 'start' \| 'pause' \| 'resume' \| 'stop' \| 'release' \| 'reset', callback: () => void): void | +| media.AudioRecorder | on(type: 'error', callback: ErrorCallback): void | +| media.AudioRecorder | resume(): void | +| media.AudioRecorder | start(): void | +| media.AudioRecorder | pause(): void | +| media.AudioRecorder | stop(): void | +| media.AudioRecorder | reset(): void | +| media.AudioRecorderConfig | audioSampleRate?: number | +| media.AudioRecorderConfig | location?: Location | +| media.AudioRecorderConfig | fileFormat?: ContainerFormatType | +| media.AudioRecorderConfig | interface AudioRecorderConfig | +| media.AudioRecorderConfig | audioEncoder?: AudioEncoder | +| media.AudioRecorderConfig | audioEncodeBitRate?: number | +| media.AudioRecorderConfig | numberOfChannels?: number | +| media.AudioRecorderConfig | format?: AudioOutputFormat | +| media.AudioRecorderConfig | uri: string | +| media.AudioRecorderConfig | audioEncoderMime?: CodecMimeType | +| media.VideoRecorder | interface VideoRecorder | +| media.VideoRecorder | prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void | +| media.VideoRecorder | prepare(config: VideoRecorderConfig): Promise\ | +| media.VideoRecorder | release(callback: AsyncCallback\): void | +| media.VideoRecorder | release(): Promise\ | +| media.VideoRecorder | readonly state: VideoRecordState | +| media.VideoRecorder | on(type: 'error', callback: ErrorCallback): void | +| media.VideoRecorder | resume(callback: AsyncCallback\): void | +| media.VideoRecorder | resume(): Promise\ | +| media.VideoRecorder | start(callback: AsyncCallback\): void | +| media.VideoRecorder | start(): Promise\ | +| media.VideoRecorder | pause(callback: AsyncCallback\): void | +| media.VideoRecorder | pause(): Promise\ | +| media.VideoRecorder | stop(callback: AsyncCallback\): void | +| media.VideoRecorder | stop(): Promise\ | +| media.VideoRecorder | reset(callback: AsyncCallback\): void | +| media.VideoRecorder | reset(): Promise\ | +| media.VideoRecorder | getInputSurface(callback: AsyncCallback\): void | +| media.VideoRecorder | getInputSurface(): Promise\ | +| media.VideoRecorderConfig | videoSourceType: VideoSourceType | +| media.VideoRecorderConfig | audioSourceType?: AudioSourceType | +| media.VideoRecorderConfig | profile: VideoRecorderProfile | +| media.VideoRecorderConfig | rotation?: number | +| media.VideoRecorderConfig | url: string | +| media.VideoRecorderConfig | location?: Location | +| media.VideoRecorderConfig | interface VideoRecorderConfig | +| media.VideoRecorderProfile | readonly videoBitrate: number | +| media.VideoRecorderProfile | readonly videoCodec: CodecMimeType | +| media.VideoRecorderProfile | readonly audioCodec: CodecMimeType | +| media.VideoRecorderProfile | readonly videoFrameRate: number | +| media.VideoRecorderProfile | readonly videoFrameHeight: number | +| media.VideoRecorderProfile | readonly audioSampleRate: number | +| media.VideoRecorderProfile | readonly audioBitrate: number | +| media.VideoRecorderProfile | readonly videoFrameWidth: number | +| media.VideoRecorderProfile | readonly audioChannels: number | +| media.VideoRecorderProfile | readonly fileFormat: ContainerFormatType | +| media.VideoRecorderProfile | interface VideoRecorderProfile | +| unnamed | type VideoRecordState = 'idle' \| 'prepared' \| 'playing' \| 'paused' \| 'stopped' \| 'error' | + +变更接口如下: + +| 类名 | 接口声明 | 变更前能力 | 变更后能力 | 变更前是否为系统接口 | 变更后是否为系统接口 | +| --------------------- | ------------------------------------------------------------ | ----------------------------------------------- | -------------------------------------------- | -------------------- | -------------------- | +| media.AudioSourceType | enum AudioSourceType { /** * default audio source type. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ AUDIO_SOURCE_TYPE_DEFAULT = 0, /** * source type mic. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ AUDIO_SOURCE_TYPE_MIC = 1, } | SystemCapability.Multimedia.Media.VideoRecorder | SystemCapability.Multimedia.Media.AVRecorder | 是 | 否 | +| media.VideoSourceType | enum VideoSourceType { /** * surface raw data. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ VIDEO_SOURCE_TYPE_SURFACE_YUV = 0, /** * surface ES data. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ VIDEO_SOURCE_TYPE_SURFACE_ES = 1, } | SystemCapability.Multimedia.Media.VideoRecorder | SystemCapability.Multimedia.Media.AVRecorder | 是 | 否 | + +**适配指导** + +请参考各接口的[API参考](../../../application-dev/reference/apis/js-apis-media.md) + +## cl.media.3 错误码变更 + +新增标准的错误枚举类型[AVErrorCode9](../../../application-dev/reference/apis/js-apis-media.md#averrorcode)9+替代原有错误枚举类型[MediaErrorCode](../../../application-dev/reference/apis/js-apis-media.md#mediaerrorcode)8+。 + +**变更影响** + +以往接口返回错误码枚举类型为[MediaErrorCode](../../../application-dev/reference/apis/js-apis-media.md#mediaerrorcode)8+不变。新增接口错误码类型均采用[AVErrorCode9](../../../application-dev/reference/apis/js-apis-media.md#averrorcode)9+。 + +**关键的接口/组件变更** + +新增接口如下: + +| 类名 | 新增错误码声明 | +| ----------------- | ------------------------------------------------------------ | +| media.AVErrorCode | enum AVErrorCode { /** * operation success. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_OK = 0, /** * permission denied. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_NO_PERMISSION = 201, /** * invalid parameter. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_INVALID_PARAMETER = 401, /** * the api is not supported in the current version * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_UNSUPPORT_CAPABILITY = 801, /** * the system memory is insufficient or the number of services reaches the upper limit * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_NO_MEMORY = 5400101, /** * current status does not allow or do not have permission to perform this operation * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_OPERATE_NOT_PERMIT = 5400102, /** * data flow exception information * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_IO = 5400103, /** * system or network response timeout. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_TIMEOUT = 5400104, /** * service process died. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_SERVICE_DIED = 5400105, /** * unsupported media format * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_UNSUPPORT_FORMAT = 5400106, } | + +停止维护接口如下: + +| 类名 | 停止维护错误码声明 | +| -------------------- | ------------------------------------------------------------ | +| media.MediaErrorCode | enum MediaErrorCode { /** * operation success. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_OK = 0, /** * malloc or new memory failed. maybe system have no memory. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_NO_MEMORY = 1, /** * no permission for the operation. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_OPERATION_NOT_PERMIT = 2, /** * invalid argument. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_INVALID_VAL = 3, /** * an I/O error occurred. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_IO = 4, /** * operation time out. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_TIMEOUT = 5, /** * unknown error. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_UNKNOWN = 6, /** * media service died. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_SERVICE_DIED = 7, /** * operation is not permit in current state. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_INVALID_STATE = 8, /** * operation is not supported in current version. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_UNSUPPORTED = 9, } | \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-testfwk_arkxtest.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-testfwk_arkxtest.md new file mode 100644 index 0000000000000000000000000000000000000000..d508e473d7d48695a059508de789b84730b4f13e --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-testfwk_arkxtest.md @@ -0,0 +1,42 @@ +# 测试子系统ChangeLog + +## cl.testfwk_arkxtest.1 Rect控件边框信息类接口名称变更 + +表示控件边框信息的枚举类型Rect定义自4.0.2.1版本起进行了变更。 + +## 变更影响 + +此变更影响@ohos.uitest提供的Rect接口。用户此前在测试用例开发中使用了@ohos.uitest-api9 中Rect接口的,需要进行适配才可以在新版本SDK环境正常编译通过。 + +## 关键的接口/组件变更 + +### Rect9+ + +变更前: + +| 名称 | 值 | 说明 | +| ------- | ---- | ------------------------- | +| leftX | 1 | 控件边框的左上角的X坐标。 | +| topY | 2 | 控件边框的左上角的Y坐标。 | +| rightX | 3 | 控件边框的右下角的X坐标。 | +| bottomY | 4 | 控件边框的右下角的Y坐标。 | + +变更后: + +| 名称 | 值 | 说明 | +| ------ | ---- | ------------------------- | +| left | 1 | 控件边框的左上角的X坐标。 | +| top | 2 | 控件边框的左上角的Y坐标。 | +| right | 3 | 控件边框的右下角的X坐标。 | +| bottom | 4 | 控件边框的右下角的Y坐标。 | + +## 适配指导 + +### 适配接口名称变更 + +可按照如下规则做类名替换: + +- `leftX-->left` +- `topY-->top` +- `rightX-->right` +- `bottomY-->bottom` diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-inputmethod-framworks.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-inputmethod-framworks.md new file mode 100644 index 0000000000000000000000000000000000000000..38edd589bb5fce2d395dc6036a8658b6174dc8a2 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-inputmethod-framworks.md @@ -0,0 +1,30 @@ +# 输入法框架changeLog + +## cl.inputmethod_frameworks.1 API文件名变更 + +下列模块与HarmonyOS中的SDK不兼容,且不符合OpenHarmony接口文件名命名规范。在API9进行变更。 + + **变更影响** + + 修改后的SDK与先前已发布版本不兼容,影响在此前版本已开发的应用,应用需要进行适配改动才可以在新版本SDK环境正常编译通过。 + + **关键的接口/组件变更** + +| 模块 | 变更前文件名 | 变更后文件名 | +|------|--------------|--------------| +| 输入法框架模块 | @ohos.inputmethod.d.ts |@ohos.inputMethod.d.ts | +| 输入法服务模块 |@ohos.inputmethodengine.d.ts | @ohos.inputMethodEngine.d.ts | +| 输入法ExtentionAbility模块 | @ohos.inputmethodextensionability.d.ts | @ohos.InputMethodExtensionAbility.d.ts | +| 输入法ExtentionContext模块 |@ohos.inputmethodextensioncontext.d.ts | @ohos.InputMethodExtensionContext.d.ts | +| 输入法子类型模块 | @ohos.inputMethodSubtype.d.ts | @ohos.InputMethodSubtype.d.ts | + + **适配指导** + + 应用中对输入法框架d.ts文件的import后的文件名要写为变更后文件名,即小驼峰/大驼峰命名格式。 + 如: + +```js +import inputMethodEngine from '@ohos.inputMethodEngine'; +``` + + \ No newline at end of file