提交 b523f2d8 编写于 作者: Z z00524957

Merge branch 'monthly_20221018' of https://gitee.com/zengyawen/docs into monthly_20221018

...@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share ...@@ -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.| |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.| |delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.|
For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md).
**Table 2** APIs of the data consumer **Table 2** APIs of the data consumer
...@@ -34,11 +34,49 @@ There are two roles in **DataShare**: ...@@ -34,11 +34,49 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### Data Provider Application Development (Only for System Applications) ### Data Provider Application Development (Only for System Applications)
1. Import dependencies. [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
- **onCreate**
Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server.
- **insert**
Inserts data. This API is called when the client requests to insert data.
- **update**
Updates data. This API is called when the client requests to update data.
- **delete**
Deletes data. This API is called when the client requests to delete data.
- **query**
Queries data. This API is called when the client requests to query data.
- **batchInsert**
Batch inserts data. This API is called when the client requests to batch insert data.
- **normalizeUri**
Converts the URI provided by the client to the URI used by the server.
- **denormalizeUri**
Converts the URI used by the server to the initial URI passed by the client.
Before implementing a **DataShare** service, you need to create a **DataShareExtensionAbility** object in the DevEco Studio project as follows:
1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **DataShareAbility**.
2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**.
3. In the **DataShareAbility.ts** file, import **DataShareExtensionAbility** and other dependencies.
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
...@@ -47,9 +85,9 @@ Examples are given below. ...@@ -47,9 +85,9 @@ Examples are given below.
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. 4. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. 5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts ```ts
const DB_NAME = "DB00.db"; const DB_NAME = "DB00.db";
...@@ -66,7 +104,7 @@ Examples are given below. ...@@ -66,7 +104,7 @@ Examples are given below.
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt' result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store. // Create an RDB store.
rdb.getRdbStore(this.context, { rdb.getRdbStore(this.context, {
name: DB_NAME, name: DB_NAME,
...@@ -76,7 +114,9 @@ Examples are given below. ...@@ -76,7 +114,9 @@ Examples are given below.
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
}); });
if (callback) {
callback(); callback();
}
}); });
} }
...@@ -103,14 +143,15 @@ Examples are given below. ...@@ -103,14 +143,15 @@ Examples are given below.
}; };
``` ```
4. Define **DataShareExtensionAbility** in **module.json5**.
| Field| Description | 6. Define **DataShareExtensionAbility** in **module.json5**.
| ------------ | ------------------------------------------------------------ |
| Field | Description |
| --------- | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "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.| | "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. | | "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**.| | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. |
**module.json5 example** **module.json5 example**
...@@ -128,12 +169,14 @@ Examples are given below. ...@@ -128,12 +169,14 @@ Examples are given below.
] ]
``` ```
### Data Consumer Application Development ### Data Consumer Application Development
1. Import dependencies. 1. Import dependencies.
```ts ```ts
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
import dataShare from '@ohos.data.dataShare'; import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
...@@ -151,7 +194,7 @@ Examples are given below. ...@@ -151,7 +194,7 @@ Examples are given below.
let dsHelper; let dsHelper;
let abilityContext; let abilityContext;
export default class MainAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
abilityContext = this.context; abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{ dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
...@@ -168,7 +211,7 @@ Examples are given below. ...@@ -168,7 +211,7 @@ Examples are given below.
let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*"); let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log("dsHelper insert result: " + data);
...@@ -186,4 +229,3 @@ Examples are given below. ...@@ -186,4 +229,3 @@ Examples are given below.
console.log("dsHelper delete result: " + data); console.log("dsHelper delete result: " + data);
}); });
``` ```
...@@ -68,11 +68,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -68,11 +68,11 @@ The following uses a single KV store as an example to describe the development p
grantPermission(); grantPermission();
// Stage model // Stage model
import AbilityStage from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends AbilityStage { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let context = this.context; let context = this.context;
} }
...@@ -103,9 +103,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -103,9 +103,9 @@ The following uses a single KV store as an example to describe the development p
let context = featureAbility.getContext(); let context = featureAbility.getContext();
// Obtain the context of the stage model. // Obtain the context of the stage model.
import AbilityStage from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends AbilityStage{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
......
...@@ -113,10 +113,10 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -113,10 +113,10 @@ You can use the following APIs to delete a **Preferences** instance or data file
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability' import UIAbility from '@ohos.app.ability.UIAbility'
let context = null; let context = null;
let preferences = null; let preferences = null;
export default class MainAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -159,7 +159,7 @@ You can use the following APIs to delete a **Preferences** instance or data file ...@@ -159,7 +159,7 @@ You can use the following APIs to delete a **Preferences** instance or data file
5. Store data persistently. 5. Store data persistently.
Use **flush()** to flush data from the **Preferences** instance to its file. Use **preferences.flush()** to flush data from the **Preferences** instance to its file.
```js ```js
preferences.flush(); preferences.flush();
......
...@@ -4,9 +4,7 @@ ...@@ -4,9 +4,7 @@
- [USB Service Overview](usb-overview.md) - [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md) - [USB Service Development](usb-guidelines.md)
- Location - Location
- [Location Overview](device-location-overview.md) - [Location Service Development](location-guidelines.md)
- [Obtaining Device Location Information](device-location-info.md)
- [Geocoding and Reverse Geocoding Capabilities](device-location-geocoding.md)
- Sensor - Sensor
- [Sensor Overview](sensor-overview.md) - [Sensor Overview](sensor-overview.md)
- [Sensor Development](sensor-guidelines.md) - [Sensor Development](sensor-guidelines.md)
......
# 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 location information.
**Table1** APIs for geocoding and reverse geocoding
| API | Description |
| -------- | -------- |
| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. |
| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. |
## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
```
import geolocation 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.
```
geolocation.isGeoServiceAvailable((err, data) => {
if (err) {
console.log('isGeoServiceAvailable err: ' + JSON.stringify(err));
} else {
console.log('isGeoServiceAvailable data: ' + JSON.stringify(data));
}
});
```
3. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information.
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
});
```
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.
```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
});
```
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**.
# 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
The following table describes APIs available for obtaining device location information.
**Table 1** APIs for obtaining device location information
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Registers a listener for location changes with a location request initiated. |
| off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted. |
| on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events. |
| off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events. |
| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports. |
| off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports. |
| on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events. |
| off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events. |
| on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Registers a listener for GNSS NMEA message change events. |
| off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unregisters the listener for GNSS NMEA message change events. |
| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence. |
| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence. |
| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtains the current location. This API uses an asynchronous callback to return the result. |
| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This API uses a promise to return the result. |
| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This API uses an asynchronous callback to return the result. |
| getLastLocation() : Promise<Location> | Obtains the previous location. This API uses a promise to return the result. |
| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. |
| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This API uses a promise to return the result. |
| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result. |
| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This API uses a promise to return the result. |
| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This API uses an asynchronous callback to return the result. |
| enableLocation() : Promise<boolean> | Enables the location service. This API uses a promise to return the result. |
| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This API uses an asynchronous callback to return the result. |
| disableLocation() : Promise<boolean> | Disables the location service. This API uses a promise to return the result. |
| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This API uses an asynchronous callback to return the result. |
| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This API uses a promise to return the result. |
| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses an asynchronous callback to return the result.|
| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses a promise to return the result.|
| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This API uses an asynchronous callback to return the result.|
| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This API uses a promise to return the result. |
| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | Checks whether a user agrees with the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | Checks whether a user agrees with the privacy statement of the location service. This API uses a promise to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Sets the user confirmation status for the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Sets the user confirmation status for the privacy statement of the location service. This API uses a promise to return the result.|
## How to Develop
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.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.LOCATION_IN_BACKGROUND
The **ohos.permission.LOCATION** permission is a must if your application needs to access the device location information.
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 **geolocation** module by which you can implement all APIs related to the basic location capabilities.
```
import geolocation 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.<br>
**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.<br>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.<br>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.<br>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.<br>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.<br>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:
```
var requestInfo = {'scenario': geolocation.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.
```
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.<br>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.<br>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.<br>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:
```
var requestInfo = {'priority': geolocation.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.
```
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
```
5. Start device location.
```
geolocation.on('locationChange', requestInfo, locationChange);
```
6. (Optional) Stop device location.
```
geolocation.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.
```
geolocation.getLastLocation((err, data) => {
if (err) {
console.log('getLastLocation: err: ' + JSON.stringify(err));
} else {
console.log('getLastLocation: data: ' + JSON.stringify(data));
}
});
```
To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user.
# 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)
# Location Service Development
## 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 OpenHarmony, 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.
### Service Introduction
Location awareness helps determine where a mobile device locates. The location subsystem 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.
### Constraints
Your application can use the location function only after the user has granted the required permission and turned on the location 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 (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location)
## Applying for Location Permissions
### When to Use
Before using system 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.
The system provides the following location permissions:
- ohos.permission.LOCATION: used to obtain location accurate to meters.
- ohos.permission.APPROXIMATELY\_LOCATION: used to obtain location accurate to 5 kilometers.
- ohos.permission.LOCATION\_IN\_BACKGROUND: used to obtain location while the application is running at the background.
If your application needs to access the device location information, it must first apply for required permissions.
**Table 1** Ways to apply for location permissions
| Target API Level| Location Permission| Permission Application Result| Location Accuracy|
| -------- | -------- | -------- | -------- |
| Earlier than 9| ohos.permission.LOCATION | Successful| Location accurate to meters.|
| 9 and later| ohos.permission.LOCATION | Failed| No location obtained.|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Successful| Location accurate to 5 kilometers.|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Successful| Location accurate to meters.|
If your application needs to access the device location information when running in the background, it must be configured to be able to run in 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).
For details about the permissions required for each API of the location service, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
### How to Develop
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
## 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
The following table lists the APIs used to obtain the device location information. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
**Table 2** APIs for obtaining device location information
| API| Description|
| -------- | -------- |
| on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;): void | Registers a listener for location changes with a location request initiated.|
| off(type: 'locationChange', callback?: Callback&lt;Location&gt;): void | Unregisters the listener for location changes with the corresponding location request deleted.|
| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;): void | Obtains the current location. This API uses an asynchronous callback to return the result. |
| getCurrentLocation(request?: CurrentLocationRequest): Promise&lt;Location&gt; | Obtains the current location. This API uses a promise to return the result. |
| getLastLocation(): Location | Obtains the last known device location.|
### How to Develop
1. Before using basic location capabilities, check whether your application has been granted the permission to access device location information. If not, your application first needs to apply for the required permission. For details, see [Applying for Location Permissions](#applying-for-location-permissions).
2. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities.
```ts
import geoLocationManager from '@ohos.geoLocationManager';
```
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.<br>
**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 location service scenarios currently supported are described as follows.
**Location service scenarios**
- NAVIGATION<br>
Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. <br>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. <br>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. <br>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<br>
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. <br>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.
- CAR\_HAILING<br>
Applicable when your application needs to obtain the current location of a user who is hailing a taxi. <br>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.
- DAILY\_LIFE\_SERVICE<br>
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. <br>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.
- NO\_POWER<br>
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. <br>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.
```ts
export enum LocationRequestScenario {
UNSET = 0x300,
NAVIGATION,
TRAJECTORY_TRACKING,
CAR_HAILING,
DAILY_LIFE_SERVICE,
NO_POWER,
}
```
Sample code for initializing **requestInfo** for navigation:
```ts
let 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.
**Location priority policies**
- ACCURACY<br>
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.
- FIRST\_FIX<br>
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.
- LOW\_POWER<br>
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.
```ts
export enum LocationRequestPriority {
UNSET = 0x200,
ACCURACY,
LOW_POWER,
FIRST_FIX,
}
```
Sample code for initializing **requestInfo** for the location accuracy priority policy:
```ts
let 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
let locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
```
5. Start obtaining the device location.
```ts
geoLocationManager.on('locationChange', requestInfo, locationChange);
```
6. (Optional) Stop obtaining the device location.
If your application no longer needs the device location, stop obtaining the device location to avoid high power consumption.
```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 {
let location = geoLocationManager.getLastLocation();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
## Geocoding and Reverse Geocoding
### When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. To address this issue, the system provides your application the geocoding and reverse geocoding capabilities:
- Geocoding: converts geographic descriptions into specific coordinates.
- Reverse geocoding: converts coordinates into geographic descriptions.
The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc.
### Available APIs
The following table lists the APIs used for mutual conversion between coordinates and geographic descriptions. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
**Table 3** APIs for geocoding and reverse geocoding conversion
| API| Description|
| -------- | -------- |
| isGeocoderAvailable(): boolean; | Obtains the (reverse) geocoding service status.|
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts coordinates into geographic descriptions through reverse geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts coordinates into geographic descriptions through reverse geocoding. This API uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts geographic descriptions into coordinates through geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts geographic descriptions 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.geoLocationManager';
```
2. Check whether the **geoCoder** service is available.
- Call **isGeoServiceAvailable** to check whether the **geoCoder** service is available. If the service is available, go to step 3.
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
let isAvailable = geoLocationManager.isGeocoderAvailable();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
3. Obtain the geocoding conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information.
```ts
let 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);
}
```
The application can access the **GeoAddress** list that matches the specified coordinates for the corresponding geographic descriptions. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
- Call **getAddressesFromLocationName** to convert geographic descriptions into coordinates.
```ts
let 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);
}
```
The application can access the **GeoAddress** list that matches the specified geographic descriptions for the corresponding coordinates. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
## Geofencing
### When to Use
A geofence is a group of virtual bounds defining an area on the map. When a user device enters or leaves a geofence, or stays in a geofence, your app on the user device can automatically receive notifications and alarms.
Currently, only circular geofences are supported, and the geofencing function of the GNSS chip is required.
A typical application of geofencing is to create a geofence around an enterprise for targeted advertising. In different areas, you can provide differentiated promotions for mobile devices.
### Available APIs
The following table lists the APIs used for geofencing. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
**Table 4** Geofencing APIs
| API| Description|
| -------- | -------- |
| on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | Registers a listener for status change events of the specified geofence.|
| off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; | Unregisters the listener for status change events of the specified geofence.|
### How to Develop
1. Declare the **ohos.permission.APPROXIMATELY_LOCATION** permission. For details, see [Applying for Location Permissions](#applying-for-location-permissions).
2. Import the [geoLocationManager](../reference/apis/js-apis-geoLocationManager.md) and [wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) modules.
```ts
import geoLocationManager from '@ohos.geoLocationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
```
3. Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object.
Scenario 1: Create a **WantAgentInfo** object for starting an ability.
```ts
let wantAgentObj = null; // Save the created WantAgent object for completing the trigger operations at a later time.
// Set the operation type through operationType of the WantAgentInfo object.
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** object for publishing [common events](../application-models/common-event-overview.md).
```ts
let wantAgentObj = null; // Save the created WantAgent object for completing the trigger operations at a later time.
// Set the operation type through operationType of the WantAgentInfo object.
let wantAgentInfo = {
wants: [
{
action: "event_name", // Set the event name.
parameters: {},
}
],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
}
```
4. Call [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to create a **WantAgent** object.
After obtaining the **WantAgent** object, call the geofencing API to add a geofence.
```ts
// Create a WantAgent object.
wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
if (err) {
console.error('getWantAgent err=' + JSON.stringify(err));
return;
}
console.info('getWantAgent success');
wantAgentObj = data;
let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
try {
geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
});
```
5. Have the system automatically trigger the action defined for the **WantAgent** object when a device enters or exits the geofence.
...@@ -8,7 +8,7 @@ In Host mode, you can obtain the list of connected USB devices, enable or disabl ...@@ -8,7 +8,7 @@ In Host mode, you can obtain the list of connected USB devices, enable or disabl
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md). The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usbManager.md).
**Table 1** Open USB APIs **Table 1** Open USB APIs
...@@ -18,7 +18,7 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -18,7 +18,7 @@ The following table lists the USB APIs currently available. For details, see the
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. | | requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device list returned by `getDevices()`. | | connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device list returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. | | getDevices(): Array<Readonly\<USBDevice>> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise\<number> | Performs bulk transfer. | | bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise\<number> | Performs bulk transfer. |
...@@ -36,7 +36,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -36,7 +36,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
```js ```js
// Import the USB API package. // Import the USB API package.
import usb from '@ohos.usbV9'; import usb from '@ohos.usbManager';
// Obtain the USB device list. // Obtain the USB device list.
let deviceList = usb.getDevices(); let deviceList = usb.getDevices();
/* /*
......
...@@ -6,7 +6,7 @@ The [intl](intl-guidelines.md) module provides basic i18n capabilities through t ...@@ -6,7 +6,7 @@ The [intl](intl-guidelines.md) module provides basic i18n capabilities through t
## Obtaining and Setting i18n 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. The following table lists the APIs used to configure information such as the system language, preferred language, country or region, 24-hour clock, and use of local digits.
### Available APIs ### Available APIs
...@@ -30,15 +30,15 @@ The system provides APIs to configure information such as the system language, p ...@@ -30,15 +30,15 @@ The system provides APIs to configure information such as the system language, p
| System | getPreferredLanguageList()<sup>9+</sup> | Obtains the preferred language list. | | System | getPreferredLanguageList()<sup>9+</sup> | Obtains the preferred language list. |
| System | getFirstPreferredLanguage()<sup>9+</sup> | Obtains the first language in the preferred language list. | | System | getFirstPreferredLanguage()<sup>9+</sup> | Obtains the first language in the preferred language list. |
| System | getAppPreferredLanguage()<sup>9+</sup> | Obtains the preferred language of an application. | | System | getAppPreferredLanguage()<sup>9+</sup> | Obtains the preferred language of an application. |
| System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Sets whether to enable the local digit switch. | | System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Specifies whether to enable use of local digits. |
| System | getUsingLocalDigit()<sup>9+</sup> | Checks whether the local digit switch is turned on. | | System | getUsingLocalDigit()<sup>9+</sup> | Checks whether use of local digits is enabled. |
| | isRTL(locale:string):boolean<sup>9+</sup> | Checks whether the locale uses a right-to-left (RTL) language.| | | isRTL(locale:string):boolean<sup>9+</sup> | Checks whether the locale uses a right-to-left (RTL) language.|
### How to Develop ### How to Develop
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Obtain and set the system language. 2. Obtain and set the system language.
...@@ -51,7 +51,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -51,7 +51,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLanguage("en"); // Set the system language to en. I18n.System.setSystemLanguage("en"); // Set the system language to en.
let language = I18n.System.getSystemLanguage(); // language = "en" let language = I18n.System.getSystemLanguage(); // language = "en"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -65,7 +65,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -65,7 +65,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemRegion("CN"); // Set the system country to CN. I18n.System.setSystemRegion("CN"); // Set the system country to CN.
let region = I18n.System.getSystemRegion(); // region = "CN" let region = I18n.System.getSystemRegion(); // region = "CN"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -79,7 +79,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -79,7 +79,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN. I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN.
let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN" let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -92,7 +92,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -92,7 +92,7 @@ The system provides APIs to configure information such as the system language, p
let rtl = I18n.isRTL("zh-CN"); // rtl = false let rtl = I18n.isRTL("zh-CN"); // rtl = false
rtl = I18n.isRTL("ar"); // rtl = true rtl = I18n.isRTL("ar"); // rtl = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -106,7 +106,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -106,7 +106,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.set24HourClock(true); I18n.System.set24HourClock(true);
let hourClock = I18n.System.is24HourClock(); // hourClock = true let hourClock = I18n.System.is24HourClock(); // hourClock = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -121,7 +121,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -121,7 +121,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false; let sentenceCase = false;
let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English" let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -136,7 +136,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -136,7 +136,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false; let sentenceCase = false;
let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S." let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S."
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -150,7 +150,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -150,7 +150,7 @@ The system provides APIs to configure information such as the system language, p
let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"] let 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 let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -162,7 +162,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -162,7 +162,7 @@ The system provides APIs to configure information such as the system language, p
try { try {
let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -182,7 +182,7 @@ The system provides APIs to configure information such as the system language, p ...@@ -182,7 +182,7 @@ The system provides APIs to configure information such as the system language, p
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB" let 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. let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources.
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -190,14 +190,14 @@ The system provides APIs to configure information such as the system language, p ...@@ -190,14 +190,14 @@ The system provides APIs to configure information such as the system language, p
Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.) Call **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. Call **getUsingLocalDigit** to check whether the local digit switch is enabled.
Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur". Currently, use of local digits is supported only for the following languages: **ar**, **as**, **bn**, **fa**, **mr**, **my**, **ne**, **ur**.
```js ```js
try { try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
let status = I18n.System.getUsingLocalDigit(); // status = true let status = I18n.System.getUsingLocalDigit(); // status = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
} }
``` ```
...@@ -220,14 +220,14 @@ try { ...@@ -220,14 +220,14 @@ try {
| Calendar | getMinimalDaysInFirstWeek():number<sup>8+</sup> | Obtains the minimum number of days in the first week of a year. | | Calendar | getMinimalDaysInFirstWeek():number<sup>8+</sup> | Obtains the minimum number of days in the first week of a year. |
| Calendar | setMinimalDaysInFirstWeek(value:number): void<sup>8+</sup> | Sets the minimum number of days in the first week of a year. | | Calendar | setMinimalDaysInFirstWeek(value:number): void<sup>8+</sup> | Sets the minimum number of days in the first week of a year. |
| Calendar | getDisplayName(locale:string):string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. | | Calendar | getDisplayName(locale:string):string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. |
| Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether the specified date in this **Calendar** object is a weekend. | | Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether a given date is a weekend in the calendar. |
### How to Develop ### How to Develop
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate a **Calendar** object. 2. Instantiate a **Calendar** object.
...@@ -254,7 +254,7 @@ try { ...@@ -254,7 +254,7 @@ try {
Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object. Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object.
```js ```js
calendar.set(2021, 12, 21, 6, 0, 0) calendar.set(2021, 12, 21, 6, 0, 0);
``` ```
5. Set and obtain the time zone for the **Calendar** object. 5. Set and obtain the time zone for the **Calendar** object.
...@@ -317,7 +317,7 @@ try { ...@@ -317,7 +317,7 @@ try {
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate a **PhoneNumberFormat** object. 2. Instantiate a **PhoneNumberFormat** object.
...@@ -359,7 +359,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. ...@@ -359,7 +359,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Convert a measurement unit. 2. Convert a measurement unit.
...@@ -393,7 +393,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. ...@@ -393,7 +393,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiates an **IndexUtil** object. 2. Instantiates an **IndexUtil** object.
...@@ -418,7 +418,7 @@ The **I18NUtil** class provides an API to implement measurement conversion. ...@@ -418,7 +418,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
Call **addLocale** to add the alphabet index of a new locale to the current index list. Call **addLocale** to add the alphabet index of a new locale to the current index list.
```js ```js
indexUtil.addLocale("ar") indexUtil.addLocale("ar");
``` ```
5. Obtain the index of a string. 5. Obtain the index of a string.
...@@ -454,7 +454,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc ...@@ -454,7 +454,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate a **BreakIterator** object. 2. Instantiate a **BreakIterator** object.
...@@ -462,7 +462,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc ...@@ -462,7 +462,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
Call **getLineInstance** to instantiate a **BreakIterator** object. Call **getLineInstance** to instantiate a **BreakIterator** object.
```js ```js
let locale = "en-US" let locale = "en-US";
let breakIterator = I18n.getLineInstance(locale); let breakIterator = I18n.getLineInstance(locale);
``` ```
...@@ -531,7 +531,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc ...@@ -531,7 +531,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Instantiate the **TimeZone** object, and obtain the time zone information. 2. Instantiate the **TimeZone** object, and obtain the time zone information.
...@@ -592,7 +592,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to ...@@ -592,7 +592,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Obtains the transliterator ID list. 2. Obtains the transliterator ID list.
...@@ -637,7 +637,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to ...@@ -637,7 +637,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Check the input character has a certain attribute. 2. Check the input character has a certain attribute.
...@@ -719,7 +719,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to ...@@ -719,7 +719,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module. 1. Import the **i18n** module.
```js ```js
import I18n from '@ohos.i18n' import I18n from '@ohos.i18n';
``` ```
2. Check the sequence of year, month, and day in a date. 2. Check the sequence of year, month, and day in a date.
......
...@@ -25,7 +25,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -25,7 +25,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiates a **Locale** object. 2. Instantiates a **Locale** object.
...@@ -100,7 +100,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -100,7 +100,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **DateTimeFormat** object. 2. Instantiate a **DateTimeFormat** object.
...@@ -170,7 +170,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -170,7 +170,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **NumberFormat** object. 2. Instantiate a **NumberFormat** object.
...@@ -195,7 +195,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ...@@ -195,7 +195,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
```js ```js
let options = {compactDisplay: "short", notation: "compact"}; let options = {compactDisplay: "short", notation: "compact"};
let numberFormat = new Intl.NumberFormat("zh-CN", options); let numberFormat = new Intl.NumberFormat("zh-CN", options);
let number = 1234.5678 let number = 1234.5678;
let formatResult = numberFormat.format(number); // formatResult = "1235" let formatResult = numberFormat.format(number); // formatResult = "1235"
``` ```
...@@ -229,7 +229,7 @@ Users in different regions have different requirements for string sorting. [Coll ...@@ -229,7 +229,7 @@ Users in different regions have different requirements for string sorting. [Coll
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **Collator** object. 2. Instantiate a **Collator** object.
...@@ -290,7 +290,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -290,7 +290,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **PluralRules** object. 2. Instantiate a **PluralRules** object.
...@@ -313,7 +313,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -313,7 +313,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js ```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
let number = 1234.5678 let number = 1234.5678;
let categoryResult = pluralRules.select(number); // categoryResult = "other" let categoryResult = pluralRules.select(number); // categoryResult = "other"
``` ```
...@@ -338,7 +338,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -338,7 +338,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior. Importing an incorrect bundle can lead to unexpected API behavior.
```js ```js
import Intl from '@ohos.intl' import Intl from '@ohos.intl';
``` ```
2. Instantiate a **RelativeTimeFormat** object. 2. Instantiate a **RelativeTimeFormat** object.
...@@ -362,7 +362,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -362,7 +362,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2; let number = 2;
let unit = "year" let unit = "year";
let formatResult = relativeTimeFormat.format(number, unit); // 2 years later let formatResult = relativeTimeFormat.format(number, unit); // 2 years later
``` ```
...@@ -373,7 +373,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -373,7 +373,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2; let number = 2;
let unit = "year" let unit = "year";
let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}] let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}]
``` ```
......
...@@ -312,7 +312,7 @@ ...@@ -312,7 +312,7 @@
- [@ohos.systemParameterV9 (System Parameter)](js-apis-system-parameterV9.md) - [@ohos.systemParameterV9 (System Parameter)](js-apis-system-parameterV9.md)
- [@ohos.thermal (Thermal Management)](js-apis-thermal.md) - [@ohos.thermal (Thermal Management)](js-apis-thermal.md)
- [@ohos.update (Update)](js-apis-update.md) - [@ohos.update (Update)](js-apis-update.md)
- [@ohos.usbV9 (USB Management)](js-apis-usb.md) - [@ohos.usbManager (USB Manager)](js-apis-usbManager.md)
- [@ohos.vibrator (Vibrator)](js-apis-vibrator.md) - [@ohos.vibrator (Vibrator)](js-apis-vibrator.md)
- Account Management - Account Management
- [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md)
......
...@@ -2,9 +2,11 @@ ...@@ -2,9 +2,11 @@
The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status. The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status.
> **NOTE**<br> > **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 initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```js ```js
...@@ -20,18 +22,18 @@ Describes battery information. ...@@ -20,18 +22,18 @@ Describes battery information.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------- | ------------------- | ---- | ---- | ---------------------| | --------------- | ------------------- | ---- | ---- | ---------------------|
| batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. | | batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. |
| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the device. | | chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging status of the device. |
| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the device. | | healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health status of the device. |
| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. | | pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. |
| voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. | | voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. |
| technology | string | Yes | No | Battery technology of the device. | | technology | string | Yes | No | Battery technology of the device. |
| batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. | | batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. |
| isBatteryPresent<sup>7+</sup> | boolean | Yes | No | Whether the battery is supported or present. | | isBatteryPresent<sup>7+</sup> | boolean | Yes | No | Whether the battery is supported or present. |
| batteryCapacityLevel<sup>9+</sup> | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. | | batteryCapacityLevel<sup>9+</sup> | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. |
| estimatedRemainingChargeTime<sup>9+</sup> | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. | | estimatedRemainingChargeTime<sup>9+</sup> | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. This is a system API. |
| totalEnergy<sup>9+</sup> | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. | | totalEnergy<sup>9+</sup> | number | Yes | No | Total battery capacity of the device, in unit of mAh. **System API**: This is a system API. |
| nowCurrent<sup>9+</sup> | number | Yes | No | Battery current of the device, in unit of mA. This is a system API. | | nowCurrent<sup>9+</sup> | number | Yes | No | Battery current of the device, in unit of mA. **System API**: This is a system API. |
| remainingEnergy<sup>9+</sup> | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. This is a system API.| | remainingEnergy<sup>9+</sup> | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. **System API**: This is a system API.|
## BatteryPluggedType ## BatteryPluggedType
...@@ -41,10 +43,10 @@ Enumerates charger types. ...@@ -41,10 +43,10 @@ Enumerates charger types.
| Name | Value | Description | | Name | Value | Description |
| -------- | ---- | ----------------- | | -------- | ---- | ----------------- |
| NONE | 0 | Unknown type | | NONE | 0 | Unknown charger type. |
| AC | 1 | AC charger| | AC | 1 | AC charger.|
| USB | 2 | USB charger | | USB | 2 | USB charger. |
| WIRELESS | 3 | Wireless charger| | WIRELESS | 3 | Wireless charger.|
## BatteryChargeState ## BatteryChargeState
...@@ -82,14 +84,15 @@ Enumerates battery levels. ...@@ -82,14 +84,15 @@ Enumerates battery levels.
| Name | Value| Description | | Name | Value| Description |
| -------------- | ------ | ---------------------------- | | -------------- | ------ | ---------------------------- |
| LEVEL_NONE | 0 | Unknown battery level. |
| LEVEL_FULL | 1 | Full battery level. | | LEVEL_FULL | 1 | Full battery level. |
| LEVEL_HIGH | 2 | High battery level. | | LEVEL_HIGH | 2 | High battery level. |
| LEVEL_NORMAL | 3 | Normal battery level.| | LEVEL_NORMAL | 3 | Normal battery level.|
| LEVEL_LOW | 4 | Low battery level. | | LEVEL_LOW | 4 | Low battery level. |
| LEVEL_CRITICAL | 5 | Ultra-low battery level.| | LEVEL_WARNING | 5 | Alarm battery level.|
| LEVEL_CRITICAL | 6 | Ultra-low battery level.|
| LEVEL_SHUTDOWN | 7 | Power-down battery level.|
## CommonEventBatteryChangedCode<sup>9+</sup> ## CommonEventBatteryChangedKey<sup>9+</sup>
Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event. Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event.
...@@ -97,14 +100,12 @@ Enumerates keys for querying the additional information about the **COMMON_EVENT ...@@ -97,14 +100,12 @@ Enumerates keys for querying the additional information about the **COMMON_EVENT
| Name | Value| Description | | Name | Value| Description |
| -------------------- | ------ | -------------------------------------------------- | | -------------------- | ------ | -------------------------------------------------- |
| EXTRA_SOC | 0 | Remaining battery level in percentage. | | EXTRA_SOC | "soc" | Remaining battery level in percentage. |
| EXTRA_VOLTAGE | 1 | Battery voltage of the device. | | EXTRA_CHARGE_STATE | "chargeState" | Battery charging status of the device. |
| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. | | EXTRA_HEALTH_STATE | "healthState" | Battery health status of the device. |
| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. | | EXTRA_PLUGGED_TYPE | "pluggedType" | Type of the charger connected to the device. |
| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. | | EXTRA_VOLTAGE | "voltage" | Battery voltage of the device. |
| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. | | EXTRA_TECHNOLOGY | "technology" | Battery technology of the device. |
| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. | | EXTRA_TEMPERATURE | "temperature" | Battery temperature of the device. |
| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. | | EXTRA_PRESENT | "present" | Whether the battery is supported by the device or installed.|
| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. | | EXTRA_CAPACITY_LEVEL | "capacityLevel" | Battery level of the device. |
| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.|
| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. |
...@@ -175,7 +175,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono ...@@ -175,7 +175,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono
| -------- | -------------------- | ---- | ------------------------ | | -------- | -------------------- | ---- | ------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| | type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.|
| uri | string | Yes | URI of the data.| | uri | string | Yes | URI of the data.|
| callback | AsyncCallback&lt;void&gt; | No | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | No | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
......
...@@ -53,10 +53,10 @@ Stage model: ...@@ -53,10 +53,10 @@ Stage model:
```ts ```ts
// Import the module. // Import the module.
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -110,7 +110,7 @@ Called when the **revokeSave()** API is successfully called. ...@@ -110,7 +110,7 @@ Called when the **revokeSave()** API is successfully called.
## DistributedObjectV9 ## DistributedObjectV9
Provides APIs for managing a distributed data object. Represents a distributed data object.
### setSessionId<sup>9+</sup> ### setSessionId<sup>9+</sup>
...@@ -156,10 +156,10 @@ Stage model: ...@@ -156,10 +156,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -218,10 +218,10 @@ Stage model: ...@@ -218,10 +218,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -257,7 +257,7 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -257,7 +257,7 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
...@@ -294,10 +294,10 @@ Stage model: ...@@ -294,10 +294,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -321,7 +321,7 @@ g_object.setSessionId().then (()=>{ ...@@ -321,7 +321,7 @@ g_object.setSessionId().then (()=>{
on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Subscribes to data changes of this distributed data object. Subscribes to the data change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
...@@ -357,10 +357,10 @@ Stage model: ...@@ -357,10 +357,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -381,7 +381,7 @@ g_object.on("change", globalThis.changeCallback); ...@@ -381,7 +381,7 @@ g_object.on("change", globalThis.changeCallback);
off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Unsubscribes from the data changes of this distributed data object. Unsubscribes from the data change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
...@@ -413,10 +413,10 @@ Stage model: ...@@ -413,10 +413,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -432,7 +432,7 @@ g_object.off("change"); ...@@ -432,7 +432,7 @@ g_object.off("change");
on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void
Subscribes to statue changes of this distributed data object. Subscribes to the status change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
...@@ -463,10 +463,10 @@ Stage model: ...@@ -463,10 +463,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -507,7 +507,7 @@ let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:fals ...@@ -507,7 +507,7 @@ let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:fals
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
// Unregister the specified status change callback. // Unsubscribe from the specified status change callback for the distributed data object.
g_object.off("status",globalThis.statusCallback); g_object.off("status",globalThis.statusCallback);
// Unregister all status change callbacks. // Unregister all status change callbacks.
g_object.off("status"); g_object.off("status");
...@@ -517,10 +517,10 @@ Stage model: ...@@ -517,10 +517,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -529,7 +529,7 @@ let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:fals ...@@ -529,7 +529,7 @@ let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:fals
globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
} }
// Unregister the specified status change callback. // Unsubscribe from all status change callbacks for the distributed data object.
g_object.off("status",globalThis.statusCallback); g_object.off("status",globalThis.statusCallback);
// Unregister all status change callbacks. // Unregister all status change callbacks.
g_object.off("status"); g_object.off("status");
...@@ -579,10 +579,10 @@ g_object.save("local", (result) => { ...@@ -579,10 +579,10 @@ g_object.save("local", (result) => {
Stage model: Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -627,6 +627,8 @@ The saved data will be released in the following cases: ...@@ -627,6 +627,8 @@ The saved data will be released in the following cases:
**Example** **Example**
FA model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
...@@ -643,13 +645,14 @@ g_object.save("local").then((result) => { ...@@ -643,13 +645,14 @@ g_object.save("local").then((result) => {
console.error("save failed"); console.error("save failed");
}); });
``` ```
Stage model:
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context
} }
...@@ -712,10 +715,10 @@ Stage model: ...@@ -712,10 +715,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
context = this.context context = this.context
} }
...@@ -786,10 +789,10 @@ Stage model: ...@@ -786,10 +789,10 @@ Stage model:
```ts ```ts
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context. // Obtain the context.
let context; let context;
class MainAbility extends Ability { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
context = this.context context = this.context
} }
...@@ -1000,7 +1003,7 @@ Unsubscribes from the status change of this distributed data object. ...@@ -1000,7 +1003,7 @@ Unsubscribes from the status change of this distributed data object.
| Name| Type| Mandatory| Description| | 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.| | 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.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.| | 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.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
......
...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re ...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | 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.| | callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | 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.|
...@@ -69,9 +69,9 @@ Stage model: ...@@ -69,9 +69,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -103,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result ...@@ -103,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
**Return value** **Return value**
...@@ -139,9 +139,9 @@ Stage model: ...@@ -139,9 +139,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. | | name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -215,9 +215,9 @@ Stage model: ...@@ -215,9 +215,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.| | name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value** **Return value**
...@@ -294,9 +294,9 @@ Stage model: ...@@ -294,9 +294,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. | | name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -358,9 +358,9 @@ Stage model: ...@@ -358,9 +358,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.| | name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value** **Return value**
...@@ -428,9 +428,9 @@ Stage model: ...@@ -428,9 +428,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -662,7 +662,7 @@ try { ...@@ -662,7 +662,7 @@ try {
has(key: string, callback: AsyncCallback&lt;boolean&gt;): void has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.. Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -698,7 +698,7 @@ try { ...@@ -698,7 +698,7 @@ try {
has(key: string): Promise&lt;boolean&gt; has(key: string): Promise&lt;boolean&gt;
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.. Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -987,7 +987,7 @@ Unsubscribes from data changes. ...@@ -987,7 +987,7 @@ Unsubscribes from data changes.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ------------------------------------------ | | -------- | -------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | | type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. |
| callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| | callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, all callbacks for data changes will be unregistered. |
**Example** **Example**
......
# @ohos.geoLocationManager (Geolocation Manager) # @ohos.geoLocationManager (Geolocation Manager)
The **geoLocationManager** module provides location service management functions. The **geoLocationManager** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.
> **NOTE**<br> > **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.
## Applying for Permissions ## Applying for Permissions
...@@ -18,18 +19,18 @@ The system provides the following location permissions: ...@@ -18,18 +19,18 @@ The system provides the following location permissions:
If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: 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 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. 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.
| API Version| Location Permission| Permission Application Result| Location Accuracy| | API Version| Location Permission| Permission Application Result| Location Accuracy|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| | Earlier than 9| ohos.permission.LOCATION | Successful| Location accurate to meters.|
| 9 and later| ohos.permission.LOCATION | Failure| No location obtained| | 9 and later| ohos.permission.LOCATION | Failed| No location obtained.|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Successful| Location accurate to 5 kilometers.|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Successful| Location accurate to meters.|
If your application needs to access the device location information when running in the background, it must be configured to be able to run in 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. If your application needs to access the device location information when running in the background, it must be configured to be able to run in 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). You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md).
...@@ -41,13 +42,288 @@ import geoLocationManager from '@ohos.geoLocationManager'; ...@@ -41,13 +42,288 @@ import geoLocationManager from '@ohos.geoLocationManager';
``` ```
## ReverseGeoCodeRequest
Defines a reverse geocoding request.
**System capability**: SystemCapability.Location.Location.Geocoder
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from **-90** to **90**.|
| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from **-180** to **180**.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
## GeoCodeRequest
Defines a geocoding request.
**System capability**: SystemCapability.Location.Location.Geocoder
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges. The value ranges from **-90** to **90**.|
| minLongitude | number | Yes| Yes| Minimum longitude. The value ranges from **-180** to **180**.|
| maxLatitude | number | Yes| Yes| Maximum latitude. The value ranges from **-90** to **90**.|
| maxLongitude | number | Yes| Yes| Maximum longitude. The value ranges from **-180** to **180**.|
## GeoAddress
Defines a geographic location.
**System capability**: SystemCapability.Location.Location.Geocoder
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| latitude | number | Yes| No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from **-90** to **90**.|
| longitude | number | Yes| No | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from **-180** to **180**.|
| locale | string | Yes| No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| placeName | string | Yes| No | Landmark of the location.|
| countryCode | string | Yes| No | Country code.|
| countryName | string| Yes| No| Country name.|
| administrativeArea | string | Yes| No| Administrative region name.|
| subAdministrativeArea | string | Yes| No| Sub-administrative region name.|
| locality | string | Yes| No| Locality information.|
| subLocality | string | Yes| No| Sub-locality information.|
| roadName | string | Yes| No|Road name.|
| subRoadName | string | Yes| No| Auxiliary road information.|
| premises | string| Yes| No|House information.|
| postalCode | string | Yes| No| Postal code.|
| phoneNumber | string | Yes| No| Phone number.|
| addressUrl | string | Yes| No| Website URL.|
| descriptions | Array&lt;string&gt; | Yes| No| Additional descriptions.|
| descriptionsSize | number | Yes| No| Total number of additional descriptions. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
| isFromMock | Boolean | Yes| No| Whether the geographic address is obtained from the mock reverse geocoding function.<br>**System API**: This is a system API.|
## LocationRequest
Defines a location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request. For details about the value range, see [LocationRequestPriority](#locationrequestpriority).|
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request. For details about the value range, see [LocationRequestScenario](#locationrequestscenario).|
| timeInterval | number | Yes| Yes| Time interval at which location information is reported, in seconds. The value must be greater than **0**.|
| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported. The value must be greater than **0**, in meters.|
| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The value must be greater than **0**.|
## CurrentLocationRequest
Defines the current location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request. For details about the value range, see [LocationRequestPriority](#locationrequestpriority).|
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request. For details about the value range, see [LocationRequestScenario](#locationrequestscenario).|
| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The value must be greater than **0**.|
| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**. The value must be greater than or equal to **1000**.|
## SatelliteStatusInfo
Defines the satellite status information.
**System capability**: SystemCapability.Location.Location.Gnss
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| satellitesNumber | number | Yes| No| Number of satellites. The value must be greater than or equal to **0**.|
| satelliteIds | Array&lt;number&gt; | Yes| No| Array of satellite IDs. The value must be greater than or equal to **0**.|
| carrierToNoiseDensitys | Array&lt;number&gt; | Yes| No| Carrier-to-noise density ratio, that is, **cn0**. The value must be greater than **0**.|
| altitudes | Array&lt;number&gt; | Yes| No| Satellite altitude angle information. The value ranges from **-90** to **90**, in degrees.|
| azimuths | Array&lt;number&gt; | Yes| No| Azimuth information. The value ranges from **0** to **360**, in degrees.|
| carrierFrequencies | Array&lt;number&gt; | Yes| No| Carrier frequency. The value must be greater than or equal to **0**, in Hz.|
## CachedGnssLocationsRequest
Represents a request for reporting cached GNSS locations.
**System capability**: SystemCapability.Location.Location.Gnss
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds. The value must be greater than **0**.|
| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.<br>**false**: discards the cached GNSS locations when the cache queue is full.|
## Geofence
Defines a GNSS geofence. Currently, only circular geofences are supported.
**System capability**: SystemCapability.Location.Location.Geofence
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| latitude | number | Yes| Yes|Latitude information. The value ranges from **-90** to **90**.|
| longitude | number | Yes|Yes| Longitude information. The value ranges from **-180** to **180**.|
| radius | number | Yes|Yes| Radius of a circular geofence. The value must be greater than **0**, in meters.|
| expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds. The value must be greater than **0**.|
## GeofenceRequest
Represents a GNSS geofencing request.
**System capability**: SystemCapability.Location.Location.Geofence
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.|
| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.|
## LocationCommand
Defines an extended command.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.|
| command | string | Yes| Yes | Extended command, in the string format.|
## Location
Defines a location.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| latitude | number| Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from **-90** to **90**.|
| longitude | number| Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from **-180** to **180**.|
| altitude | number | Yes| No| Location altitude, in meters.|
| accuracy | number | Yes| No| Location accuracy, in meters.|
| speed | number | Yes| No|Speed, in m/s.|
| timeStamp | number | Yes| No| Location timestamp in the UTC format.|
| direction | number | Yes| No| Direction information. The value ranges from **0** to **360**, in degrees.|
| timeSinceBoot | number | Yes| No| Location timestamp since boot.|
| additions | Array&lt;string&gt; | Yes| No| Additional description.|
| additionSize | number | Yes| No| Number of additional descriptions. The value must be greater than or equal to **0**. |
| isFromMock | Boolean | Yes| No| Whether the location information is from the mock location function.<br>**System API**: This is a system API.|
## ReverseGeocodingMockInfo
Represents information of the mock reverse geocoding function.
**System capability**: SystemCapability.Location.Location.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Yes| Latitude and longitude information.|
| geoAddress | [GeoAddress](#geoaddress) | Yes| Yes|Geographic address.|
## LocationMockConfig
Represents the mock location configuration.
**System capability**: SystemCapability.Location.Location.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| timeInterval | number | Yes| Yes| Interval at which mock locations are reported, in seconds.|
| locations | Array&lt;[Location](#location)&gt; | Yes| Yes| Array of mocked locations.|
## CountryCode
Represents country code information.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| country | string | Yes| No| Country code.|
| type | [CountryCodeType](#countrycodetype) | Yes| No| Country code source.|
## LocationRequestPriority
Sets the priority of the location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x200 | Priority unspecified.<br>If this option is used, [LocationRequestPriority](#locationrequestpriority) is invalid.|
| ACCURACY | 0x201 | Location accuracy preferred.<br>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.|
| LOW_POWER | 0x202 | Power efficiency preferred.<br>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.|
| FIRST_FIX | 0x203 | Fast location preferred. Use this option if you want to obtain a location as fast as possible.<br>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. It can lead to significant hardware resource consumption and power consumption.|
## LocationRequestScenario
Sets the scenario of the location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x300 | Scenario unspecified.<br>If this option is used, [LocationRequestScenario](#locationrequest scenario) is invalid.|
| NAVIGATION | 0x301 | Navigation scenario.<br>This option is applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking.<br>In this scenario, GNSS positioning is used to provide location services to ensure the optimal location accuracy of the system.<br>The location result is reported at a minimum interval of 1 second by default.|
| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking scenario.<br>This option is 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.<br>The location result is reported at a minimum interval of 1 second by default.|
| CAR_HAILING | 0x303 | Ride hailing scenario.<br>This option is applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>The location result is reported at a minimum interval of 1 second by default.|
| DAILY_LIFE_SERVICE | 0x304 | Daily life service scenario.<br>This option is 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.<br>The location result is reported at a minimum interval of 1 second by default.|
| NO_POWER | 0x305 | Power efficiency scenario.<br>This option is applicable when your application does not proactively start the location service. 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.|
## LocationPrivacyType
Defines the privacy statement type.
**System capability**: SystemCapability.Location.Location.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Value| Description|
| -------- | -------- | -------- |
| OTHERS | 0 | Other scenarios. Reserved field.|
| STARTUP | 1 | Privacy statement displayed in the startup wizard. |
| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.|
## CountryCodeType
Represents the country code source type.
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| COUNTRY_CODE_FROM_LOCALE | 1 | Country code obtained from the language configuration of the globalization module.|
| COUNTRY_CODE_FROM_SIM | 2 | Country code obtained from the SIM card.|
| COUNTRY_CODE_FROM_LOCATION | 3 | Country code obtained using the reverse geocoding function based on the user's location information.|
| COUNTRY_CODE_FROM_NETWORK | 4 | Country code obtained from the cellular network registration information.|
## geoLocationManager.on('locationChange') ## geoLocationManager.on('locationChange')
on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;): void on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;): void
Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). Registers a listener for location changes with a location request initiated.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
...@@ -73,8 +349,8 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -73,8 +349,8 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => { let locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location)); console.log('locationChanger: data: ' + JSON.stringify(location));
}; };
try { try {
...@@ -92,7 +368,7 @@ off(type: 'locationChange', callback?: Callback&lt;Location&gt;): void ...@@ -92,7 +368,7 @@ off(type: 'locationChange', callback?: Callback&lt;Location&gt;): void
Unregisters the listener for location changes with the corresponding location request deleted. Unregisters the listener for location changes with the corresponding location request deleted.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
...@@ -117,8 +393,8 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -117,8 +393,8 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => { let locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location)); console.log('locationChanger: data: ' + JSON.stringify(location));
}; };
try { try {
...@@ -157,7 +433,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -157,7 +433,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var locationEnabledChange = (state) => { let locationEnabledChange = (state) => {
console.log('locationEnabledChange: ' + JSON.stringify(state)); console.log('locationEnabledChange: ' + JSON.stringify(state));
} }
try { try {
...@@ -195,7 +471,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -195,7 +471,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var locationEnabledChange = (state) => { let locationEnabledChange = (state) => {
console.log('locationEnabledChange: state: ' + JSON.stringify(state)); console.log('locationEnabledChange: state: ' + JSON.stringify(state));
} }
try { try {
...@@ -213,7 +489,7 @@ on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callb ...@@ -213,7 +489,7 @@ on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callb
Registers a listener for cached GNSS location reports. Registers a listener for cached GNSS location reports.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -239,10 +515,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -239,10 +515,10 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var cachedLocationsCb = (locations) => { let cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations));
} }
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
try { try {
geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb);
} catch (err) { } catch (err) {
...@@ -257,7 +533,7 @@ off(type: 'cachedGnssLocationsChange', callback?: Callback&lt;Array&lt;Location& ...@@ -257,7 +533,7 @@ off(type: 'cachedGnssLocationsChange', callback?: Callback&lt;Array&lt;Location&
Unregisters the listener for cached GNSS location reports. Unregisters the listener for cached GNSS location reports.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -282,10 +558,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -282,10 +558,10 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var cachedLocationsCb = (locations) => { let cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations));
} }
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
try { try {
geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb);
geoLocationManager.off('cachedGnssLocationsChange'); geoLocationManager.off('cachedGnssLocationsChange');
...@@ -301,7 +577,7 @@ on(type: 'satelliteStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) ...@@ -301,7 +577,7 @@ on(type: 'satelliteStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;)
Registers a listener for GNSS satellite status change events. Registers a listener for GNSS satellite status change events.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -325,7 +601,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -325,7 +601,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var gnssStatusCb = (satelliteStatusInfo) => { let gnssStatusCb = (satelliteStatusInfo) => {
console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo));
} }
...@@ -343,7 +619,7 @@ off(type: 'satelliteStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt ...@@ -343,7 +619,7 @@ off(type: 'satelliteStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt
Unregisters the listener for GNSS satellite status change events. Unregisters the listener for GNSS satellite status change events.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -368,7 +644,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -368,7 +644,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var gnssStatusCb = (satelliteStatusInfo) => { let gnssStatusCb = (satelliteStatusInfo) => {
console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo));
} }
try { try {
...@@ -411,7 +687,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -411,7 +687,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var nmeaCb = (str) => { let nmeaCb = (str) => {
console.log('nmeaMessage: ' + JSON.stringify(str)); console.log('nmeaMessage: ' + JSON.stringify(str));
} }
...@@ -454,7 +730,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -454,7 +730,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var nmeaCb = (str) => { let nmeaCb = (str) => {
console.log('nmeaMessage: ' + JSON.stringify(str)); console.log('nmeaMessage: ' + JSON.stringify(str));
} }
...@@ -473,7 +749,7 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo ...@@ -473,7 +749,7 @@ on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): vo
Registers a listener for status change events of the specified geofence. Registers a listener for status change events of the specified geofence.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Geofence **System capability**: SystemCapability.Location.Location.Geofence
...@@ -483,7 +759,7 @@ Registers a listener for status change events of the specified geofence. ...@@ -483,7 +759,7 @@ Registers a listener for status change events of the specified geofence.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.|
| request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.|
| want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to return geofence (entrance or exit) events.|
**Error codes** **Error codes**
...@@ -499,23 +775,23 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -499,23 +775,23 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility", abilityName: "EntryAbility",
action: "action1", action: "action1"
} }
], ],
operationType: wantAgent.OperationType.START_ABILITY, operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0, requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}; };
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
try { try {
geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
} catch (err) { } catch (err) {
...@@ -531,7 +807,7 @@ off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): v ...@@ -531,7 +807,7 @@ off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): v
Unregisters the listener for status change events of the specified geofence. Unregisters the listener for status change events of the specified geofence.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Geofence **System capability**: SystemCapability.Location.Location.Geofence
...@@ -541,7 +817,7 @@ Unregisters the listener for status change events of the specified geofence. ...@@ -541,7 +817,7 @@ Unregisters the listener for status change events of the specified geofence.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.|
| request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.|
| want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to return geofence (entrance or exit) events.|
**Error codes** **Error codes**
...@@ -557,13 +833,13 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -557,13 +833,13 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility", abilityName: "EntryAbility",
action: "action1", action: "action1",
} }
], ],
...@@ -573,7 +849,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -573,7 +849,7 @@ For details about the following error codes, see [Location Error Codes](../error
}; };
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
try { try {
geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj); geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj);
...@@ -614,7 +890,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -614,7 +890,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var callback = (code) => { let callback = (code) => {
console.log('countryCodeChange: ' + JSON.stringify(code)); console.log('countryCodeChange: ' + JSON.stringify(code));
} }
...@@ -655,7 +931,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -655,7 +931,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var callback = (code) => { let callback = (code) => {
console.log('countryCodeChange: ' + JSON.stringify(code)); console.log('countryCodeChange: ' + JSON.stringify(code));
} }
...@@ -675,7 +951,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;L ...@@ -675,7 +951,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;L
Obtains the current location. This API uses an asynchronous callback to return the result. Obtains the current location. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
...@@ -700,8 +976,8 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -700,8 +976,8 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
var locationChange = (err, location) => { let locationChange = (err, location) => {
if (err) { if (err) {
console.log('locationChanger: err=' + JSON.stringify(err)); console.log('locationChanger: err=' + JSON.stringify(err));
} }
...@@ -723,7 +999,7 @@ getCurrentLocation(callback: AsyncCallback&lt;Location&gt;): void; ...@@ -723,7 +999,7 @@ getCurrentLocation(callback: AsyncCallback&lt;Location&gt;): void;
Obtains the current location. This API uses an asynchronous callback to return the result. Obtains the current location. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
...@@ -747,7 +1023,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -747,7 +1023,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var locationChange = (err, location) => { let locationChange = (err, location) => {
if (err) { if (err) {
console.log('locationChanger: err=' + JSON.stringify(err)); console.log('locationChanger: err=' + JSON.stringify(err));
} }
...@@ -769,7 +1045,7 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise&lt;Location&gt; ...@@ -769,7 +1045,7 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise&lt;Location&gt;
Obtains the current location. This API uses a promise to return the result. Obtains the current location. This API uses a promise to return the result.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
...@@ -783,87 +1059,7 @@ Obtains the current location. This API uses a promise to return the result. ...@@ -783,87 +1059,7 @@ Obtains the current location. This API uses a promise to return the result.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;[Location](#location)&gt; | [Location](#location) | NA | Promise used to return the current location.| | Promise&lt;[Location](#location)&gt; | [Location](#location) | NA | Promise used to return the current location.|
**Error codes**
For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
|3301000 | Location service is unavailable. |
|3301100 | The location switch is off. |
|3301200 | Failed to obtain the geographical location. |
**Example**
```ts
import geoLocationManager from '@ohos.geoLocationManager';
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
try {
geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
console.log('current location: ' + JSON.stringify(result));
})
.catch((error) => {
console.log('promise, getCurrentLocation: error=' + JSON.stringify(error));
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
## geoLocationManager.getLastLocation
getLastLocation(): Location
Obtains the last location.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core
**Return value**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| Location | [Location](#location) | NA | Location information.|
**Error codes**
For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
|3301000 | Location service is unavailable. |
|3301100 | The location switch is off. |
|3301200 |Failed to obtain the geographical location. |
**Example**
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
var location = geoLocationManager.getLastLocation();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
## geoLocationManager.isLocationEnabled
isLocationEnabled(): boolean
Checks whether the location service is enabled.
**System capability**: SystemCapability.Location.Location.Core
**Return value**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| boolean | boolean | NA | Result indicating whether the location service is enabled.|
**Error codes** **Error codes**
...@@ -872,34 +1068,42 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -872,34 +1068,42 @@ For details about the following error codes, see [Location Error Codes](../error
| ID| Error Message| | ID| Error Message|
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
|3301100 | The location switch is off. |
|3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
try { try {
var locationEnabled = geoLocationManager.isLocationEnabled(); geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
console.log('current location: ' + JSON.stringify(result));
})
.catch((error) => {
console.log('promise, getCurrentLocation: error=' + JSON.stringify(error));
});
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
} }
``` ```
## geoLocationManager.requestEnableLocation ## geoLocationManager.getLastLocation
requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;): void getLastLocation(): Location
Requests to enable the location service. This API uses an asynchronous callback to return the result. Obtains the last location.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
**Parameters** **Return value**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| | Location | [Location](#location) | NA | Location information.|
**Error codes** **Error codes**
...@@ -908,34 +1112,26 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -908,34 +1112,26 @@ For details about the following error codes, see [Location Error Codes](../error
| ID| Error Message| | ID| Error Message|
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
|3301700 | No response to the request. | |3301100 | The location switch is off. |
|3301200 |Failed to obtain the geographical location. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
geoLocationManager.requestEnableLocation((err, data) => { let location = geoLocationManager.getLastLocation();
if (err) {
console.log('requestEnableLocation: err=' + JSON.stringify(err));
}
if (data) {
console.log('requestEnableLocation: data=' + JSON.stringify(data));
}
});
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
} }
``` ```
## geoLocationManager.requestEnableLocation ## geoLocationManager.isLocationEnabled
requestEnableLocation(): Promise&lt;boolean&gt;
Requests to enable the location service. This API uses a promise to return the result. isLocationEnabled(): boolean
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION Checks whether the location service is enabled.
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
...@@ -943,7 +1139,7 @@ Requests to enable the location service. This API uses a promise to return the r ...@@ -943,7 +1139,7 @@ Requests to enable the location service. This API uses a promise to return the r
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;boolean&gt; | boolean | NA | Promise used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| | boolean | boolean | NA | Result indicating whether the location service is enabled.|
**Error codes** **Error codes**
...@@ -952,19 +1148,13 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -952,19 +1148,13 @@ For details about the following error codes, see [Location Error Codes](../error
| ID| Error Message| | ID| Error Message|
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
|3301700 | No response to the request. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
geoLocationManager.requestEnableLocation().then((result) => { let locationEnabled = geoLocationManager.isLocationEnabled();
console.log('promise, requestEnableLocation: ' + JSON.stringify(result));
})
.catch((error) => {
console.log('promise, requestEnableLocation: error=' + JSON.stringify(error));
});
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
} }
...@@ -1092,7 +1282,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1092,7 +1282,7 @@ For details about the following error codes, see [Location Error Codes](../error
getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void
Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. Converts coordinates into geographic descriptions through reverse geocoding. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Location.Location.Geocoder **System capability**: SystemCapability.Location.Location.Geocoder
...@@ -1116,7 +1306,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1116,7 +1306,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
try { try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) { if (err) {
...@@ -1136,7 +1326,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1136,7 +1326,7 @@ For details about the following error codes, see [Location Error Codes](../error
getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt;; getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt;;
Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. Converts coordinates into geographic descriptions through reverse geocoding. This API uses a promise to return the result.
**System capability**: SystemCapability.Location.Location.Geocoder **System capability**: SystemCapability.Location.Location.Geocoder
...@@ -1165,7 +1355,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1165,7 +1355,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
try { try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data)); console.log('getAddressesFromLocation: ' + JSON.stringify(data));
...@@ -1183,7 +1373,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1183,7 +1373,7 @@ For details about the following error codes, see [Location Error Codes](../error
getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void
Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. Converts geographic descriptions into coordinates through geocoding. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Location.Location.Geocoder **System capability**: SystemCapability.Location.Location.Geocoder
...@@ -1207,7 +1397,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1207,7 +1397,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; let geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
try { try {
geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) { if (err) {
...@@ -1227,7 +1417,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1227,7 +1417,7 @@ For details about the following error codes, see [Location Error Codes](../error
getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt;
Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. Converts geographic descriptions into coordinates through geocoding. This API uses a promise to return the result.
**System capability**: SystemCapability.Location.Location.Geocoder **System capability**: SystemCapability.Location.Location.Geocoder
...@@ -1256,7 +1446,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1256,7 +1446,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; let geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
try { try {
geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => { geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); console.log('getAddressesFromLocationName: ' + JSON.stringify(result));
...@@ -1296,7 +1486,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1296,7 +1486,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
var isAvailable = geoLocationManager.isGeocoderAvailable(); let isAvailable = geoLocationManager.isGeocoderAvailable();
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
} }
...@@ -1309,7 +1499,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;): void; ...@@ -1309,7 +1499,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;): void;
Obtains the number of cached GNSS locations. Obtains the number of cached GNSS locations.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -1353,7 +1543,7 @@ getCachedGnssLocationsSize(): Promise&lt;number&gt;; ...@@ -1353,7 +1543,7 @@ getCachedGnssLocationsSize(): Promise&lt;number&gt;;
Obtains the number of cached GNSS locations. Obtains the number of cached GNSS locations.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -1395,7 +1585,7 @@ flushCachedGnssLocations(callback: AsyncCallback&lt;void&gt;): void; ...@@ -1395,7 +1585,7 @@ flushCachedGnssLocations(callback: AsyncCallback&lt;void&gt;): void;
Obtains all cached GNSS locations and clears the GNSS cache queue. Obtains all cached GNSS locations and clears the GNSS cache queue.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -1437,7 +1627,7 @@ flushCachedGnssLocations(): Promise&lt;void&gt;; ...@@ -1437,7 +1627,7 @@ flushCachedGnssLocations(): Promise&lt;void&gt;;
Obtains all cached GNSS locations and clears the GNSS cache queue. Obtains all cached GNSS locations and clears the GNSS cache queue.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION **Required permissions**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Gnss **System capability**: SystemCapability.Location.Location.Gnss
...@@ -1501,7 +1691,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1501,7 +1691,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var requestInfo = {'scenario': 0x301, 'command': "command_1"}; let requestInfo = {'scenario': 0x301, 'command': "command_1"};
try { try {
geoLocationManager.sendCommand(requestInfo, (err, result) => { geoLocationManager.sendCommand(requestInfo, (err, result) => {
if (err) { if (err) {
...@@ -1546,7 +1736,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1546,7 +1736,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var requestInfo = {'scenario': 0x301, 'command': "command_1"}; let requestInfo = {'scenario': 0x301, 'command': "command_1"};
try { try {
geoLocationManager.sendCommand(requestInfo).then((result) => { geoLocationManager.sendCommand(requestInfo).then((result) => {
console.log('promise, sendCommand success'); console.log('promise, sendCommand success');
...@@ -1614,7 +1804,7 @@ Obtains the current country code. ...@@ -1614,7 +1804,7 @@ Obtains the current country code.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;[CountryCode](#countrycode)&gt; | [CountryCode](#countrycode) | NA | Callback used to return the country code.| | Promise&lt;[CountryCode](#countrycode)&gt; | [CountryCode](#countrycode) | NA | Promise used to return the country code.|
**Error codes** **Error codes**
...@@ -1711,6 +1901,8 @@ setMockedLocations(config: LocationMockConfig): void; ...@@ -1711,6 +1901,8 @@ setMockedLocations(config: LocationMockConfig): void;
Sets the mock location information. The mock locations will be reported at the interval specified in this API. Sets the mock location information. The mock locations will be reported at the interval specified in this API.
This API can be invoked only after [geoLocationManager.enableLocationMock](#geolocationmanagerenablelocationmock) is called.
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
**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.
...@@ -1734,15 +1926,16 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1734,15 +1926,16 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var locations = [ let locations = [
{"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true},
{"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true},
{"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true},
{"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true},
{"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true}
]; ];
var config = {"timeInterval": 5, "locations": locations}; let config = {"timeInterval": 5, "locations": locations};
try { try {
geoLocationManager.enableLocationMock();
geoLocationManager.setMockedLocations(config); geoLocationManager.setMockedLocations(config);
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
...@@ -1816,6 +2009,8 @@ setReverseGeocodingMockInfo(mockInfos: Array&lt;ReverseGeocodingMockInfo&gt;): v ...@@ -1816,6 +2009,8 @@ setReverseGeocodingMockInfo(mockInfos: Array&lt;ReverseGeocodingMockInfo&gt;): v
Sets information of the mock reverse geocoding function, including the mapping between a location and geographic name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographic name will be returned. Sets information of the mock reverse geocoding function, including the mapping between a location and geographic name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographic name will be returned.
This API can be invoked only after [geoLocationManager.enableReverseGeocodingMock](#geolocationmanagerenablereversegeocodingmock) is called.
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
**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.
...@@ -1824,7 +2019,7 @@ Sets information of the mock reverse geocoding function, including the mapping b ...@@ -1824,7 +2019,7 @@ Sets information of the mock reverse geocoding function, including the mapping b
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| mockInfos | Array&lt;[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)&gt; | Yes| Array of information of the mock reverse geocoding function, including a location and a geographic name.| | mockInfos | Array&lt;[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)&gt; | Yes| Array of information of the mock reverse geocoding function, including a location and a geographic address.|
**Error codes** **Error codes**
...@@ -1838,7 +2033,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1838,7 +2033,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
var mockInfos = [ let mockInfos = [
{"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}},
{"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}},
{"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}},
...@@ -1846,6 +2041,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1846,6 +2041,7 @@ For details about the following error codes, see [Location Error Codes](../error
{"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}},
]; ];
try { try {
geoLocationManager.enableReverseGeocodingMock();
geoLocationManager.setReverseGeocodingMockInfo(mockInfos); geoLocationManager.setReverseGeocodingMockInfo(mockInfos);
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
...@@ -1873,7 +2069,7 @@ Checks whether a user agrees with the privacy statement of the location service. ...@@ -1873,7 +2069,7 @@ Checks whether a user agrees with the privacy statement of the location service.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| boolean | boolean | NA | Result indicating whether the user agrees with the privacy statement.| | boolean | boolean | NA | Whether the user agrees with the privacy statement.|
**Error codes** **Error codes**
...@@ -1888,7 +2084,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1888,7 +2084,7 @@ For details about the following error codes, see [Location Error Codes](../error
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
var isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1); let isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1);
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
} }
...@@ -1932,276 +2128,3 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1932,276 +2128,3 @@ For details about the following error codes, see [Location Error Codes](../error
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
} }
``` ```
## LocationRequestPriority
Sets the priority of the location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x200 | Priority unspecified.|
| ACCURACY | 0x201 | Location accuracy.|
| LOW_POWER | 0x202 | Power efficiency.|
| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.|
## LocationRequestScenario
Sets the scenario of the location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x300 | Scenario unspecified.|
| NAVIGATION | 0x301 | Navigation.|
| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.|
| CAR_HAILING | 0x303 | Ride hailing.|
| DAILY_LIFE_SERVICE | 0x304 | Daily life services.|
| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. 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.|
## ReverseGeoCodeRequest
Defines a reverse geocoding request.
**System capability**: SystemCapability.Location.Location.Geocoder
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned.|
## GeoCodeRequest
Defines a geocoding request.
**System capability**: SystemCapability.Location.Location.Geocoder
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned.|
| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.|
| minLongitude | number | Yes| Yes| Minimum longitude.|
| maxLatitude | number | Yes| Yes| Maximum latitude.|
| maxLongitude | number | Yes| Yes| Maximum longitude.|
## GeoAddress
Defines a geographic location.
**System capability**: SystemCapability.Location.Location.Geocoder
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| latitude | number | Yes| No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude | number | Yes| No | Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| locale | string | Yes| No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| placeName | string | Yes| No | Landmark of the location.|
| countryCode | string | Yes| No | Country code.|
| countryName | string| Yes| No| Country name.|
| administrativeArea | string | Yes| No| Administrative region name.|
| subAdministrativeArea | string | Yes| No| Sub-administrative region name.|
| locality | string | Yes| No| Locality information.|
| subLocality | string | Yes| No| Sub-locality information.|
| roadName | string | Yes| No|Road name.|
| subRoadName | string | Yes| No| Auxiliary road information.|
| premises | string| Yes| No|House information.|
| postalCode | string | Yes| No| Postal code.|
| phoneNumber | string | Yes| No| Phone number.|
| addressUrl | string | Yes| No| Website URL.|
| descriptions | Array&lt;string&gt; | Yes| No| Additional descriptions.|
| descriptionsSize | number | Yes| No| Total number of additional descriptions.|
| isFromMock | Boolean | Yes| No| Whether the geographic name is from the mock reverse geocoding function.|
## LocationRequest
Defines a location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.|
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.|
| timeInterval | number | Yes| Yes| Time interval at which location information is reported.|
| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.|
| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.|
## CurrentLocationRequest
Defines the current location request.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.|
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.|
| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.|
| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.|
## SatelliteStatusInfo
Defines the satellite status information.
**System capability**: SystemCapability.Location.Location.Gnss
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| satellitesNumber | number | Yes| No| Number of satellites.|
| satelliteIds | Array&lt;number&gt; | Yes| No| Array of satellite IDs.|
| carrierToNoiseDensitys | Array&lt;number&gt; | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.|
| altitudes | Array&lt;number&gt; | Yes| No| Altitude information.|
| azimuths | Array&lt;number&gt; | Yes| No| Azimuth information.|
| carrierFrequencies | Array&lt;number&gt; | Yes| No| Carrier frequency.|
## CachedGnssLocationsRequest
Represents a request for reporting cached GNSS locations.
**System capability**: SystemCapability.Location.Location.Gnss
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.|
| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.<br>**false**: discards the cached GNSS locations when the cache queue is full.|
## Geofence
Defines a GNSS geofence. Currently, only circular geofences are supported.
**System capability**: SystemCapability.Location.Location.Geofence
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| latitude | number | Yes| Yes|Latitude information.|
| longitude | number | Yes|Yes| Longitude information.|
| radius | number | Yes|Yes| Radius of a circular geofence.|
| expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds.|
## GeofenceRequest
Represents a GNSS geofencing request.
**System capability**: SystemCapability.Location.Location.Geofence
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.|
| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.|
## LocationPrivacyType
Defines the privacy statement type.
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| OTHERS | 0 | Other scenarios.|
| STARTUP | 1 | Privacy statement displayed in the startup wizard.|
| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.|
## LocationCommand
Defines an extended command.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.|
| command | string | Yes| Yes | Extended command, in the string format.|
## Location
Defines a location.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| latitude | number| Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude | number| Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| altitude | number | Yes| No| Location altitude, in meters.|
| accuracy | number | Yes| No| Location accuracy, in meters.|
| speed | number | Yes| No|Speed, in m/s.|
| timeStamp | number | Yes| No| Location timestamp in the UTC format.|
| direction | number | Yes| No| Direction information.|
| timeSinceBoot | number | Yes| No| Location timestamp since boot.|
| additions | Array&lt;string&gt; | Yes| No| Additional description.|
| additionSize | number | Yes| No| Number of additional descriptions.|
| isFromMock | Boolean | Yes| No| Whether the location information is from the mock location function.|
## ReverseGeocodingMockInfo
Represents information of the mock reverse geocoding function.
**System capability**: SystemCapability.Location.Location.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Yes| Latitude and longitude information.|
| geoAddress | [GeoAddress](#geoaddress) | Yes| Yes|Geographic name.|
## LocationMockConfig
Represents the information of the mock location function.
**System capability**: SystemCapability.Location.Location.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| timeInterval | number | Yes| Yes| Interval at which mock locations are reported, in seconds.|
| locations | Array&lt;Location&gt; | Yes| Yes| Array of mocked locations.|
## CountryCode
Represents country code information.
**System capability**: SystemCapability.Location.Location.Core
| Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| country | string | Yes| No| Country code.|
| type | [CountryCodeType](#countrycodetype) | Yes| No| Country code source.|
## CountryCodeType
Represents the country code source type.
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| COUNTRY_CODE_FROM_LOCALE | 1 | Country code obtained from the language configuration of the globalization module.|
| COUNTRY_CODE_FROM_SIM | 2 | Country code obtained from the SIM card.|
| COUNTRY_CODE_FROM_LOCATION | 3 | Country code obtained using the reverse geocoding function based on the user's location information.|
| COUNTRY_CODE_FROM_NETWORK | 4 | Country code obtained from the cellular network registration information.|
# @ohos.geolocation (Geolocation) # Geolocation
The **geolocation** module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.
> **NOTE** > **NOTE**
> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The 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 provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead.
> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead.
## Applying for Permissions ## Applying for Permissions
...@@ -20,18 +19,18 @@ The system provides the following location permissions: ...@@ -20,18 +19,18 @@ The system provides the following location permissions:
If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: 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 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. 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.
| API Version| Location Permission| Permission Application Result| Location Accuracy| | API Version| Location Permission| Permission Application Result| Location Accuracy|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| | Earlier than 9| ohos.permission.LOCATION | Successful| Location accurate to meters.|
| 9 and later| ohos.permission.LOCATION | Failure| No location obtained| | 9 and later| ohos.permission.LOCATION | Failed| No location obtained.|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Successful| Location accurate to 5 kilometers.|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Successful| Location accurate to meters.|
If your application needs to access the device location information when running in the background, it must be configured to be able to run in 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. If your application needs to access the device location information when running in the background, it must be configured to be able to run in 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). You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md).
...@@ -42,13 +41,13 @@ You can declare the required permission in your application's configuration file ...@@ -42,13 +41,13 @@ You can declare the required permission in your application's configuration file
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
``` ```
## geolocation.on('locationChange')<sup>(deprecated) </sup> ## geolocation.on('locationChange')<sup>(deprecated)</sup>
on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;): void on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;): void
Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). Registers a listener for location changes with a location request initiated.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -60,8 +59,8 @@ Registers a listener for location changes with a location request initiated. The ...@@ -60,8 +59,8 @@ Registers a listener for location changes with a location request initiated. The
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **locationChange** indicates a location change event.| | type | string | Yes| Event type. The value **locationChange** indicates a location change event.|
| request | [LocationRequest](#locationrequest) | Yes| Location request.| | request | [LocationRequest](#locationrequestdeprecated) | Yes| Location request.|
| callback | Callback&lt;[Location](#location)&gt; | Yes| Callback used to return the location change event.| | callback | Callback&lt;[Location](#locationdeprecated)&gt; | Yes| Callback used to return the location change event.|
...@@ -69,21 +68,21 @@ Registers a listener for location changes with a location request initiated. The ...@@ -69,21 +68,21 @@ Registers a listener for location changes with a location request initiated. The
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => { let locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location)); console.log('locationChanger: data: ' + JSON.stringify(location));
}; };
geolocation.on('locationChange', requestInfo, locationChange); geolocation.on('locationChange', requestInfo, locationChange);
``` ```
## geolocation.off('locationChange')<sup>(deprecated) </sup> ## geolocation.off('locationChange')<sup>(deprecated)</sup>
off(type: 'locationChange', callback?: Callback&lt;Location&gt;): void off(type: 'locationChange', callback?: Callback&lt;Location&gt;): void
Unregisters the listener for location changes with the corresponding location request deleted. Unregisters the listener for location changes with the corresponding location request deleted.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -95,15 +94,15 @@ Unregisters the listener for location changes with the corresponding location re ...@@ -95,15 +94,15 @@ Unregisters the listener for location changes with the corresponding location re
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **locationChange** indicates a location change event.| | type | string | Yes| Event type. The value **locationChange** indicates a location change event.|
| callback | Callback&lt;[Location](#location)&gt; | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| | callback | Callback&lt;[Location](#locationdeprecated)&gt; | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; let requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => { let locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location)); console.log('locationChanger: data: ' + JSON.stringify(location));
}; };
geolocation.on('locationChange', requestInfo, locationChange); geolocation.on('locationChange', requestInfo, locationChange);
...@@ -111,13 +110,13 @@ Unregisters the listener for location changes with the corresponding location re ...@@ -111,13 +110,13 @@ Unregisters the listener for location changes with the corresponding location re
``` ```
## geolocation.on('locationServiceState')<sup>(deprecated) </sup> ## geolocation.on('locationServiceState')<sup>(deprecated)</sup>
on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;): void on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;): void
Registers a listener for location service status change events. Registers a listener for location service status change events.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationenabledchange). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -136,20 +135,20 @@ Registers a listener for location service status change events. ...@@ -136,20 +135,20 @@ Registers a listener for location service status change events.
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var locationServiceState = (state) => { let locationServiceState = (state) => {
console.log('locationServiceState: ' + JSON.stringify(state)); console.log('locationServiceState: ' + JSON.stringify(state));
} }
geolocation.on('locationServiceState', locationServiceState); geolocation.on('locationServiceState', locationServiceState);
``` ```
## geolocation.off('locationServiceState')<sup>(deprecated) </sup> ## geolocation.off('locationServiceState')<sup>(deprecated)</sup>
off(type: 'locationServiceState', callback?: Callback&lt;boolean&gt;): void; off(type: 'locationServiceState', callback?: Callback&lt;boolean&gt;): void;
Unregisters the listener for location service status change events. Unregisters the listener for location service status change events.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationenabledchange). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -168,7 +167,7 @@ Unregisters the listener for location service status change events. ...@@ -168,7 +167,7 @@ Unregisters the listener for location service status change events.
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var locationServiceState = (state) => { let locationServiceState = (state) => {
console.log('locationServiceState: state: ' + JSON.stringify(state)); console.log('locationServiceState: state: ' + JSON.stringify(state));
} }
geolocation.on('locationServiceState', locationServiceState); geolocation.on('locationServiceState', locationServiceState);
...@@ -176,13 +175,13 @@ Unregisters the listener for location service status change events. ...@@ -176,13 +175,13 @@ Unregisters the listener for location service status change events.
``` ```
## geolocation.on('cachedGnssLocationsReporting')<sup>(deprecated) </sup> ## geolocation.on('cachedGnssLocationsReporting')<sup>(deprecated)</sup>
on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;): void; on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;): void;
Registers a listener for cached GNSS location reports. Registers a listener for cached GNSS location reports.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroncachedgnsslocationschange).
...@@ -195,29 +194,29 @@ Registers a listener for cached GNSS location reports. ...@@ -195,29 +194,29 @@ Registers a listener for cached GNSS location reports.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.|
| request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.| | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequestdeprecated) | Yes| Request for reporting cached GNSS location.|
| callback | Callback&lt;Array&lt;[Location](#location)&gt;&gt; | Yes| Callback used to return cached GNSS locations.| | callback | Callback&lt;Array&lt;[Location](#locationdeprecated)&gt;&gt; | Yes| Callback used to return cached GNSS locations.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var cachedLocationsCb = (locations) => { let cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations));
} }
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);
``` ```
## geolocation.off('cachedGnssLocationsReporting')<sup>(deprecated) </sup> ## geolocation.off('cachedGnssLocationsReporting')<sup>(deprecated)</sup>
off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;): void; off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;): void;
Unregisters the listener for cached GNSS location reports. Unregisters the listener for cached GNSS location reports.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroffcachedgnsslocationschange).
...@@ -230,29 +229,29 @@ Unregisters the listener for cached GNSS location reports. ...@@ -230,29 +229,29 @@ Unregisters the listener for cached GNSS location reports.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.|
| callback | Callback&lt;Array&lt;[Location](#location)&gt;&gt; | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| | callback | Callback&lt;Array&lt;[Location](#locationdeprecated)&gt;&gt; | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var cachedLocationsCb = (locations) => { let cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations));
} }
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; let requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);
geolocation.off('cachedGnssLocationsReporting'); geolocation.off('cachedGnssLocationsReporting');
``` ```
## geolocation.on('gnssStatusChange')<sup>(deprecated) </sup> ## geolocation.on('gnssStatusChange')<sup>(deprecated)</sup>
on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;): void; on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;): void;
Registers a listener for GNSS satellite status change events. Registers a listener for GNSS satellite status change events.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageronsatellitestatuschange).
...@@ -265,27 +264,27 @@ Registers a listener for GNSS satellite status change events. ...@@ -265,27 +264,27 @@ Registers a listener for GNSS satellite status change events.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.|
| callback | Callback&lt;[SatelliteStatusInfo](#satellitestatusinfo)&gt; | Yes| Callback used to return GNSS satellite status changes.| | callback | Callback&lt;[SatelliteStatusInfo](#satellitestatusinfodeprecated)&gt; | Yes| Callback used to return GNSS satellite status changes.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var gnssStatusCb = (satelliteStatusInfo) => { let gnssStatusCb = (satelliteStatusInfo) => {
console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo));
} }
geolocation.on('gnssStatusChange', gnssStatusCb); geolocation.on('gnssStatusChange', gnssStatusCb);
``` ```
## geolocation.off('gnssStatusChange')<sup>(deprecated) </sup> ## geolocation.off('gnssStatusChange')<sup>(deprecated)</sup>
off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;): void; off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;): void;
Unregisters the listener for GNSS satellite status change events. Unregisters the listener for GNSS satellite status change events.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffsatellitestatuschange).
...@@ -298,13 +297,13 @@ Unregisters the listener for GNSS satellite status change events. ...@@ -298,13 +297,13 @@ Unregisters the listener for GNSS satellite status change events.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.|
| callback | Callback&lt;[SatelliteStatusInfo](#satellitestatusinfo)&gt; | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| | callback | Callback&lt;[SatelliteStatusInfo](#satellitestatusinfodeprecated)&gt; | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var gnssStatusCb = (satelliteStatusInfo) => { let gnssStatusCb = (satelliteStatusInfo) => {
console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo));
} }
geolocation.on('gnssStatusChange', gnssStatusCb); geolocation.on('gnssStatusChange', gnssStatusCb);
...@@ -312,13 +311,13 @@ Unregisters the listener for GNSS satellite status change events. ...@@ -312,13 +311,13 @@ Unregisters the listener for GNSS satellite status change events.
``` ```
## geolocation.on('nmeaMessageChange')<sup>(deprecated) </sup> ## geolocation.on('nmeaMessageChange')<sup>(deprecated)</sup>
on(type: 'nmeaMessageChange', callback: Callback&lt;string&gt;): void; on(type: 'nmeaMessageChange', callback: Callback&lt;string&gt;): void;
Registers a listener for GNSS NMEA message change events. Registers a listener for GNSS NMEA message change events.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageronnmeamessage).
...@@ -338,20 +337,20 @@ Registers a listener for GNSS NMEA message change events. ...@@ -338,20 +337,20 @@ Registers a listener for GNSS NMEA message change events.
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var nmeaCb = (str) => { let nmeaCb = (str) => {
console.log('nmeaMessageChange: ' + JSON.stringify(str)); console.log('nmeaMessageChange: ' + JSON.stringify(str));
} }
geolocation.on('nmeaMessageChange', nmeaCb ); geolocation.on('nmeaMessageChange', nmeaCb );
``` ```
## geolocation.off('nmeaMessageChange')<sup>(deprecated) </sup> ## geolocation.off('nmeaMessageChange')<sup>(deprecated)</sup>
off(type: 'nmeaMessageChange', callback?: Callback&lt;string&gt;): void; off(type: 'nmeaMessageChange', callback?: Callback&lt;string&gt;): void;
Unregisters the listener for GNSS NMEA message change events. Unregisters the listener for GNSS NMEA message change events.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageroffnmeamessage).
...@@ -371,7 +370,7 @@ Unregisters the listener for GNSS NMEA message change events. ...@@ -371,7 +370,7 @@ Unregisters the listener for GNSS NMEA message change events.
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var nmeaCb = (str) => { let nmeaCb = (str) => {
console.log('nmeaMessageChange: ' + JSON.stringify(str)); console.log('nmeaMessageChange: ' + JSON.stringify(str));
} }
geolocation.on('nmeaMessageChange', nmeaCb); geolocation.on('nmeaMessageChange', nmeaCb);
...@@ -379,13 +378,13 @@ Unregisters the listener for GNSS NMEA message change events. ...@@ -379,13 +378,13 @@ Unregisters the listener for GNSS NMEA message change events.
``` ```
## geolocation.on('fenceStatusChange')<sup>(deprecated) </sup> ## geolocation.on('fenceStatusChange')<sup>(deprecated)</sup>
on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void;
Registers a listener for status change events of the specified geofence. Registers a listener for status change events of the specified geofence.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanagerongnssfencestatuschange).
...@@ -398,22 +397,21 @@ Registers a listener for status change events of the specified geofence. ...@@ -398,22 +397,21 @@ Registers a listener for status change events of the specified geofence.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.|
| request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | request | [GeofenceRequest](#geofencerequestdeprecated) | Yes| Geofencing request.|
| want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to return geofence (entrance or exit) events.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility", abilityName: "EntryAbility",
action: "action1", action: "action1"
} }
], ],
operationType: wantAgent.OperationType.START_ABILITY, operationType: wantAgent.OperationType.START_ABILITY,
...@@ -422,19 +420,19 @@ Registers a listener for status change events of the specified geofence. ...@@ -422,19 +420,19 @@ Registers a listener for status change events of the specified geofence.
}; };
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); geolocation.on('fenceStatusChange', requestInfo, wantAgentObj);
}); });
``` ```
## geolocation.off('fenceStatusChange')<sup>(deprecated) </sup> ## geolocation.off('fenceStatusChange')<sup>(deprecated)</sup>
off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void;
Unregisters the listener for status change events of the specified geofence. Unregisters the listener for status change events of the specified geofence.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffgnssfencestatuschange).
...@@ -447,20 +445,20 @@ Unregisters the listener for status change events of the specified geofence. ...@@ -447,20 +445,20 @@ Unregisters the listener for status change events of the specified geofence.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.|
| request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | request | [GeofenceRequest](#geofencerequestdeprecated) | Yes| Geofencing request.|
| want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| | want | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes| **WantAgent** used to return geofence (entrance or exit) events.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility", abilityName: "EntryAbility",
action: "action1", action: "action1",
} }
], ],
...@@ -470,20 +468,20 @@ Unregisters the listener for status change events of the specified geofence. ...@@ -470,20 +468,20 @@ Unregisters the listener for status change events of the specified geofence.
}; };
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); geolocation.on('fenceStatusChange', requestInfo, wantAgentObj);
geolocation.off('fenceStatusChange', requestInfo, wantAgentObj); geolocation.off('fenceStatusChange', requestInfo, wantAgentObj);
}); });
``` ```
## geolocation.getCurrentLocation<sup>(deprecated) </sup> ## geolocation.getCurrentLocation<sup>(deprecated)</sup>
getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;): void getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;): void
Obtains the current location. This API uses an asynchronous callback to return the result. Obtains the current location. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -494,15 +492,15 @@ Obtains the current location. This API uses an asynchronous callback to return t ...@@ -494,15 +492,15 @@ Obtains the current location. This API uses an asynchronous callback to return t
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.| | request | [CurrentLocationRequest](#currentlocationrequestdeprecated) | Yes| Location request.|
| callback | AsyncCallback&lt;[Location](#location)&gt; | Yes| Callback used to return the current location.| | callback | AsyncCallback&lt;[Location](#locationdeprecated)&gt; | Yes| Callback used to return the current location.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
var locationChange = (err, location) => { let locationChange = (err, location) => {
if (err) { if (err) {
console.log('locationChanger: err=' + JSON.stringify(err)); console.log('locationChanger: err=' + JSON.stringify(err));
} }
...@@ -514,14 +512,14 @@ Obtains the current location. This API uses an asynchronous callback to return t ...@@ -514,14 +512,14 @@ Obtains the current location. This API uses an asynchronous callback to return t
``` ```
## geolocation.getCurrentLocation<sup>(deprecated) </sup> ## geolocation.getCurrentLocation<sup>(deprecated)</sup>
getCurrentLocation(callback: AsyncCallback&lt;Location&gt;): void getCurrentLocation(callback: AsyncCallback&lt;Location&gt;): void
Obtains the current location. This API uses an asynchronous callback to return the result. Obtains the current location. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -532,13 +530,13 @@ Obtains the current location. This API uses an asynchronous callback to return t ...@@ -532,13 +530,13 @@ Obtains the current location. This API uses an asynchronous callback to return t
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[Location](#location)&gt; | Yes| Callback used to return the current location.| | callback | AsyncCallback&lt;[Location](#locationdeprecated)&gt; | Yes| Callback used to return the current location.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var locationChange = (err, location) => { let locationChange = (err, location) => {
if (err) { if (err) {
console.log('locationChanger: err=' + JSON.stringify(err)); console.log('locationChanger: err=' + JSON.stringify(err));
} }
...@@ -550,13 +548,13 @@ Obtains the current location. This API uses an asynchronous callback to return t ...@@ -550,13 +548,13 @@ Obtains the current location. This API uses an asynchronous callback to return t
``` ```
## geolocation.getCurrentLocation<sup>(deprecated) </sup> ## geolocation.getCurrentLocation<sup>(deprecated)</sup>
getCurrentLocation(request?: CurrentLocationRequest): Promise&lt;Location&gt; getCurrentLocation(request?: CurrentLocationRequest): Promise&lt;Location&gt;
Obtains the current location. This API uses a promise to return the result. Obtains the current location. This API uses a promise to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation-2). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -567,33 +565,33 @@ Obtains the current location. This API uses a promise to return the result. ...@@ -567,33 +565,33 @@ Obtains the current location. This API uses a promise to return the result.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| | request | [CurrentLocationRequest](#currentlocationrequestdeprecated) | No| Location request.|
**Return value** **Return value**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;[Location](#location)&gt; |[Location](#location)|NA| Promise used to return the current location.| | Promise&lt;[Location](#locationdeprecated)&gt; |[Location](#locationdeprecated)|NA| Promise used to return the current location.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
geolocation.getCurrentLocation(requestInfo).then((result) => { geolocation.getCurrentLocation(requestInfo).then((result) => {
console.log('current location: ' + JSON.stringify(result)); console.log('current location: ' + JSON.stringify(result));
}); });
``` ```
## geolocation.getLastLocation<sup>(deprecated) </sup> ## geolocation.getLastLocation<sup>(deprecated)</sup>
getLastLocation(callback: AsyncCallback&lt;Location&gt;): void getLastLocation(callback: AsyncCallback&lt;Location&gt;): void
Obtains the previous location. This API uses an asynchronous callback to return the result. Obtains the previous location. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -604,7 +602,7 @@ Obtains the previous location. This API uses an asynchronous callback to return ...@@ -604,7 +602,7 @@ Obtains the previous location. This API uses an asynchronous callback to return
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[Location](#location)&gt; | Yes| Callback used to return the previous location.| | callback | AsyncCallback&lt;[Location](#locationdeprecated)&gt; | Yes| Callback used to return the previous location.|
**Example** **Example**
...@@ -622,13 +620,13 @@ Obtains the previous location. This API uses an asynchronous callback to return ...@@ -622,13 +620,13 @@ Obtains the previous location. This API uses an asynchronous callback to return
``` ```
## geolocation.getLastLocation<sup>(deprecated) </sup> ## geolocation.getLastLocation<sup>(deprecated)</sup>
getLastLocation(): Promise&lt;Location&gt; getLastLocation(): Promise&lt;Location&gt;
Obtains the previous location. This API uses a promise to return the result. Obtains the previous location. This API uses a promise to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -639,7 +637,7 @@ Obtains the previous location. This API uses a promise to return the result. ...@@ -639,7 +637,7 @@ Obtains the previous location. This API uses a promise to return the result.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;[Location](#location)&gt; | [Location](#location)|NA|Promise used to return the previous location.| | Promise&lt;[Location](#locationdeprecated)&gt; | [Location](#locationdeprecated)|NA|Promise used to return the previous location.|
**Example** **Example**
...@@ -652,13 +650,13 @@ Obtains the previous location. This API uses a promise to return the result. ...@@ -652,13 +650,13 @@ Obtains the previous location. This API uses a promise to return the result.
``` ```
## geolocation.isLocationEnabled<sup>(deprecated) </sup> ## geolocation.isLocationEnabled<sup>(deprecated)</sup>
isLocationEnabled(callback: AsyncCallback&lt;boolean&gt;): void isLocationEnabled(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. Checks whether the location service is enabled. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -686,13 +684,13 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ...@@ -686,13 +684,13 @@ Checks whether the location service is enabled. This API uses an asynchronous ca
``` ```
## geolocation.isLocationEnabled<sup>(deprecated) </sup> ## geolocation.isLocationEnabled<sup>(deprecated)</sup>
isLocationEnabled(): Promise&lt;boolean&gt; isLocationEnabled(): Promise&lt;boolean&gt;
Checks whether the location service is enabled. This API uses a promise to return the result. Checks whether the location service is enabled. This API uses a promise to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -715,14 +713,14 @@ Checks whether the location service is enabled. This API uses a promise to retur ...@@ -715,14 +713,14 @@ Checks whether the location service is enabled. This API uses a promise to retur
``` ```
## geolocation.requestEnableLocation<sup>(deprecated) </sup> ## geolocation.requestEnableLocation<sup>(deprecated)</sup>
requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;): void requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;): void
Requests to enable the location service. This API uses an asynchronous callback to return the result. Requests to enable the location service. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation). > This API has been discarded since API version 9. It is recommended that a dialog box be displayed in the application to request the user to go to Settings to enable the location function and specify the scenarios in which the location information will be used in the dialog box.
**Required permissions**: ohos.permission.LOCATION **Required permissions**: ohos.permission.LOCATION
...@@ -749,14 +747,14 @@ Requests to enable the location service. This API uses an asynchronous callback ...@@ -749,14 +747,14 @@ Requests to enable the location service. This API uses an asynchronous callback
``` ```
## geolocation.requestEnableLocation<sup>(deprecated) </sup> ## geolocation.requestEnableLocation<sup>(deprecated)</sup>
requestEnableLocation(): Promise&lt;boolean&gt; requestEnableLocation(): Promise&lt;boolean&gt;
Requests to enable the location service. This API uses a promise to return the result. Requests to enable the location service. This API uses a promise to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation-1). > This API has been discarded since API version 9. It is recommended that a dialog box be displayed in the application to request the user to go to Settings to enable the location function and specify the scenarios in which the location information will be used in the dialog box.
**Required permissions**: ohos.permission.LOCATION **Required permissions**: ohos.permission.LOCATION
...@@ -778,13 +776,13 @@ Requests to enable the location service. This API uses a promise to return the r ...@@ -778,13 +776,13 @@ Requests to enable the location service. This API uses a promise to return the r
``` ```
## geolocation.isGeoServiceAvailable<sup>(deprecated) </sup> ## geolocation.isGeoServiceAvailable<sup>(deprecated)</sup>
isGeoServiceAvailable(callback: AsyncCallback&lt;boolean&gt;): void isGeoServiceAvailable(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -812,13 +810,13 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ...@@ -812,13 +810,13 @@ Checks whether the (reverse) geocoding service is available. This API uses an as
``` ```
## geolocation.isGeoServiceAvailable<sup>(deprecated) </sup> ## geolocation.isGeoServiceAvailable<sup>(deprecated)</sup>
isGeoServiceAvailable(): Promise&lt;boolean&gt; isGeoServiceAvailable(): Promise&lt;boolean&gt;
Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -841,13 +839,13 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ...@@ -841,13 +839,13 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro
``` ```
## geolocation.getAddressesFromLocation<sup>(deprecated) </sup> ## geolocation.getAddressesFromLocation<sup>(deprecated)</sup>
getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void
Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. Converts coordinates into geographic descriptions through reverse geocoding. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -858,14 +856,14 @@ Converts coordinates into geographic description through reverse geocoding. This ...@@ -858,14 +856,14 @@ Converts coordinates into geographic description through reverse geocoding. This
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| | request | [ReverseGeoCodeRequest](#reversegeocoderequestdeprecated) | Yes| Reverse geocoding request.|
| callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Yes| Callback used to return the reverse geocoding result.| | callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddressdeprecated)&gt;&gt; | Yes| Callback used to return the reverse geocoding result.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) { if (err) {
console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); console.log('getAddressesFromLocation: err=' + JSON.stringify(err));
...@@ -877,13 +875,13 @@ Converts coordinates into geographic description through reverse geocoding. This ...@@ -877,13 +875,13 @@ Converts coordinates into geographic description through reverse geocoding. This
``` ```
## geolocation.getAddressesFromLocation<sup>(deprecated) </sup> ## geolocation.getAddressesFromLocation<sup>(deprecated)</sup>
getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt;; getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt;;
Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. Converts coordinates into geographic descriptions through reverse geocoding. This API uses a promise to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation-1). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -894,32 +892,32 @@ Converts coordinates into geographic description through reverse geocoding. This ...@@ -894,32 +892,32 @@ Converts coordinates into geographic description through reverse geocoding. This
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| | request | [ReverseGeoCodeRequest](#reversegeocoderequestdeprecated) | Yes| Reverse geocoding request.|
**Return value** **Return value**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Array&lt;[GeoAddress](#geoaddress)&gt;|NA|Promise used to return the reverse geocoding result.| | Promise&lt;Array&lt;[GeoAddress](#geoaddressdeprecated)&gt;&gt; | Array&lt;[GeoAddress](#geoaddressdeprecated)&gt;|NA|Promise used to return the reverse geocoding result.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data)); console.log('getAddressesFromLocation: ' + JSON.stringify(data));
}); });
``` ```
## geolocation.getAddressesFromLocationName<sup>(deprecated) </sup> ## geolocation.getAddressesFromLocationName<sup>(deprecated)</sup>
getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void
Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. Converts geographic descriptions into coordinates through geocoding. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -930,14 +928,14 @@ Converts geographic description into coordinates through geocoding. This API use ...@@ -930,14 +928,14 @@ Converts geographic description into coordinates through geocoding. This API use
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| | request | [GeoCodeRequest](#geocoderequestdeprecated) | Yes| Geocoding request.|
| callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Yes| Callback used to return the geocoding result.| | callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddressdeprecated)&gt;&gt; | Yes| Callback used to return the geocoding result.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; let geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) { if (err) {
console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); console.log('getAddressesFromLocationName: err=' + JSON.stringify(err));
...@@ -949,13 +947,13 @@ Converts geographic description into coordinates through geocoding. This API use ...@@ -949,13 +947,13 @@ Converts geographic description into coordinates through geocoding. This API use
``` ```
## geolocation.getAddressesFromLocationName<sup>(deprecated) </sup> ## geolocation.getAddressesFromLocationName<sup>(deprecated)</sup>
getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt;
Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. Converts geographic descriptions into coordinates through geocoding. This API uses a promise to return the result.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname-1). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -966,32 +964,32 @@ Converts geographic description into coordinates through geocoding. This API use ...@@ -966,32 +964,32 @@ Converts geographic description into coordinates through geocoding. This API use
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| | request | [GeoCodeRequest](#geocoderequestdeprecated) | Yes| Geocoding request.|
**Return value** **Return value**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Array&lt;[GeoAddress](#geoaddress)&gt;|NA|Promise used to return the geocoding result.| | Promise&lt;Array&lt;[GeoAddress](#geoaddressdeprecated)&gt;&gt; | Array&lt;[GeoAddress](#geoaddressdeprecated)&gt;|NA|Promise used to return the geocoding result.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; let geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); console.log('getAddressesFromLocationName: ' + JSON.stringify(result));
}); });
``` ```
## geolocation.getCachedGnssLocationsSize<sup>(deprecated) </sup> ## geolocation.getCachedGnssLocationsSize<sup>(deprecated)</sup>
getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;): void; getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;): void;
Obtains the number of cached GNSS locations. Obtains the number of cached GNSS locations.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize).
...@@ -1020,13 +1018,13 @@ Obtains the number of cached GNSS locations. ...@@ -1020,13 +1018,13 @@ Obtains the number of cached GNSS locations.
``` ```
## geolocation.getCachedGnssLocationsSize<sup>(deprecated) </sup> ## geolocation.getCachedGnssLocationsSize<sup>(deprecated)</sup>
getCachedGnssLocationsSize(): Promise&lt;number&gt;; getCachedGnssLocationsSize(): Promise&lt;number&gt;;
Obtains the number of cached GNSS locations. Obtains the number of cached GNSS locations.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize-1).
...@@ -1050,13 +1048,13 @@ Obtains the number of cached GNSS locations. ...@@ -1050,13 +1048,13 @@ Obtains the number of cached GNSS locations.
``` ```
## geolocation.flushCachedGnssLocations<sup>(deprecated) </sup> ## geolocation.flushCachedGnssLocations<sup>(deprecated)</sup>
flushCachedGnssLocations(callback: AsyncCallback&lt;boolean&gt;): void; flushCachedGnssLocations(callback: AsyncCallback&lt;boolean&gt;): void;
Obtains all cached GNSS locations and clears the GNSS cache queue. Obtains all cached GNSS locations and clears the GNSS cache queue.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations).
...@@ -1085,13 +1083,13 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ...@@ -1085,13 +1083,13 @@ Obtains all cached GNSS locations and clears the GNSS cache queue.
``` ```
## geolocation.flushCachedGnssLocations<sup>(deprecated) </sup> ## geolocation.flushCachedGnssLocations<sup>(deprecated)</sup>
flushCachedGnssLocations(): Promise&lt;boolean&gt;; flushCachedGnssLocations(): Promise&lt;boolean&gt;;
Obtains all cached GNSS locations and clears the GNSS cache queue. Obtains all cached GNSS locations and clears the GNSS cache queue.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations-1).
...@@ -1115,13 +1113,13 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ...@@ -1115,13 +1113,13 @@ Obtains all cached GNSS locations and clears the GNSS cache queue.
``` ```
## geolocation.sendCommand<sup>(deprecated) </sup> ## geolocation.sendCommand<sup>(deprecated)</sup>
sendCommand(command: LocationCommand, callback: AsyncCallback&lt;boolean&gt;): void; sendCommand(command: LocationCommand, callback: AsyncCallback&lt;boolean&gt;): void;
Sends an extended command to the location subsystem. Sends an extended command to the location subsystem.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand).
...@@ -1133,14 +1131,14 @@ Sends an extended command to the location subsystem. ...@@ -1133,14 +1131,14 @@ Sends an extended command to the location subsystem.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| | command | [LocationCommand](#locationcommanddeprecated) | Yes| Extended command (string) to be sent.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the operation result.| | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the operation result.|
**Example** **Example**
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var requestInfo = {'scenario': 0x301, 'command': "command_1"}; let requestInfo = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo, (err, result) => { geolocation.sendCommand(requestInfo, (err, result) => {
if (err) { if (err) {
console.log('sendCommand: err=' + JSON.stringify(err)); console.log('sendCommand: err=' + JSON.stringify(err));
...@@ -1152,13 +1150,13 @@ Sends an extended command to the location subsystem. ...@@ -1152,13 +1150,13 @@ Sends an extended command to the location subsystem.
``` ```
## geolocation.sendCommand<sup>(deprecated) </sup> ## geolocation.sendCommand<sup>(deprecated)</sup>
sendCommand(command: LocationCommand): Promise&lt;boolean&gt;; sendCommand(command: LocationCommand): Promise&lt;boolean&gt;;
Sends an extended command to the location subsystem. Sends an extended command to the location subsystem.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand).
...@@ -1170,7 +1168,7 @@ Sends an extended command to the location subsystem. ...@@ -1170,7 +1168,7 @@ Sends an extended command to the location subsystem.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| | command | [LocationCommand](#locationcommanddeprecated) | Yes| Extended command (string) to be sent.|
**Return value** **Return value**
...@@ -1182,80 +1180,18 @@ Sends an extended command to the location subsystem. ...@@ -1182,80 +1180,18 @@ Sends an extended command to the location subsystem.
```ts ```ts
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
var requestInfo = {'scenario': 0x301, 'command': "command_1"}; let requestInfo = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo).then((result) => { geolocation.sendCommand(requestInfo).then((result) => {
console.log('promise, sendCommand: ' + JSON.stringify(result)); console.log('promise, sendCommand: ' + JSON.stringify(result));
}); });
``` ```
## LocationRequestPriority<sup>(deprecated) </sup> ## ReverseGeoCodeRequest<sup>(deprecated)</sup>
Sets the priority of the location request.
> **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
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x200 | Priority unspecified.|
| ACCURACY | 0x201 | Location accuracy.|
| LOW_POWER | 0x202 | Power efficiency.|
| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.|
## LocationRequestScenario<sup>(deprecated) </sup>
Sets the scenario of the location request.
> **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
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x300 | Scenario unspecified.|
| NAVIGATION | 0x301 | Navigation.|
| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.|
| CAR_HAILING | 0x303 | Ride hailing.|
| DAILY_LIFE_SERVICE | 0x304 | Daily life services.|
| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. 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.|
## GeoLocationErrorCode<sup>(deprecated) </sup>
Enumerates error codes of the location service.
> **NOTE**
> This API is deprecated since API version 9.
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| INPUT_PARAMS_ERROR<sup>7+</sup> | 101 | Incorrect input parameters.|
| REVERSE_GEOCODE_ERROR<sup>7+</sup> | 102 | Failed to call the reverse geocoding API.|
| GEOCODE_ERROR<sup>7+</sup> | 103 | Failed to call the geocoding API.|
| LOCATOR_ERROR<sup>7+</sup> | 104 | Failed to obtain the location.|
| LOCATION_SWITCH_ERROR<sup>7+</sup> | 105 | Failed to change the location service switch.|
| LAST_KNOWN_LOCATION_ERROR<sup>7+</sup> | 106 | Failed to obtain the previous location.|
| LOCATION_REQUEST_TIMEOUT_ERROR<sup>7+</sup> | 107 | Failed to obtain the location within the specified time.|
## ReverseGeoCodeRequest<sup>(deprecated) </sup>
Defines a reverse geocoding request. Defines a reverse geocoding request.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.ReverseGeoCodeRequest](js-apis-geoLocationManager.md#reversegeocoderequest). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -1265,16 +1201,16 @@ Defines a reverse geocoding request. ...@@ -1265,16 +1201,16 @@ Defines a reverse geocoding request.
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| | locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from **-90** to **90**.|
| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| | longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from **-180** to **180**.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| | maxItems | number | Yes| Yes| Maximum number of location records to be returned. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
## GeoCodeRequest<sup>(deprecated) </sup> ## GeoCodeRequest<sup>(deprecated)</sup>
Defines a geocoding request. Defines a geocoding request.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoCodeRequest](js-apis-geoLocationManager.md#geocoderequest). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -1285,18 +1221,18 @@ Defines a geocoding request. ...@@ -1285,18 +1221,18 @@ Defines a geocoding request.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| | locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.| | description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| | maxItems | number | Yes| Yes| Maximum number of location records to be returned. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.| | minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges. The value ranges from **-90** to **90**.|
| minLongitude | number | Yes| Yes| Minimum longitude.| | minLongitude | number | Yes| Yes| Minimum longitude. The value ranges from **-180** to **180**.|
| maxLatitude | number | Yes| Yes| Maximum latitude.| | maxLatitude | number | Yes| Yes| Maximum latitude. The value ranges from **-90** to **90**.|
| maxLongitude | number | Yes| Yes| Maximum longitude.| | maxLongitude | number | Yes| Yes| Maximum longitude. The value ranges from **-180** to **180**.|
## GeoAddress<sup>(deprecated) </sup> ## GeoAddress<sup>(deprecated)</sup>
Defines a geographic location. Defines a geographic location.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoAddress](js-apis-geoLocationManager.md#geoaddress). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -1305,8 +1241,8 @@ Defines a geographic location. ...@@ -1305,8 +1241,8 @@ Defines a geographic location.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from **-90** to **90**.|
| longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| | longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from **-180** to **180**.|
| locale<sup>7+</sup> | string | Yes| No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| | locale<sup>7+</sup> | string | Yes| No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| placeName<sup>7+</sup> | string | Yes| No| Landmark of the location.| | placeName<sup>7+</sup> | string | Yes| No| Landmark of the location.|
| countryCode<sup>7+</sup> | string | Yes| No| Country code.| | countryCode<sup>7+</sup> | string | Yes| No| Country code.|
...@@ -1322,14 +1258,14 @@ Defines a geographic location. ...@@ -1322,14 +1258,14 @@ Defines a geographic location.
| phoneNumber<sup>7+</sup> | string | Yes| No| Phone number.| | phoneNumber<sup>7+</sup> | string | Yes| No| Phone number.|
| addressUrl<sup>7+</sup> | string | Yes| No| Website URL.| | addressUrl<sup>7+</sup> | string | Yes| No| Website URL.|
| descriptions<sup>7+</sup> | Array&lt;string&gt; | Yes| No| Additional descriptions.| | descriptions<sup>7+</sup> | Array&lt;string&gt; | Yes| No| Additional descriptions.|
| descriptionsSize<sup>7+</sup> | number | Yes| No| Total number of additional descriptions.| | descriptionsSize<sup>7+</sup> | number | Yes| No| Total number of additional descriptions. The value must be greater than or equal to **0**. A value smaller than **10** is recommended.|
## LocationRequest<sup>(deprecated) </sup> ## LocationRequest<sup>(deprecated)</sup>
Defines a location request. Defines a location request.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequest](js-apis-geoLocationManager.md#locationrequest). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -1338,18 +1274,18 @@ Defines a location request. ...@@ -1338,18 +1274,18 @@ Defines a location request.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| | priority | [LocationRequestPriority](#locationrequestprioritydeprecated) | Yes| Yes| Priority of the location request. For details about the value range, see [LocationRequestPriority](#locationrequestprioritydeprecated).|
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| | scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | Yes| Yes| Scenario of the location request. For details about the value range, see [LocationRequestScenario](#locationrequestscenariodeprecated).|
| timeInterval | number | Yes| Yes| Time interval at which location information is reported.| | timeInterval | number | Yes| Yes| Time interval at which location information is reported, in seconds. The value must be greater than **0**.|
| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.| | distanceInterval | number | Yes| Yes| Distance interval at which location information is reported. The value must be greater than **0**, in meters.|
| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| | maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The value must be greater than **0**.|
## CurrentLocationRequest<sup>(deprecated) </sup> ## CurrentLocationRequest<sup>(deprecated)</sup>
Defines the current location request. Defines the current location request.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#currentlocationrequest). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -1358,17 +1294,17 @@ Defines the current location request. ...@@ -1358,17 +1294,17 @@ Defines the current location request.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| | priority | [LocationRequestPriority](#locationrequestprioritydeprecated) | Yes| Yes| Priority of the location request. For details about the value range, see [LocationRequestPriority](#locationrequestprioritydeprecated).|
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| | scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | Yes| Yes| Scenario of the location request. For details about the value range, see [LocationRequestScenario](#locationrequestscenariodeprecated).|
| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| | maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The value must be greater than **0**.|
| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.| | timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**. The value must be greater than or equal to **1000**.|
## SatelliteStatusInfo<sup>(deprecated) </sup> ## SatelliteStatusInfo<sup>(deprecated)</sup>
Defines the satellite status information. Defines the satellite status information.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.SatelliteStatusInfo](js-apis-geoLocationManager.md#satellitestatusinfo).
...@@ -1378,19 +1314,19 @@ Defines the satellite status information. ...@@ -1378,19 +1314,19 @@ Defines the satellite status information.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| satellitesNumber | number | Yes| No| Number of satellites.| | satellitesNumber | number | Yes| No| Number of satellites. The value must be greater than or equal to **0**.|
| satelliteIds | Array&lt;number&gt; | Yes| No| Array of satellite IDs.| | satelliteIds | Array&lt;number&gt; | Yes| No| Array of satellite IDs. The value must be greater than or equal to **0**.|
| carrierToNoiseDensitys | Array&lt;number&gt; | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.| | carrierToNoiseDensitys | Array&lt;number&gt; | Yes| No| Carrier-to-noise density ratio, that is, **cn0**. The value must be greater than **0**.|
| altitudes | Array&lt;number&gt; | Yes| No| Altitude information.| | altitudes | Array&lt;number&gt; | Yes| No| Satellite altitude angle information. The value ranges from **-90** to **90**, in degrees.|
| azimuths | Array&lt;number&gt; | Yes| No| Azimuth information.| | azimuths | Array&lt;number&gt; | Yes| No| Azimuth information. The value ranges from **0** to **360**, in degrees.|
| carrierFrequencies | Array&lt;number&gt; | Yes| No| Carrier frequency.| | carrierFrequencies | Array&lt;number&gt; | Yes| No| Carrier frequency. The value must be greater than or equal to **0**, in Hz.|
## CachedGnssLocationsRequest<sup>(deprecated) </sup> ## CachedGnssLocationsRequest<sup>(deprecated)</sup>
Represents a request for reporting cached GNSS locations. Represents a request for reporting cached GNSS locations.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.CachedGnssLocationsRequest](js-apis-geoLocationManager.md#cachedgnsslocationsrequest).
...@@ -1400,15 +1336,15 @@ Represents a request for reporting cached GNSS locations. ...@@ -1400,15 +1336,15 @@ Represents a request for reporting cached GNSS locations.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.| | reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds. The value must be greater than **0**.|
| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.<br>**false**: discards the cached GNSS locations when the cache queue is full.| | wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.<br>**false**: discards the cached GNSS locations when the cache queue is full.|
## Geofence<sup>(deprecated) </sup> ## Geofence<sup>(deprecated)</sup>
Defines a GNSS geofence. Currently, only circular geofences are supported. Defines a GNSS geofence. Currently, only circular geofences are supported.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.Geofence](js-apis-geoLocationManager.md#geofence).
...@@ -1418,17 +1354,17 @@ Defines a GNSS geofence. Currently, only circular geofences are supported. ...@@ -1418,17 +1354,17 @@ Defines a GNSS geofence. Currently, only circular geofences are supported.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| latitude | number | Yes| Yes | Latitude information.| | latitude | number | Yes| Yes|Latitude information. The value ranges from **-90** to **90**.|
| longitude | number | Yes| Yes | Longitude information.| | longitude | number | Yes|Yes| Longitude information. The value ranges from **-180** to **180**.|
| radius | number | Yes| Yes | Radius of a circular geofence.| | radius | number | Yes|Yes| Radius of a circular geofence. The value must be greater than **0**, in meters.|
| expiration | number | Yes| Yes | Expiration period of a geofence, in milliseconds.| | expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds. The value must be greater than **0**.|
## GeofenceRequest<sup>(deprecated) </sup> ## GeofenceRequest<sup>(deprecated)</sup>
Represents a GNSS geofencing request. Represents a GNSS geofencing request.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeofenceRequest](js-apis-geoLocationManager.md#geofencerequest).
...@@ -1438,35 +1374,16 @@ Represents a GNSS geofencing request. ...@@ -1438,35 +1374,16 @@ Represents a GNSS geofencing request.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes | Priority of the location information.| | priority | [LocationRequestPriority](#locationrequestprioritydeprecated) | Yes| Yes | Priority of the location information.|
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| | scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | Yes| Yes | Location scenario.|
| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.| | geofence | [Geofence](#geofencedeprecated)| Yes| Yes | Geofence information.|
## LocationPrivacyType<sup>(deprecated) </sup>
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).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| OTHERS | 0 | Other scenarios.|
| STARTUP | 1 | Privacy statement displayed in the startup wizard.|
| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.|
## LocationCommand<sup>(deprecated)</sup>
## LocationCommand<sup>(deprecated) </sup>
Defines an extended command. Defines an extended command.
> **NOTE** > **NOTE**<br>
> This API is supported since API version 8. > 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). > This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationCommand](js-apis-geoLocationManager.md#locationcommand).
...@@ -1476,15 +1393,15 @@ Defines an extended command. ...@@ -1476,15 +1393,15 @@ Defines an extended command.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| | scenario | [LocationRequestScenario](#locationrequestscenariodeprecated) | Yes| Yes | Location scenario.|
| command | string | Yes| Yes | Extended command, in the string format.| | command | string | Yes| Yes | Extended command, in the string format.|
## Location<sup>(deprecated) </sup> ## Location<sup>(deprecated)</sup>
Defines a location. Defines a location.
> **NOTE** > **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Location](js-apis-geoLocationManager.md#location). > 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 **Required permissions**: ohos.permission.LOCATION
...@@ -1493,13 +1410,94 @@ Defines a location. ...@@ -1493,13 +1410,94 @@ Defines a location.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from **-90** to **90**.|
| longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| | longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from **-180** to **180**.|
| altitude<sup>7+</sup> | number | Yes| No| Location altitude, in meters.| | altitude<sup>7+</sup> | number | Yes| No| Location altitude, in meters.|
| accuracy<sup>7+</sup> | number | Yes| No| Location accuracy, in meters.| | accuracy<sup>7+</sup> | number | Yes| No| Location accuracy, in meters.|
| speed<sup>7+</sup> | number | Yes| No| Speed, in m/s.| | speed<sup>7+</sup> | number | Yes| No| Speed, in m/s.|
| timeStamp<sup>7+</sup> | number | Yes| No| Location timestamp in the UTC format.| | timeStamp<sup>7+</sup> | number | Yes| No| Location timestamp in the UTC format.|
| direction<sup>7+</sup> | number | Yes| No| Direction information.| | direction<sup>7+</sup> | number | Yes| No| Direction information. The value ranges from **0** to **360**, in degrees.|
| timeSinceBoot<sup>7+</sup> | number | Yes| No| Location timestamp since boot.| | timeSinceBoot<sup>7+</sup> | number | Yes| No| Location timestamp since boot.|
| additions<sup>7+</sup> | Array&lt;string&gt; | Yes| No| Additional description.| | additions<sup>7+</sup> | Array&lt;string&gt; | Yes| No| Additional description.|
| additionSize<sup>7+</sup> | number | Yes| No| Number of additional descriptions.| | additionSize<sup>7+</sup> | number | Yes| No| Number of additional descriptions. The value must be greater than or equal to **0**.|
## LocationPrivacyType<sup>(deprecated)</sup>
Defines the privacy statement type.
> **NOTE**<br>
> 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).
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| OTHERS | 0 | Other scenarios. Reserved field.|
| STARTUP | 1 | Privacy statement displayed in the startup wizard. |
| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.|
## LocationRequestPriority<sup>(deprecated)</sup>
Sets the priority of the location request.
> **NOTE**<br>
> 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
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x200 | Priority unspecified.<br>If this option is used, [LocationRequestPriority](#locationrequestprioritydeprecated) is invalid.|
| ACCURACY | 0x201 | Location accuracy preferred.<br>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.|
| LOW_POWER | 0x202 | Power efficiency preferred.<br>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.|
| FIRST_FIX | 0x203 | Fast location preferred. Use this option if you want to obtain a location as fast as possible.<br>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. It can lead to significant hardware resource consumption and power consumption.|
## LocationRequestScenario<sup>(deprecated)</sup>
Sets the scenario of the location request.
> **NOTE**<br>
> 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
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| UNSET | 0x300 | Scenario unspecified.<br>If this option is used, [LocationRequestScenario](#locationrequestscenariodeprecated) is invalid.|
| NAVIGATION | 0x301 | Navigation scenario.<br>This option is applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking.<br>In this scenario, GNSS positioning is used to provide location services to ensure the optimal location accuracy of the system.<br>The location result is reported at a minimum interval of 1 second by default.|
| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking scenario.<br>This option is 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.<br>The location result is reported at a minimum interval of 1 second by default.|
| CAR_HAILING | 0x303 | Ride hailing scenario.<br>This option is applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>The location result is reported at a minimum interval of 1 second by default.|
| DAILY_LIFE_SERVICE | 0x304 | Daily life service scenario.<br>This option is 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.<br>The location result is reported at a minimum interval of 1 second by default.|
| NO_POWER | 0x305 | Power efficiency scenario.<br>This option is applicable when your application does not proactively start the location service. 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.|
## GeoLocationErrorCode<sup>(deprecated)</sup>
Enumerates error codes of the location service.
> **NOTE**<br>
> This API is deprecated since API version 9.
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Location.Location.Core
| Name| Value| Description|
| -------- | -------- | -------- |
| INPUT_PARAMS_ERROR<sup>7+</sup> | 101 | Incorrect input parameters.|
| REVERSE_GEOCODE_ERROR<sup>7+</sup> | 102 | Failed to call the reverse geocoding API.|
| GEOCODE_ERROR<sup>7+</sup> | 103 | Failed to call the geocoding API.|
| LOCATOR_ERROR<sup>7+</sup> | 104 | Failed to obtain the location.|
| LOCATION_SWITCH_ERROR<sup>7+</sup> | 105 | Failed to change the location service switch.|
| LAST_KNOWN_LOCATION_ERROR<sup>7+</sup> | 106 | Failed to obtain the previous location.|
| LOCATION_REQUEST_TIMEOUT_ERROR<sup>7+</sup> | 107 | Failed to obtain the location within the specified time.|
...@@ -47,11 +47,11 @@ Adds one or more rules. HiChecker detects unexpected operations or gives feedbac ...@@ -47,11 +47,11 @@ Adds one or more rules. HiChecker detects unexpected operations or gives feedbac
```js ```js
try { try {
// Add a rule. // Add a rule.
hichecker.addCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);} hichecker.addCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);
// Add multiple rules. // Add multiple rules.
hichecker.addCheckRule( // hichecker.addCheckRule(
hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); // hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH);
catch (err) { } catch (err) {
console.error(`code: ${err.code}, message: ${err.message}`); console.error(`code: ${err.code}, message: ${err.message}`);
} }
``` ```
...@@ -77,9 +77,9 @@ try { ...@@ -77,9 +77,9 @@ try {
// Remove a rule. // Remove a rule.
hichecker.removeCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); hichecker.removeCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);
// Remove multiple rules. // Remove multiple rules.
hichecker.removeCheckRule( // hichecker.removeCheckRule(
hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); // hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH);
catch (err) { } catch (err) {
console.error(`code: ${err.code}, message: ${err.message}`); console.error(`code: ${err.code}, message: ${err.message}`);
} }
``` ```
...@@ -114,7 +114,7 @@ try { ...@@ -114,7 +114,7 @@ try {
// Check whether the added rule exists in the collection of added rules. // Check whether the added rule exists in the collection of added rules.
hichecker.containsCheckRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true; hichecker.containsCheckRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true;
hichecker.containsCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); // return false; hichecker.containsCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); // return false;
catch (err) { } catch (err) {
console.error(`code: ${err.code}, message: ${err.message}`); console.error(`code: ${err.code}, message: ${err.message}`);
} }
``` ```
......
...@@ -297,7 +297,7 @@ import hidebug from '@ohos.hidebug' ...@@ -297,7 +297,7 @@ import hidebug from '@ohos.hidebug'
try { try {
hidebug.startJsCpuProfiling("cpu_profiling"); hidebug.startJsCpuProfiling("cpu_profiling");
... // ...
hidebug.stopJsCpuProfiling(); hidebug.stopJsCpuProfiling();
} catch (error) { } catch (error) {
console.info(error.code) console.info(error.code)
...@@ -326,7 +326,7 @@ import hidebug from '@ohos.hidebug' ...@@ -326,7 +326,7 @@ import hidebug from '@ohos.hidebug'
try { try {
hidebug.startJsCpuProfiling("cpu_profiling"); hidebug.startJsCpuProfiling("cpu_profiling");
... // ...
hidebug.stopJsCpuProfiling(); hidebug.stopJsCpuProfiling();
} catch (error) { } catch (error) {
console.info(error.code) console.info(error.code)
......
...@@ -581,6 +581,8 @@ httpResponseCache.delete().then(() => { ...@@ -581,6 +581,8 @@ httpResponseCache.delete().then(() => {
| 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. | | 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. | | 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. |
For details about the error codes, see [libcurl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
## HttpDataType<sup>9+</sup> ## HttpDataType<sup>9+</sup>
Enumerates HTTP data types. Enumerates HTTP data types.
......
# @ohos.i18n (Internationalization) # @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 **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 [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** > **NOTE**
...@@ -53,7 +53,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -53,7 +53,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China" let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China"
} catch(error) { } catch(error) {
console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -92,7 +92,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -92,7 +92,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese
} catch(error) { } catch(error) {
console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -100,7 +100,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -100,7 +100,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLanguages(): Array&lt;string&gt; static getSystemLanguages(): Array&lt;string&gt;
Obtains the list of system languages. Obtains the list of system languages. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -123,7 +123,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -123,7 +123,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ] let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ]
} catch(error) { } catch(error) {
console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -131,7 +131,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -131,7 +131,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemCountries(language: string): Array&lt;string&gt; static getSystemCountries(language: string): Array&lt;string&gt;
Obtains the list of countries and regions supported for the specified language. Obtains the list of countries and regions supported for the specified language. For details about countries or regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -160,7 +160,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -160,7 +160,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total
} catch(error) { } catch(error) {
console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -198,7 +198,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -198,7 +198,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let res = I18n.System.isSuggested('zh', 'CN'); // res = true let res = I18n.System.isSuggested('zh', 'CN'); // res = true
} catch(error) { } catch(error) {
console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -206,7 +206,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -206,7 +206,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLanguage(): string static getSystemLanguage(): string
Obtains the system language. Obtains the system language. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -229,7 +229,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -229,7 +229,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language. let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language.
} catch(error) { } catch(error) {
console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -264,7 +264,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -264,7 +264,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
I18n.System.setSystemLanguage('zh'); // Set the current system language to zh. I18n.System.setSystemLanguage('zh'); // Set the current system language to zh.
} catch(error) { } catch(error) {
console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -272,7 +272,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -272,7 +272,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemRegion(): string static getSystemRegion(): string
Obtains the system region. Obtains the system region. For details about system regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -295,7 +295,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -295,7 +295,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region. let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region.
} catch(error) { } catch(error) {
console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -330,7 +330,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -330,7 +330,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
I18n.System.setSystemRegion('CN'); // Set the current system region to CN. I18n.System.setSystemRegion('CN'); // Set the current system region to CN.
} catch(error) { } catch(error) {
console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -338,7 +338,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -338,7 +338,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLocale(): string static getSystemLocale(): string
Obtains the system locale. Obtains the system locale. For details about system locales, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -361,7 +361,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -361,7 +361,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale. let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale.
} catch(error) { } catch(error) {
console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -396,7 +396,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -396,7 +396,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN. I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN.
} catch(error) { } catch(error) {
console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -427,7 +427,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -427,7 +427,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled. let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled.
} catch(error) { } catch(error) {
console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -463,7 +463,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -463,7 +463,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
I18n.System.set24HourClock(true); I18n.System.set24HourClock(true);
} catch(error) { } catch(error) {
console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -502,7 +502,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -502,7 +502,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list. I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list.
} catch(error) { } catch(error) {
console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -539,7 +539,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -539,7 +539,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
I18n.System.removePreferredLanguage(index); I18n.System.removePreferredLanguage(index);
} catch(error) { } catch(error) {
console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -570,7 +570,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -570,7 +570,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list. let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list.
} catch(error) { } catch(error) {
console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -601,7 +601,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -601,7 +601,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list. let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list.
} catch(error) { } catch(error) {
console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -632,7 +632,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -632,7 +632,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application. let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application.
} catch(error) { } catch(error) {
console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -640,7 +640,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -640,7 +640,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static setUsingLocalDigit(flag: boolean): void static setUsingLocalDigit(flag: boolean): void
Sets whether to enable the local digit switch. Specifies whether to enable use of local digits.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -667,7 +667,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -667,7 +667,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
} catch(error) { } catch(error) {
console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -675,7 +675,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -675,7 +675,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getUsingLocalDigit(): boolean static getUsingLocalDigit(): boolean
Checks whether the local digit switch is turned on. Checks whether use of local digits is enabled.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -698,7 +698,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod ...@@ -698,7 +698,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try { try {
let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled. let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled.
} catch(error) { } catch(error) {
console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
} }
``` ```
...@@ -1025,7 +1025,7 @@ Checks whether the specified date in this **Calendar** object is a weekend. ...@@ -1025,7 +1025,7 @@ Checks whether the specified date in this **Calendar** object is a weekend.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ---- | ---- | ---------------------------------------- | | ---- | ---- | ---- | ---------------------------------------- |
| date | Date | No | Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.| | date | Date | No | Specified date in this **Calendar** object. If the **date** parameter is not specified, the system checks whether the current date is a weekend.|
**Return value** **Return value**
......
# @ohos.intl (Internationalization) # @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 interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities.
> **NOTE** > **NOTE**
...@@ -48,9 +48,9 @@ Creates a **Locale** object. ...@@ -48,9 +48,9 @@ Creates a **Locale** object.
**Example** **Example**
```js ```js
// The default constructor uses the current system locale to create a Locale object. // The default constructor uses the current system locale to create a Locale object.
let locale = new Intl.Locale() let locale = new Intl.Locale();
// Return the current system locale. // Return the current system locale.
let localeID = locale.toString() let localeID = locale.toString();
``` ```
...@@ -72,8 +72,8 @@ Creates a **Locale** object. ...@@ -72,8 +72,8 @@ Creates a **Locale** object.
**Example** **Example**
```js ```js
// Create a Locale object named zh-CN. // Create a Locale object named zh-CN.
let locale = new Intl.Locale("zh-CN") let locale = new Intl.Locale("zh-CN");
let localeID = locale.toString() // localeID = "zh-CN" let localeID = locale.toString(); // localeID = "zh-CN"
``` ```
...@@ -429,7 +429,7 @@ Obtains the options of the **NumberFormat** object. ...@@ -429,7 +429,7 @@ Obtains the options of the **NumberFormat** object.
// Obtain the options of the NumberFormat object. // Obtain the options of the NumberFormat object.
let options = numfmt.resolvedOptions(); let options = numfmt.resolvedOptions();
let style = options.style; // style = decimal let style = options.style; // style = decimal
let notation = options.notation // notation = scientific let notation = options.notation; // notation = scientific
``` ```
...@@ -552,7 +552,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -552,7 +552,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
// Obtain the options of the Collator object. // Obtain the options of the Collator object.
let options = collator.resolvedOptions(); let options = collator.resolvedOptions();
let usage = options.usage; // usage = "sort" let usage = options.usage; // usage = "sort"
let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true let ignorePunctuation = options.ignorePunctuation; // ignorePunctuation = true
``` ```
...@@ -631,7 +631,7 @@ Obtains a string that represents the singular-plural type of the specified numbe ...@@ -631,7 +631,7 @@ Obtains a string that represents the singular-plural type of the specified numbe
| Type | Description | | Type | Description |
| ------ | ---------------------------------------- | | ------ | ---------------------------------------- |
| string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| | string | Singular-plural type. The value can be any of the following: **zero**, **one**, **two**, **few**, **many**, **others**.|
**Example** **Example**
```js ```js
......
...@@ -104,7 +104,7 @@ radio.getNetworkState((err, data) =>{ ...@@ -104,7 +104,7 @@ radio.getNetworkState((err, data) =>{
getNetworkState\(slotId: number, callback: AsyncCallback<NetworkState\>\): void getNetworkState\(slotId: number, callback: AsyncCallback<NetworkState\>\): void
Obtains the network status of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Obtains the network status. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -131,7 +131,7 @@ radio.getNetworkState(slotId, (err, data) => { ...@@ -131,7 +131,7 @@ radio.getNetworkState(slotId, (err, data) => {
getNetworkState\(slotId?: number\): Promise<NetworkState\> getNetworkState\(slotId?: number\): Promise<NetworkState\>
Obtains the network status of the SIM card in the specified slot. This API uses a promise to return the result. Obtains the network status. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -290,7 +290,7 @@ Obtains the ID of the slot in which the primary card is located. This API uses a ...@@ -290,7 +290,7 @@ Obtains the ID of the slot in which the primary card is located. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<number\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<number\> | Yes | Callback invoked to return the result.|
**Example** **Example**
...@@ -384,12 +384,16 @@ promise.then(data => { ...@@ -384,12 +384,16 @@ promise.then(data => {
}); });
``` ```
## radio.isNrSupported<sup>7+</sup> ## radio.isNrSupported<sup>(deprecated)</sup>
isNrSupported\(\): boolean isNrSupported\(\): boolean
Checks whether the current device supports 5G \(NR\). Checks whether the current device supports 5G \(NR\).
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isNRSupported](#radioisnrsupported9) instead.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
**Return value** **Return value**
...@@ -405,12 +409,15 @@ let result = radio.isNrSupported(); ...@@ -405,12 +409,15 @@ let result = radio.isNrSupported();
console.log("Result: "+ result); console.log("Result: "+ result);
``` ```
## radio.isNrSupported<sup>(deprecated)</sup>
## radio.isNrSupported<sup>8+</sup>
isNrSupported\(slotId: number\): boolean isNrSupported\(slotId: number\): boolean
Checks whether the current device supports 5G \(NR\) for the SIM card in the specified slot. Checks whether the current device supports 5G \(NR\).
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isNRSupported](#radioisnrsupported9-1) instead.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
...@@ -435,6 +442,57 @@ console.log("Result: "+ result); ...@@ -435,6 +442,57 @@ console.log("Result: "+ result);
``` ```
## radio.isNRSupported<sup>9+</sup>
isNRSupported\(\): boolean
Checks whether the current device supports 5G \(NR\).
**System capability**: SystemCapability.Telephony.CoreService
**Return value**
| Type | Description |
| ------- | -------------------------------- |
| boolean | - **true**: The current device supports 5G \(NR\).<br>- **false**: The current device does not support 5G \(NR\).|
**Example**
```js
let result = radio.isNRSupported();
console.log("Result: "+ result);
```
## radio.isNRSupported<sup>9+</sup>
isNRSupported\(slotId: number\): boolean
Checks whether the current device supports 5G \(NR\).
**System capability**: SystemCapability.Telephony.CoreService
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------------------- |
| slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
**Return value**
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| boolean | - **true**: The current device supports 5G \(NR\).<br>- **false**: The current device does not support 5G \(NR\).|
**Example**
```js
let slotId = 0;
let result = radio.isNRSupported(slotId);
console.log("Result: "+ result);
```
## radio.isRadioOn<sup>7+</sup> ## radio.isRadioOn<sup>7+</sup>
isRadioOn\(callback: AsyncCallback<boolean\>\): void isRadioOn\(callback: AsyncCallback<boolean\>\): void
...@@ -675,7 +733,7 @@ radio.getIMEI((err, data) => { ...@@ -675,7 +733,7 @@ radio.getIMEI((err, data) => {
getIMEI(slotId: number, callback: AsyncCallback<string\>): void getIMEI(slotId: number, callback: AsyncCallback<string\>): void
Obtains the IMEI of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Obtains the IMEI of the SIM card in the specified card slot. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -704,7 +762,7 @@ radio.getIMEI(slotId, (err, data) => { ...@@ -704,7 +762,7 @@ radio.getIMEI(slotId, (err, data) => {
getIMEI(slotId?: number): Promise<string\> getIMEI(slotId?: number): Promise<string\>
Obtains the IMEI of the SIM card in a card slot. This API uses a promise to return the result. Obtains the IMEI of the SIM card in the specified card slot. This API uses a promise to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -767,7 +825,7 @@ radio.getMEID((err, data) => { ...@@ -767,7 +825,7 @@ radio.getMEID((err, data) => {
getMEID(slotId: number, callback: AsyncCallback<string\>): void getMEID(slotId: number, callback: AsyncCallback<string\>): void
Obtains the MEID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Obtains the MEID of the SIM card in the specified card slot. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -796,7 +854,7 @@ radio.getMEID(slotId, (err, data) => { ...@@ -796,7 +854,7 @@ radio.getMEID(slotId, (err, data) => {
getMEID(slotId?: number): Promise<string\> getMEID(slotId?: number): Promise<string\>
Obtains the MEID of the SIM card in the specified slot. This API uses a promise to return the result. Obtains the MEID of the SIM card in the specified card slot. This API uses a promise to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -859,7 +917,7 @@ radio.getUniqueDeviceId((err, data) => { ...@@ -859,7 +917,7 @@ radio.getUniqueDeviceId((err, data) => {
getUniqueDeviceId(slotId: number, callback: AsyncCallback<string\>): void getUniqueDeviceId(slotId: number, callback: AsyncCallback<string\>): void
Obtains the unique device ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Obtains the unique device ID of the SIM card in the specified card slot. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -888,7 +946,7 @@ radio.getUniqueDeviceId(slotId, (err, data) => { ...@@ -888,7 +946,7 @@ radio.getUniqueDeviceId(slotId, (err, data) => {
getUniqueDeviceId(slotId?: number): Promise<string\> getUniqueDeviceId(slotId?: number): Promise<string\>
Obtains the unique device ID of the SIM card in the specified slot. This API uses a promise to return the result. Obtains the unique device ID of the SIM card in the specified card slot. This API uses a promise to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -928,7 +986,7 @@ Sends a cell location update request. This API uses an asynchronous callback to ...@@ -928,7 +986,7 @@ Sends a cell location update request. This API uses an asynchronous callback to
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.LOCATION **Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
...@@ -954,7 +1012,7 @@ Sends a cell location update request for the SIM card in the specified slot. Thi ...@@ -954,7 +1012,7 @@ Sends a cell location update request for the SIM card in the specified slot. Thi
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.LOCATION **Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
...@@ -978,11 +1036,11 @@ radio.sendUpdateCellLocationRequest(slotId, (err, data) => { ...@@ -978,11 +1036,11 @@ radio.sendUpdateCellLocationRequest(slotId, (err, data) => {
sendUpdateCellLocationRequest\(slotId?: number): Promise<void\> sendUpdateCellLocationRequest\(slotId?: number): Promise<void\>
Sends a cell location update request for the SIM card in the specified slot.This API uses a promise to return the result. Sends a cell location update request for the SIM card in the specified slot. This API uses a promise to return the result.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.LOCATION **Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
...@@ -1714,7 +1772,7 @@ promise.then(data => { ...@@ -1714,7 +1772,7 @@ promise.then(data => {
on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback<ImsRegInfo\>): void on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback<ImsRegInfo\>): void
Enables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Enables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -1743,7 +1801,7 @@ radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { ...@@ -1743,7 +1801,7 @@ radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => {
off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback<ImsRegInfo\>): void off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback<ImsRegInfo\>): void
Disables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Disables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -1770,7 +1828,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { ...@@ -1770,7 +1828,7 @@ radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => {
## RadioTechnology ## RadioTechnology
Enumerates radio access technologies. Enumerates radio access technologies.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
...@@ -1797,10 +1855,10 @@ Defines the signal strength. ...@@ -1797,10 +1855,10 @@ Defines the signal strength.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ----------- | --------------------------- | ---- | ----------------- |
| signalType | [NetworkType](#networktype) | Yes| Signal strength type.| | signalType | [NetworkType](#networktype) | Yes | Signal strength type.|
| signalLevel | number | Yes| Signal strength level.| | signalLevel | number | Yes | Signal strength level.|
## NetworkType ## NetworkType
...@@ -1825,17 +1883,17 @@ Defines the network status. ...@@ -1825,17 +1883,17 @@ Defines the network status.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | -------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| longOperatorName | string | Yes | Long carrier name of the registered network.| | longOperatorName | string | Yes | Long carrier name of the registered network. |
| shortOperatorName | string | Yes | Short carrier name of the registered network.| | shortOperatorName | string | Yes | Short carrier name of the registered network. |
| plmnNumeric | string | Yes | PLMN code of the registered network.| | plmnNumeric | string | Yes | PLMN code of the registered network. |
| isRoaming | boolean | Yes | Whether the user is roaming.| | isRoaming | boolean | Yes | Whether the user is roaming. |
| regState | [RegState](#regstate) | Yes | Network registration status of the device.| | regState | [RegState](#regstate) | Yes | Network registration status of the device. |
| cfgTech<sup>8+</sup> | [RadioTechnology](#radiotechnology) | Yes | RAT of the device.| | cfgTech<sup>8+</sup> | [RadioTechnology](#radiotechnology) | Yes | RAT of the device. |
| nsaState | [NsaState](#nsastate) | Yes | NSA network registration status of the device.| | nsaState | [NsaState](#nsastate) | Yes | NSA network registration status of the device. |
| isCaActive | boolean | Yes | CA status.| | isCaActive | boolean | Yes | CA status. |
| isEmergency | boolean | Yes | Whether only emergency calls are allowed.| | isEmergency | boolean | Yes | Whether only emergency calls are allowed. |
## RegState ## RegState
...@@ -1848,7 +1906,7 @@ Defines the network status. ...@@ -1848,7 +1906,7 @@ Defines the network status.
| ----------------------------- | ---- | -------------------------- | | ----------------------------- | ---- | -------------------------- |
| REG_STATE_NO_SERVICE | 0 | The device cannot use any services, including data, SMS, and call services. | | REG_STATE_NO_SERVICE | 0 | The device cannot use any services, including data, SMS, and call services. |
| REG_STATE_IN_SERVICE | 1 | The device can use services properly, including data, SMS, and call services. | | REG_STATE_IN_SERVICE | 1 | The device can use services properly, including data, SMS, and call services. |
| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service. | | REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service.|
| REG_STATE_POWER_OFF | 3 | The device cannot communicate with the network because the cellular radio service is disabled or the modem is powered off. | | REG_STATE_POWER_OFF | 3 | The device cannot communicate with the network because the cellular radio service is disabled or the modem is powered off. |
...@@ -1922,7 +1980,7 @@ Enumerates preferred network modes. ...@@ -1922,7 +1980,7 @@ Enumerates preferred network modes.
| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_GSM | 38 | NR+LTE+TD-SCDMA+GSM network mode. | | PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_GSM | 38 | NR+LTE+TD-SCDMA+GSM network mode. |
| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA | 39 | NR+LTE+TD-SCDMA+WCDMA network mode. | | PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA | 39 | NR+LTE+TD-SCDMA+WCDMA network mode. |
| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM | 40 | NR+LTE+TD-SCDMA+WCDMA+GSM network mode. | | PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM | 40 | NR+LTE+TD-SCDMA+WCDMA+GSM network mode. |
| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 41 | NR+LTE+TD-SCDMA+WCDMA+GSM+EVDO+CDMA network mode. | | PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 41 | NR+LTE+TD-SCDMA+WCDMA+GSM network mode. |
| PREFERRED_NETWORK_MODE_MAX_VALUE | 99 | Maximum value of the preferred network mode. | | PREFERRED_NETWORK_MODE_MAX_VALUE | 99 | Maximum value of the preferred network mode. |
## CellInformation<sup>8+</sup> ## CellInformation<sup>8+</sup>
...@@ -1933,13 +1991,13 @@ Defines the cell information. ...@@ -1933,13 +1991,13 @@ Defines the cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ----------------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| networkType | [NetworkType](#networktype) | Yes | Network type of the cell. | | networkType | [NetworkType](#networktype) | Yes | Network type of the cell. |
| isCamped | boolean | Yes | Status of the cell. | | isCamped | boolean | Yes | Cell status. |
| timeStamp | number | Yes | Timestamp when cell information is obtained. | | timeStamp | number | Yes | Timestamp when cell information is obtained. |
| signalInformation | [SignalInformation](#signalinformation) | Yes | Signal information. | | signalInformation | [SignalInformation](#signalinformation) | Yes | Signal information. |
| data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | Yes | CDMA cell information \|GSM cell information \|LTE cell information \|NR cell information \|TD-SCDMA cell information| | data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | Yes | CDMA cell information\|GSM cell information\|LTE cell information\|NR cell information\|TD-SCDMA cell information|
## CdmaCellInformation<sup>8+</sup> ## CdmaCellInformation<sup>8+</sup>
...@@ -1949,8 +2007,8 @@ Defines the CDMA cell information. ...@@ -1949,8 +2007,8 @@ Defines the CDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | --------- | ------ | ---- | ------------ |
| baseId | number | Yes | Base station ID. | | baseId | number | Yes | Base station ID. |
| latitude | number | Yes | Longitude. | | latitude | number | Yes | Longitude. |
| longitude | number | Yes | Latitude. | | longitude | number | Yes | Latitude. |
...@@ -1965,8 +2023,8 @@ Defines the GSM cell information. ...@@ -1965,8 +2023,8 @@ Defines the GSM cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------ | ------ | ---- | -------------------- |
| lac | number | Yes | Location area code. | | lac | number | Yes | Location area code. |
| cellId | number | Yes | Cell ID. | | cellId | number | Yes | Cell ID. |
| arfcn | number | Yes | Absolute radio frequency channel number.| | arfcn | number | Yes | Absolute radio frequency channel number.|
...@@ -1976,14 +2034,14 @@ Defines the GSM cell information. ...@@ -1976,14 +2034,14 @@ Defines the GSM cell information.
## LteCellInformation<sup>8+</sup> ## LteCellInformation<sup>8+</sup>
Defines the LTE cell information. LTE cell information.
**System API**: This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------------- | ------- | ---- | ----------------------- |
| cgi | number | Yes | Cell global identification. | | cgi | number | Yes | Cell global identification. |
| pci | number | Yes | Physical cell ID. | | pci | number | Yes | Physical cell ID. |
| tac | number | Yes | Tracking area code. | | tac | number | Yes | Tracking area code. |
...@@ -1991,18 +2049,18 @@ Defines the LTE cell information. ...@@ -1991,18 +2049,18 @@ Defines the LTE cell information.
| bandwidth | number | Yes | Bandwidth. | | bandwidth | number | Yes | Bandwidth. |
| mcc | string | Yes | Mobile country code. | | mcc | string | Yes | Mobile country code. |
| mnc | string | Yes | Mobile network code. | | mnc | string | Yes | Mobile network code. |
| isSupportEndc | boolean | Yes | Support for New Radio_Dual Connectivity. | | isSupportEndc | boolean | Yes | Support for New Radio_Dual Connectivity.|
## NrCellInformation<sup>8+</sup> ## NrCellInformation<sup>8+</sup>
Defines the NR cell information. Defines the 5G NR cell information.
**System API**: This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------- | ------ | ---- | ---------------- |
| nrArfcn | number | Yes | 5G frequency number. | | nrArfcn | number | Yes | 5G frequency number. |
| pci | number | Yes | Physical cell ID. | | pci | number | Yes | Physical cell ID. |
| tac | number | Yes | Tracking area code. | | tac | number | Yes | Tracking area code. |
...@@ -2018,8 +2076,8 @@ Defines the TD-SCDMA cell information. ...@@ -2018,8 +2076,8 @@ Defines the TD-SCDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------ | ------ | ---- | ------------ |
| lac | number | Yes | Location area code.| | lac | number | Yes | Location area code.|
| cellId | number | Yes | Cell ID. | | cellId | number | Yes | Cell ID. |
| cpid | number | Yes | Cell parameter ID.| | cpid | number | Yes | Cell parameter ID.|
...@@ -2035,8 +2093,8 @@ Defines the WCDMA cell information. ...@@ -2035,8 +2093,8 @@ Defines the WCDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------ | ------ | ---- | ------------ |
| lac | number | Yes | Location area code.| | lac | number | Yes | Location area code.|
| cellId | number | Yes | Cell ID. | | cellId | number | Yes | Cell ID. |
| psc | number | Yes | Primary scrambling code. | | psc | number | Yes | Primary scrambling code. |
...@@ -2056,7 +2114,7 @@ Enumerates NR selection modes. ...@@ -2056,7 +2114,7 @@ Enumerates NR selection modes.
| -------------------- | ---- | ---------------------------------- | | -------------------- | ---- | ---------------------------------- |
| NR_OPTION_UNKNOWN | 0 | Unknown NR selection mode. | | NR_OPTION_UNKNOWN | 0 | Unknown NR selection mode. |
| NR_OPTION_NSA_ONLY | 1 | NR selection mode in 5G non-standalone networking. | | NR_OPTION_NSA_ONLY | 1 | NR selection mode in 5G non-standalone networking. |
| NR_OPTION_SA_ONLY | 2 | NR selection mode in 5G standalone networking. | | NR_OPTION_SA_ONLY | 2 | NR selection mode in 5G non-standalone networking. |
| NR_OPTION_NSA_AND_SA | 3 | NR selection mode in non-standalone and standalone networking.| | NR_OPTION_NSA_AND_SA | 3 | NR selection mode in non-standalone and standalone networking.|
## NetworkSearchResult ## NetworkSearchResult
...@@ -2067,8 +2125,8 @@ Defines the network search result. ...@@ -2067,8 +2125,8 @@ Defines the network search result.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ---------------------- | ------------------------------------------------- | ---- | -------------- |
| isNetworkSearchSuccess | boolean | Yes | Successful network search.| | isNetworkSearchSuccess | boolean | Yes | Successful network search.|
| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Yes | Network search result.| | networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Yes | Network search result.|
...@@ -2080,12 +2138,12 @@ Defines the network information. ...@@ -2080,12 +2138,12 @@ Defines the network information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | --------------- | --------------------------------------------------- | ---- | -------------- |
| operatorName | string | Yes | Carrier name.| | operatorName | string | Yes | Carrier name.|
| operatorNumeric | string | Yes | Carrier number. | | operatorNumeric | string | Yes | Carrier number. |
| state | [NetworkInformation](#networkinformationstate) | Yes | Network information status.| | state | [NetworkInformationState](#networkinformationstate) | Yes | Network information status.|
| radioTech | string | Yes | Radio technology. | | radioTech | string | Yes | Radio access technology. |
## NetworkInformationState ## NetworkInformationState
...@@ -2110,8 +2168,8 @@ Defines the network selection mode. ...@@ -2110,8 +2168,8 @@ Defines the network selection mode.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ------------------ | --------------------------------------------- | ---- | -------------------------------------- |
| slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2| | slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
| selectMode | [NetworkSelectionMode](#networkselectionmode) | Yes | Network selection mode. | | selectMode | [NetworkSelectionMode](#networkselectionmode) | Yes | Network selection mode. |
| networkInformation | [NetworkInformation](#networkinformation) | Yes | Network information. | | networkInformation | [NetworkInformation](#networkinformation) | Yes | Network information. |
...@@ -2153,8 +2211,8 @@ Defines the IMS registration information. ...@@ -2153,8 +2211,8 @@ Defines the IMS registration information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------- | --------- | ----------- | | ----------- | ---------------------------- | ---- | ------------- |
| imsRegState | [ImsRegState](#imsregstate9) | Yes | IMS registration state.| | imsRegState | [ImsRegState](#imsregstate9) | Yes | IMS registration state.|
| imsRegTech | [ImsRegTech](#imsregtech9) | Yes | IMS registration technology.| | imsRegTech | [ImsRegTech](#imsregtech9) | Yes | IMS registration technology.|
......
...@@ -15,8 +15,8 @@ import resourceManager from '@ohos.resourceManager'; ...@@ -15,8 +15,8 @@ import resourceManager from '@ohos.resourceManager';
## Instruction ## Instruction
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object.
For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md).
```ts ```ts
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
...@@ -60,6 +60,7 @@ Obtains the **ResourceManager** object of this application. This API uses an asy ...@@ -60,6 +60,7 @@ Obtains the **ResourceManager** object of this application. This API uses an asy
}); });
}); });
``` ```
> **NOTE**<br>In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
## resourceManager.getResourceManager ## resourceManager.getResourceManager
...@@ -116,6 +117,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom ...@@ -116,6 +117,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
console.log("error is " + error); console.log("error is " + error);
}); });
``` ```
> **NOTE**<br>In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
## resourceManager.getResourceManager ## resourceManager.getResourceManager
...@@ -1767,7 +1769,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ...@@ -1767,7 +1769,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaByName(resName: string, callback: AsyncCallback&lt;Uint8Array&gt;): void getMediaByName(resName: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager **System capability**: SystemCapability.Global.ResourceManager
......
# @system.geolocation (Geographic Location) # @system.geolocation (Geolocation)
The **geolocation** module provides only basic functions such as GNSS positioning and network positioning.
> **NOTE** > **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. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead.
## Modules to Import ## Modules to Import
``` ```
import geolocation from '@system.geolocation'; import geolocation from '@system.geolocation';
``` ```
...@@ -19,43 +19,46 @@ import geolocation from '@system.geolocation'; ...@@ -19,43 +19,46 @@ import geolocation from '@system.geolocation';
ohos.permission.LOCATION ohos.permission.LOCATION
## geolocation.getLocation ## geolocation.getLocation<sup>(deprecated)</sup>
getLocation(Object): void getLocation(Object): void
Obtains the geographic location. Obtains the geographic location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation).
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
| Parameter | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| timeout | number | No | Timeout&nbsp;duration,&nbsp;in&nbsp;milliseconds.&nbsp;The&nbsp;default&nbsp;value&nbsp;is&nbsp;**30000**.<br>The&nbsp;timeout&nbsp;duration&nbsp;is&nbsp;necessary&nbsp;in&nbsp;case&nbsp;the&nbsp;request&nbsp;to&nbsp;obtain&nbsp;the&nbsp;geographic&nbsp;location&nbsp;is&nbsp;rejected&nbsp;for&nbsp;the&nbsp;lack&nbsp;of&nbsp;the&nbsp;required&nbsp;permission,&nbsp;weak&nbsp;positioning&nbsp;signal,&nbsp;or&nbsp;incorrect&nbsp;location&nbsp;settings.&nbsp;After&nbsp;the&nbsp;timeout&nbsp;duration&nbsp;expires,&nbsp;the&nbsp;fail&nbsp;function&nbsp;will&nbsp;be&nbsp;called.<br>The&nbsp;value&nbsp;is&nbsp;a&nbsp;32-digit&nbsp;positive&nbsp;integer.&nbsp;If&nbsp;the&nbsp;value&nbsp;set&nbsp;is&nbsp;less&nbsp;than&nbsp;or&nbsp;equal&nbsp;to&nbsp;**0**,&nbsp;the&nbsp;default&nbsp;value&nbsp;will&nbsp;be&nbsp;used. | | timeout | number | No| Timeout duration, in ms. The default value is **30000**.<br>The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.<br>The value is a 32-digit positive integer. If the specified value is less than or equal to **0**, the default value will be used.|
| coordType | string | No | Coordinate&nbsp;system&nbsp;type.&nbsp;Available&nbsp;types&nbsp;can&nbsp;be&nbsp;obtained&nbsp;by&nbsp;**getSupportedCoordTypes**.&nbsp;The&nbsp;default&nbsp;type&nbsp;is&nbsp;**wgs84**. | | coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful. | | success | Function | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. | | fail | Function | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete | | complete | Function | No| Called when API call is complete.|
The following values will be returned when the operation is successful. **Return value of success()**
| Parameter | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| longitude | number | Longitude | | longitude | number | Longitude.|
| latitude | number | Latitude | | latitude | number | Latitude.|
| altitude | number | Altitude | | altitude | number | Altitude.|
| accuracy | number | Location&nbsp;accuracy | | accuracy | number | Location accuracy.|
| time | number | Time&nbsp;when&nbsp;the&nbsp;location&nbsp;is&nbsp;obtained | | time | number | Time when the location is obtained.|
One of the following error codes will be returned if the operation fails. **Return value of fail()**
| Error&nbsp;Code | Description | | Error Code| Description|
| -------- | -------- | | -------- | -------- |
| 601 | Failed&nbsp;to&nbsp;obtain&nbsp;the&nbsp;required&nbsp;permission&nbsp;because&nbsp;the&nbsp;user&nbsp;rejected&nbsp;the&nbsp;request. | | 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission&nbsp;not&nbsp;declared. | | 602 | Permission not declared.|
| 800 | Operation&nbsp;times&nbsp;out&nbsp;due&nbsp;to&nbsp;a&nbsp;poor&nbsp;network&nbsp;condition&nbsp;or&nbsp;unavailable&nbsp;GPS. | | 800 | Operation times out due to a poor network condition or GNSS unavailability.|
| 801 | System&nbsp;location&nbsp;disabled. | | 801 | System location disabled.|
| 802 | The&nbsp;method&nbsp;is&nbsp;called&nbsp;again&nbsp;while&nbsp;the&nbsp;previous&nbsp;execution&nbsp;result&nbsp;is&nbsp;not&nbsp;returned&nbsp;yet. | | 802 | API called again while the previous execution result is not returned yet.|
**Example** **Example**
...@@ -68,34 +71,37 @@ export default { ...@@ -68,34 +71,37 @@ export default {
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('fail to get location. code:' + code + ', data:' + data); console.log('fail to get location. code:' + code + ', data:' + data);
}, }
}); });
}, }
} }
``` ```
## geolocation.getLocationType ## geolocation.getLocationType<sup>(deprecated)</sup>
getLocationType(Object): void getLocationType(Object): void
Obtains the supported location types. Obtains the supported location types.
> **NOTE**
> This API is deprecated since API version 9. The location subsystem supports only two location types: GNSS positioning and network positioning. No APIs will be provided to query the supported location types.
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
| Parameter | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;successful. | | success | Function | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. | | fail | Function | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete | | complete | Function | No| Called when API call is complete.|
The following values will be returned when the operation is successful. **Return value of success()**
| Parameter | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| types | Array&lt;string&gt; | Available&nbsp;location&nbsp;types,&nbsp;['gps',&nbsp;'network'] | | types | Array&lt;string&gt; | Available location types, ['gps', 'network']|
**Example** **Example**
...@@ -115,39 +121,42 @@ export default { ...@@ -115,39 +121,42 @@ export default {
``` ```
## geolocation.subscribe ## geolocation.subscribe<sup>(deprecated)</sup>
subscribe(Object): void subscribe(Object): void
Listens to the geographical location. If this method is called multiple times, the last call takes effect. Listens to the geographic location. If this method is called multiple times, the last call takes effect.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange).
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
| Parameter | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| coordType | string | No | Coordinate&nbsp;system&nbsp;type.&nbsp;Available&nbsp;types&nbsp;can&nbsp;be&nbsp;obtained&nbsp;by&nbsp;**getSupportedCoordTypes**.&nbsp;The&nbsp;default&nbsp;type&nbsp;is&nbsp;**wgs84**. | | coordType | string | No| Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**.|
| success | Function | Yes | Called&nbsp;when&nbsp;the&nbsp;geographical&nbsp;location&nbsp;changes | | success | Function | Yes| Called when the geographic location changes.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;listening&nbsp;fails | | fail | Function | No| Called when API call has failed.|
The following values will be returned when the network type is obtained. **Return value of success()**
| Parameter | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| longitude | number | Longitude | | longitude | number | Longitude.|
| latitude | number | Latitude | | latitude | number | Latitude.|
| altitude | number | Altitude | | altitude | number | Altitude.|
| accuracy | number | Location&nbsp;accuracy | | accuracy | number | Location accuracy.|
| time | number | Time&nbsp;when&nbsp;the&nbsp;location&nbsp;is&nbsp;obtained | | time | number | Time when the location is obtained.|
One of the following error codes will be returned if the operation fails. **Return value of fail()**
| Error&nbsp;Code | Description | | Error Code| Description|
| -------- | -------- | | -------- | -------- |
| 601 | Failed&nbsp;to&nbsp;obtain&nbsp;the&nbsp;required&nbsp;permission&nbsp;because&nbsp;the&nbsp;user&nbsp;rejected&nbsp;the&nbsp;request. | | 601 | Failed to obtain the required permission because the user rejected the request.|
| 602 | Permission&nbsp;not&nbsp;declared. | | 602 | Permission not declared.|
| 801 | System&nbsp;location&nbsp;disabled. | | 801 | System location disabled.|
**Example** **Example**
...@@ -167,11 +176,14 @@ export default { ...@@ -167,11 +176,14 @@ export default {
``` ```
## geolocation.unsubscribe ## geolocation.unsubscribe<sup>(deprecated)</sup>
unsubscribe(): void unsubscribe(): void
Cancels listening to the geographical location. Cancels listening to the geographic location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange).
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
...@@ -181,24 +193,27 @@ Cancels listening to the geographical location. ...@@ -181,24 +193,27 @@ Cancels listening to the geographical location.
export default { export default {
unsubscribe() { unsubscribe() {
geolocation.unsubscribe(); geolocation.unsubscribe();
}, }
} }
``` ```
## geolocation.getSupportedCoordTypes ## geolocation.getSupportedCoordTypes<sup>(deprecated)</sup>
getSupportedCoordTypes(): Array&lt;string&gt; getSupportedCoordTypes(): Array&lt;string&gt;
Obtains coordinate system types supported by the device. Obtains coordinate system types supported by the device.
> **NOTE**
> This API is deprecated since API version 9. The location subsystem supports only the wgs84 coordinate system. No APIs will be provided to query the supported coordinate system types.
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Return Value** **Return value**
| Type | Non-Null | Description | | Type| Not empty| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| Array&lt;string&gt; | Yes | Coordinate&nbsp;system&nbsp;types,&nbsp;for&nbsp;example,&nbsp;**[wgs84,&nbsp;gcj02]**. | | Array&lt;string&gt; | Yes| Coordinate system types, for example, **[wgs84, gcj02]**.|
**Example** **Example**
......
...@@ -5,6 +5,7 @@ The **usb** module provides USB device management functions, including USB devic ...@@ -5,6 +5,7 @@ The **usb** module provides USB device management functions, including USB devic
> **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. > 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 provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md) instead.
## Modules to Import ## Modules to Import
......
...@@ -4,6 +4,7 @@ The **usb** module provides USB device management functions, including USB devic ...@@ -4,6 +4,7 @@ The **usb** module provides USB device management functions, including USB devic
> **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md) instead.
## Modules to Import ## Modules to Import
......
# @ohos.usbManager (USB Manager)
The **usbManager** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import usb from "@ohos.usbManager";
```
## usb.getDevices
getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt;
Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned.
**System capability**: SystemCapability.USB.USBManager
**Return value**
| Type | Description |
| ---------------------------------------------------- | ------- |
| Array&lt;Readonly&lt;[USBDevice](#usbdevice)&gt;&gt; | USB device list.|
**Example**
```js
let devicesList = usb.getDevices();
console.log(`devicesList = ${JSON.stringify(devicesList)}`);
// devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows:
[
{
name: "1-1",
serial: "",
manufacturerName: "",
productName: "",
version: "",
vendorId: 7531,
productId: 2,
clazz: 9,
subClass: 0,
protocol: 1,
devAddress: 1,
busNum: 1,
configs: [
{
id: 1,
attributes: 224,
isRemoteWakeup: true,
isSelfPowered: true,
maxPower: 0,
name: "1-1",
interfaces: [
{
id: 0,
protocol: 0,
clazz: 9,
subClass: 0,
alternateSetting: 0,
name: "1-1",
endpoints: [
{
address: 129,
attributes: 3,
interval: 12,
maxPacketSize: 4,
direction: 128,
number: 1,
type: 3,
interfaceId: 0,
},
],
},
],
},
],
},
]
```
## usb.connectDevice
connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;
Connects to the USB device based on the device information returned by **getDevices()**.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| device | [USBDevice](#usbdevice) | Yes| USB device information.|
**Return value**
| Type| Description|
| -------- | -------- |
| Readonly&lt;[USBDevicePipe](#usbdevicepipe)&gt; | USB device pipe for data transfer.|
**Error codes**
For details about the error codes, see [USB Error Codes](../errorcodes/errorcode-usb.md).
| ID| Error Message|
| -------- | -------- |
| 14400001 |Permission denied. Need call requestRight to get permission. |
**Example**
```js
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`);
```
## usb.hasRight
hasRight(deviceName: string): boolean
Checks whether the application has the permission to access the device.
Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise.|
**Example**
```js
let devicesName="1-1";
let bool = usb.hasRight(devicesName);
console.log(bool);
```
## usb.requestRight
requestRight(deviceName: string): Promise&lt;boolean&gt;
Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted; and the value **false** indicates the opposite.|
**Example**
```js
let devicesName="1-1";
usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${JSON.stringify(ret)}`);
});
```
## usb.removeRight
removeRight(deviceName: string): boolean
Removes the permission for the application to access a USB device.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite.|
**Example**
```js
let devicesName="1-1";
if (usb.removeRight(devicesName) {
console.log(`Succeed in removing right`);
}
```
## usb.addRight
addRight(bundleName: string, deviceName: string): boolean
Adds the permission for the application to access a USB device.
[requestRight](#usbrequestright) triggers a dialog box to request for user authorization, whereas **addRight** adds the access permission directly without displaying a dialog box.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
| bundleName | string | Yes| Bundle name of the application.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.|
**Example**
```js
let devicesName = "1-1";
let bundleName = "com.example.hello";
if (usb.addRight(bundleName, devicesName) {
console.log(`Succeed in adding right`);
}
```
## usb.claimInterface
claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number
Claims a USB interface.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and USB interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to claim.|
| force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise.|
**Example**
```js
let ret = usb.claimInterface(devicepipe, interfaces);
console.log(`claimInterface = ${ret}`);
```
## usb.releaseInterface
releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number
Releases a USB interface.
Before you do this, ensure that you have claimed the interface by calling [usb.claimInterface](#usbclaiminterface).
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB interface is successfully released; returns an error code otherwise.|
**Example**
```js
let ret = usb.releaseInterface(devicepipe, interfaces);
console.log(`releaseInterface = ${ret}`);
```
## usb.setConfiguration
setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number
Sets the device configuration.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device configuration, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| config | [USBConfiguration](#usbconfiguration) | Yes| USB configuration to set.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise.|
**Example**
```js
let ret = usb.setConfiguration(devicepipe, config);
console.log(`setConfiguration = ${ret}`);
```
## usb.setInterface
setInterface(pipe: USBDevicePipe, iface: USBInterface): number
Sets a USB interface.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------------------------------- | --- | ------------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes | Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes | USB interface to set. |
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB interface is successfully set; returns an error code otherwise.|
**Example**
```js
let ret = usb.setInterface(devicepipe, interfaces);
console.log(`setInterface = ${ret}`);
```
## usb.getRawDescriptor
getRawDescriptor(pipe: USBDevicePipe): Uint8Array
Obtains the raw USB descriptor.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
**Return value**
| Type| Description|
| -------- | -------- |
| Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.|
**Example**
```js
let ret = usb.getRawDescriptor(devicepipe);
```
## usb.getFileDescriptor
getFileDescriptor(pipe: USBDevicePipe): number
Obtains the file descriptor.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | Returns the file descriptor of the USB device if the operation is successful; returns **-1** otherwise.|
**Example**
```js
let ret = usb.getFileDescriptor(devicepipe);
```
## usb.controlTransfer
controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise&lt;number&gt;
Performs control transfer.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| controlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.|
**Example**
```js
usb.controlTransfer(devicepipe, USBControlParams).then((ret) => {
console.log(`controlTransfer = ${JSON.stringify(ret)}`);
})
```
## usb.bulkTransfer
bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise&lt;number&gt;
Performs bulk transfer.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| endpoint | [USBEndpoint](#usbendpoint) | Yes| USB endpoint, which is used to determine the USB port for data transfer.|
| buffer | Uint8Array | Yes| Buffer for writing or reading data.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.|
**Example**
```js
// Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission.
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${JSON.stringify(ret)}`);
});
```
## usb.closePipe
closePipe(pipe: USBDevicePipe): number
Closes a USB device pipe.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise.|
**Example**
```js
let ret = usb.closePipe(devicepipe);
console.log(`closePipe = ${ret}`);
```
## usb.usbFunctionsFromString
usbFunctionsFromString(funcs: string): number
Converts the USB function list in the string format to a numeric mask in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------- |
| funcs | string | Yes | Function list in string format.|
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | Function list in numeric mask format.|
**Example**
```js
let funcs = "acm";
let ret = usb.usbFunctionsFromString(funcs);
```
## usb.usbFunctionsToString
usbFunctionsToString(funcs: FunctionType): string
Converts the USB function list in the numeric mask format to a string in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ----------------- |
| funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.|
**Return value**
| Type | Description |
| ------ | ------------------------------ |
| string | Function list in string format.|
**Example**
```js
let funcs = ACM | ECM;
let ret = usb.usbFunctionsToString(funcs);
```
## usb.setCurrentFunctions
setCurrentFunctions(funcs: FunctionType): Promise\<void\>
Sets the current USB function list in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ----------------- |
| funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.|
**Return value**
| Type | Description |
| --------------- | ------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```js
let funcs = HDC;
usb.setCurrentFunctions(funcs).then(() => {
console.info('usb setCurrentFunctions successfully.');
}).catch(err => {
console.error('usb setCurrentFunctions failed: ' + err.code + ' message: ' + err.message);
});
```
## usb.getCurrentFunctions
getCurrentFunctions(): FunctionType
Obtains the numeric mask combination for the USB function list in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Return value**
| Type | Description |
| ------------------------------ | --------------------------------- |
| [FunctionType](#functiontype) | Numeric mask combination for the USB function list.|
**Example**
```js
let ret = usb.getCurrentFunctions();
```
## usb.getPorts
getPorts(): Array\<USBPort\>
Obtains the list of all physical USB ports.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Return value**
| Type | Description |
| ----------------------------- | --------------------- |
| [Array\<USBPort\>](#usbport) | List of physical USB ports.|
**Example**
```js
let ret = usb.getPorts();
```
## usb.getSupportedModes
getSupportedModes(portId: number): PortModeType
Obtains the mask combination for the supported mode list of a given USB port.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------- |
| portId | number | Yes | Port number.|
**Return value**
| Type | Description |
| ------------------------------ | -------------------------- |
| [PortModeType](#portmodetype) | Mask combination for the supported mode list.|
**Example**
```js
let ret = usb.getSupportedModes(0);
```
## usb.setPortRoles
setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\<void\>
Sets the role types supported by a specified port, which can be **powerRole** (for charging) and **dataRole** (for data transfer).
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | -------------------------------- | ---- | ---------------- |
| portId | number | Yes | Port number. |
| powerRole | [PowerRoleType](#powerroletype) | Yes | Role for charging. |
| dataRole | [DataRoleType](#dataroletype) | Yes | Role for data transfer.|
**Return value**
| Type | Description |
| --------------- | ------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```js
let portId = 1;
usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
console.info('usb setPortRoles successfully.');
}).catch(err => {
console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
});
```
## USBEndpoint
Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface).
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Mandatory |Description |
| ------------- | ------------------------------------------- | ------------- |------------- |
| address | number | Yes|Endpoint address. |
| attributes | number | Yes|Endpoint attributes. |
| interval | number | Yes|Endpoint interval. |
| maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. |
| number | number | Yes|Endpoint number. |
| type | number | Yes|Endpoint type. |
| interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.|
## USBInterface
Represents a USB interface. One [USBConfiguration](#usbconfiguration) object can contain multiple **USBInterface** instances, each providing a specific function.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Mandatory |Description |
| ---------------- | ---------------------------------------- | ------------- |--------------------- |
| id | number | Yes|Unique ID of the USB interface. |
| protocol | number | Yes|Interface protocol. |
| clazz | number | Yes|Device type. |
| subClass | number | Yes|Device subclass. |
| alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes|Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface. |
## USBConfiguration
Represents the USB configuration. One [USBDevice](#usbdevice) can contain multiple **USBConfig** instances.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Mandatory |Description |
| -------------- | ------------------------------------------------ | --------------- |--------------- |
| id | number | Yes|Unique ID of the USB configuration. |
| attributes | number | Yes|Configuration attributes. |
| maxPower | number | Yes|Maximum power consumption, in mA. |
| name | string | Yes|Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes|Support for remote wakeup.|
| isSelfPowered | boolean | Yes| Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes. |
## USBDevice
Represents the USB device information.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Mandatory |Description |
| ---------------- | ------------------------------------ | ---------- |---------- |
| busNum | number | Yes|Bus address. |
| devAddress | number | Yes|Device address. |
| serial | string | Yes|Sequence number. |
| name | string | Yes|Device name. |
| manufacturerName | string | Yes| Device manufacturer. |
| productName | string | Yes|Product name. |
| version | string | Yes|Version number. |
| vendorId | number | Yes|Vendor ID. |
| productId | number | Yes|Product ID. |
| clazz | number | Yes|Device class. |
| subClass | number | Yes|Device subclass. |
| protocol | number | Yes|Device protocol code. |
| configs | Array&lt;[USBConfiguration](#usbconfiguration)&gt; | Yes|Device configuration descriptor information.|
## USBDevicePipe
Represents a USB device pipe, which is used to determine a USB device.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Mandatory |Description |
| ---------- | ------ | ----- |----- |
| busNum | number |Yes| Bus address.|
| devAddress | number |Yes| Device address.|
## USBControlParams
Represents control transfer parameters.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Mandatory |Description |
| ------- | ----------------------------------------------- | ---------------- |---------------- |
| request | number | Yes |Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. |
| value | number | Yes |Request parameter value. |
| index | number | Yes |Index of the request parameter value.|
| data | Uint8Array | Yes |Buffer for writing or reading data. |
## USBPort
Represents a USB port.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Mandatory |Description |
| -------------- | ------------------------------- | ------------------- |------------------------ |
| id | number | Yes |Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes |USB port role. |
## USBPortStatus
Enumerates USB port roles.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Type| Mandatory |Description |
| ---------------- | -------- | ---------------- |---------------------- |
| currentMode | number | Yes|Current USB mode. |
| currentPowerRole | number | Yes |Current power role. |
| currentDataRole | number | Yes |Current data role.|
## USBRequestTargetType
Enumerates request target types.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ---------------------------- | ---- | ------ |
| USB_REQUEST_TARGET_DEVICE | 0 | Device.|
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.|
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint.|
| USB_REQUEST_TARGET_OTHER | 3 | Other.|
## USBControlRequestType
Enumerates control request types.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------------------------- | ---- | ------ |
| USB_REQUEST_TYPE_STANDARD | 0 | Standard.|
| USB_REQUEST_TYPE_CLASS | 1 | Class. |
| USB_REQUEST_TYPE_VENDOR | 2 | Vendor.|
## USBRequestDirection
Enumerates request directions.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| --------------------------- | ---- | ------------------------ |
| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.|
| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.|
## FunctionType
Enumerates USB device function types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------------ | ---- | ---------- |
| NONE | 0 | No function.|
| ACM | 1 | ACM function. |
| ECM | 2 | ECM function. |
| HDC | 4 | HDC function. |
| MTP | 8 | Not supported currently.|
| PTP | 16 | Not supported currently.|
| RNDIS | 32 | Not supported currently.|
| MIDI | 64 | Not supported currently.|
| AUDIO_SOURCE | 128 | Not supported currently.|
| NCM | 256 | Not supported currently.|
## PortModeType
Enumerates USB port mode types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| --------- | ---- | ---------------------------------------------------- |
| NONE | 0 | None |
| UFP | 1 | Upstream facing port, which functions as the sink of power supply. |
| DFP | 2 | Downstream facing port, which functions as the source of power supply. |
| DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.|
| NUM_MODES | 4 | Not supported currently. |
## PowerRoleType
Enumerates power role types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------ | ---- | ---------- |
| NONE | 0 | None |
| SOURCE | 1 | External power supply.|
| SINK | 2 | Internal power supply.|
## DataRoleType
Enumerates data role types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------ | ---- | ------------ |
| NONE | 0 | None |
| HOST | 1 | USB host.|
| DEVICE | 2 | USB device.|
...@@ -94,39 +94,6 @@ Declare the events for service widgets in the **actions** field in the JSON file ...@@ -94,39 +94,6 @@ Declare the events for service widgets in the **actions** field in the JSON file
} }
``` ```
You can also implement redirection to the target application using a **want**, which contains the **abilityName**, **bundleName**, and **parameters** fields.
| Selector | Type | Default Value | Description |
| ------ | ------ | -------- | ---------------------------------------- |
| action | string | "router" | Event type.<br>- **"router"**: redirection event.<br>- **"message"**: message event.|
| want | [Want](../apis/js-apis-app-ability-want.md) | - | Information about the target application. For details, see the **want** format. |
```json
{
"data": {
"mainAbility": "xxx.xxx.xxx"
},
"actions": {
"routerEventName1": {
"action": "router",
"want": {
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility"
}
},
"routerEventName2": {
"action": "router",
"want": {
"action": "xxx.intent.action.DIAL",
"uri": "tel:12345678"
}
}
}
}
```
In API version 8, the [featureAbility.getWant](../apis/js-apis-ability-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters.
- Message event properties - Message event properties
......
# HiSysEvent Logging Configuration<a name="EN-US_TOPIC_0000001080478132"></a> # HiSysEvent Logging Configuration
## Overview<a name="section315316685115"></a>
If HiSysEvent logging is required for a component, you need to define a YAML file and [configure the YAML file path](#section123181432175135) in the **bundle.json** file. During compilation, the OpenHarmony compilation framework will use the Python compilation script to parse and verify all the YAML files configured in the **bundle.json** file. On completion, the compilation framework will summarize the configuration information in the YAML files and convert the information into a JSON file named **hisysevent.def**. After that, the compilation framework will put the JSON file to a specified path as the basis for the system to determine whether to log system events. ## Overview
### Basic Concepts<a name="section123181432175143"></a>
### Function Introduction
If HiSysEvent logging is required for a component, you need to define a YAML file and [configure the YAML file path](#configuring-the-yaml-file-path) in the **bundle.json** file. During compilation, the OpenHarmony compilation framework will use the Python compilation script to parse and verify all the YAML files configured in the **bundle.json** file. On completion, the compilation framework will summarize the configuration information in the YAML files and convert the information into a JSON file named **hisysevent.def**. After that, the compilation framework will put the JSON file to a specified path as the basis for the system to determine whether to log system events.
### Basic Concepts
Understanding the following concepts would be helpful for you in configuring HiSysEvent logging. Understanding the following concepts would be helpful for you in configuring HiSysEvent logging.
- Event domain - Event domain<br>Represents the domain to which an event belongs. It is specified by the **domain** field in the YAML file. For details, see [domain](#example) in the example YAML file.
Represents the domain to which an event belongs. It is specified by the **domain** field in the YAML file. For details, see [domain](#section123181432175123) in the example YAML file.
- Event name<br>Indicates the events in an event domain. For details, see [EVENT\_NAMEA/EVENT\_NAMEB](#example) in the example YAML file.
- Event name - Parameter<br>Defines the key values in an event name. For details, see [__BASE/NAME1/NAME2](#example) in the example YAML file.
Indicates the events in an event domain. For details, see [EVENT\_NAMEA/EVENT\_NAMEB](#section123181432175123) in the example YAML file.
- Parameter
Defines the key values in an event name. For details, see [__BASE/NAME1/NAME2](#section123181432175123) in the example YAML file.
### Constraints
### Constraints<a name="section123181432175114"></a> Constraints on the event domain, event name, and parameter
- Each YAML file can contain only one event domain, and the domain name cannot be the same as that defined in other YAML files. - Each YAML file can contain only one event domain, and the domain name cannot be the same as that defined in other YAML files.
- Zero or more event names can be defined for one event domain. The event names in the same event domain must be unique. - Zero or more event names can be defined for one event domain. The event names in the same event domain must be unique.
- Multiple parameters can be defined for one event name. The parameters in the same event name must be unique. There must be one and only one parameter named **\__BASE** in each event name. See Table 1 for the fields of this parameter and Table 2 for the fields of other custom parameters. - Multiple parameters can be defined for one event name. The parameters in the same event name must be unique. There must be only one parameter named **__BASE** in each event name. See Table 1 for the fields of this parameter and Table 2 for the fields of other custom parameters.
**Table 1** Fields in the \__BASE parameter **Table 1** Fields in the \__BASE parameter
| Field| Description| | Field| Description|
| ----- | ----- | | -------- | -------- |
| type | Indicates the type of the event. This field is mandatory. <br><br>Value:<ul><li>**FAULT**: fault </li><li>**STATISTIC**: statistics </li><li>**SECURITY**: security </li><li>**BEHAVIOR**: user behavior</li></ul> | | type | Event type. This field is mandatory.<br>Value:<br>- FAULT: fault<br>- STATISTIC: statistics<br>- SECURITY: security<br>- BEHAVIOR: user behavior|
| level | Indicates the level of the event. This field is mandatory. <br><br>Value: <ul><li>**CRITICAL**: critical </li><li>**MINOR**: minor</li></ul> | | level | Event level. This field is mandatory.<br>Value:<br>- CRITICAL: critical<br>- MINOR: minor|
| tag | Indicates the tag of the event. This field is mandatory. <br><br>Rule:<ul><li>You can define a maximum of five tags separated with a space. </li><li>A single tag can contain a maximum of 16 characters, including a to z, A to Z, and 0 to 9.</li></ul>| | tag | Event tag. This field is mandatory.<br>Rule:<br>- You can define a maximum of five tags, separated with a space.<br>- A single tag can contain a maximum of 16 characters, including a to z, A to Z, and 0 to 9.|
| desc | Describes the event name. This field is mandatory. <br><br>Rule:<ul><li>The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (&#95;).</li></ul>| | desc | Event name. This field is mandatory.<br>Rule:<br>The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).|
**Table 2** Description of custom parameters **Table 2** Description of custom parameters
| Field| Description| | Field| Description|
| ----- | ----- | | -------- | -------- |
| type | Indicates the type of a parameter. This field is mandatory. <br><br>Value: <ul><li>BOOL</li><li>UINT8</li><li>UINT16</li><li>INT32</li><li>UINT32</li><li>UINT64</li><li>FLOAT</li><li>DOUBLE</li><li>STRING</li></ul>| | type | Parameter type. This field is mandatory.<br>Value:<br>- BOOL<br>- INT8<br>- UINT8<br>- INT16<br>- UINT16<br>- INT32<br>- UINT32<br>- INT64<br>- UINT64<br>- FLOAT<br>- DOUBLE<br>- STRING |
| arrsize | Specifies the length of the parameter of the array type. This field is optional. <br><br>Value range: <ul><li>1-100</li></ul>| | arrsize | Length of the parameter of the array type. This field is optional.<br>Value:<br>1-100|
| desc | Describes the parameter. This field is mandatory. <br><br>Rule:<ul><li>The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (&#95;).</li></ul>| | desc | Parameter description. This field is mandatory.<br>Rule:<br>The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).|
## Writing a YAML File<a name="section123181432175113"></a> ## Writing a YAML File
### Writing Rules<a name="section123181432175133"></a>
### Writing Rules
- Event domain naming rules: - Event domain naming rules:
- The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;). - The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;).
- The name contains 1 to 16 characters. - The name contains 1 to 16 characters.
- Event naming rules: - Event naming rules:
- The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;). - The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;).
- The name contains 1 to 32 characters. - The name contains 1 to 32 characters.
- The number of internal event names in an event domain cannot exceed 4096. - The number of internal event names in an event domain cannot exceed 4096.
- Parameter naming rules: - Parameter naming rules:
- The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;). - The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;).
- The name contains 1 to 32 characters. - The name contains 1 to 32 characters.
- The number of parameters in an event domain cannot exceed 128. - The number of parameters in an event domain cannot exceed 128.
### Example<a name="section123181432175123"></a>
- In the example YAML file, the event domain name is **MODULEA**. The event domain contains two events named **EVENT\_NAMEA** and **EVENT\_NAMEB**. ### Example
- **EVENT\_NAMEA** is defined as a critical event of the fault type. The event contains the **NAME1** parameter of the string type, the **NAME2** parameter of the string type, and the **NAME3** parameter of the unsigned short integer type. Therefore, you can perform [real-time subscription](subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEA**.
- **EVENT\_NAMEB** is defined as a general event of the statistics type. The event contains the **NAME1** parameter of the unsigned short integer type and the **NAME2** parameter of the integer type. Because two event tags named **tag1** and **tag2** are defined for **EVENT\_NAMEB** in the **\__BASE** parameter, you can perform [real-time subscription](subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEB**, or based on the event tag. - In the example YAML file, the event domain name is **MODULEA**. The event domain contains two events named **EVENT_NAMEA** and **EVENT_NAMEB**.
- **EVENT\_NAMEA** is defined as a critical event of the fault type. The event contains the **NAME1** parameter of the string type, the **NAME2** parameter of the string type, and the **NAME3** parameter of the unsigned short integer type. Therefore, you can perform [real-time subscription](../subsystems/subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEA**.
- **EVENT\_NAMEB** is defined as a general event of the statistics type. The event contains the **NAME1** parameter of the unsigned short integer type and the **NAME2** parameter of the integer type. Because two event tags named **tag1** and **tag2** are defined for **EVENT\_NAMEB** in the **\__BASE** parameter, you can perform [real-time subscription](../subsystems/subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEB**, or based on the event tag.
``` ```
########################################## ##########################################
# HiSysEvent definition for MODULEA # the hisysevent definition for module a #
########################################## ##########################################
domain: MODULEA domain: MODULEA
...@@ -84,11 +95,14 @@ Understanding the following concepts would be helpful for you in configuring HiS ...@@ -84,11 +95,14 @@ Understanding the following concepts would be helpful for you in configuring HiS
NAME2: {type: INT32, desc: name2} NAME2: {type: INT32, desc: name2}
``` ```
## Verifying the YAML File<a name="section123181432175115"></a>
### Configuring the YAML File Path<a name="section123181432175135"></a> ## Verifying the YAML File
### Configuring the YAML File Path
In the **bundle.json** file, use the **hisysevent_config** attribute to specify the YAML file path.
In the **bundle.json** file, use the ```hisysevent_config``` attribute to specify the YAML file path.
``` ```
{ {
...@@ -131,21 +145,22 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif ...@@ -131,21 +145,22 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif
} }
``` ```
>![](../public_sys-resources/icon-note.gif) **Note:**
>The YAML file can be placed in any directory of the component project as needed. You only need to specify the path in the **bundle.json** file.
### Compiling the YAML File<a name="section123181432175137"></a> > **NOTE**<br>
> The YAML file can be placed in any directory of the component project as needed. You only need to specify the path in the **bundle.json** file.
- Perform full compilation.
- During full compilation of the system, the configuration in the YAML files of all components are summarized. After the compilation is complete, the **hisysevent.def** file will be generated in the specified directory. ### Compiling YAML Files
- Perform full compilation.
- During full compilation of the system, the configurations in the YAML files of all components are summarized. After the compilation is complete, the **hisysevent.def** file will be generated in the specified directory.
``` ```
cd absolute path of the project's root directory cd *absolute path of the project's root directory*
./build --product-name <product name> ./build --product-name <product name>
``` ```
- To obtain the **hisysevent.def** file generated after full compilation, run the following command: - To obtain the **hisysevent.def** file generated after full compilation, run the following commands:
``` ```
cd absolute path of the project's root directory cd absolute path of the project's root directory
...@@ -153,9 +168,9 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif ...@@ -153,9 +168,9 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif
``` ```
- Single-file compilation: - Single-file compilation:
You can also compile the YAML file of a single component by running the following commands: You can also compile the YAML file of a single component by running the following commands:
``` ```
cd absolute path of the project's root directory cd absolute path of the project's root directory
./build/ohos/hisysevent/gen_def_from_all_yaml.py --yaml-list <yaml file list> --def-path <file store directory> ./build/ohos/hisysevent/gen_def_from_all_yaml.py --yaml-list <yaml file list> --def-path <file store directory>
...@@ -163,13 +178,14 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif ...@@ -163,13 +178,14 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif
**Table 3** Parameters for single-file compilation **Table 3** Parameters for single-file compilation
| Parameter| Description| | Option| Description|
| ------ | ------ | | -------- | -------- |
| --yaml-list | Specifies the paths of the YAML files to be compiled. If there are multiple YAML file paths, separate each of them with a space.| | --yaml-list | Paths of the YAML files to be compiled. If there are multiple YAML file paths, separate each of them with a space.|
| --def-path | Specifies the path of the **hisysevent.def** file generated after compilation.| | --def-path | Path of the **hisysevent.def** file generated after compilation.|
### Logging and Querying Events<a name="section123181432175139"></a> ### Logging and Querying Events
1. Push the **hisysevent.def** file to the **/system/etc/hiview/** directory of the device by using the [hdc_std tool](subsys-toolchain-hdc-guide.md). 1. Push the **hisysevent.def** file to the **/system/etc/hiview/** directory of the device by using the [hdc_std tool](../subsystems/subsys-toolchain-hdc-guide.md).
2. Trigger logging of the custom system events in the YAML file. Then, run [hisysevent -l](subsys-dfx-hisysevent-tool.md) to query historical system events to find out if the logging of the custom system events is successful. 2. Trigger logging of the custom system events in the YAML file. Then, run [hisysevent -l](../subsystems/subsys-dfx-hisysevent-tool.md) to query historical system events to find out if the logging of the custom system events is successful.
# Telephony Subsystem Changelog
## cl.telephony.1 Radio Module API Change
### `isNrSupported` API Change for the Radio Module of Telephony Subsystem
NR is a proper noun and must be capitalized.
You need to adapt your application.
**Change Impacts**
The JS API needs to be adapted for applications developed based on earlier versions. Otherwise, relevant functions will be affected.
**Key API/Component Changes**
- Involved APIs:
isNrSupported(): boolean;
isNrSupported(slotId: number): boolean;
- Before change:
```js
function isNrSupported(): boolean;
function isNrSupported(slotId: number): boolean;
```
- After change:
```js
function isNRSupported(): boolean;
function isNRSupported(slotId: number): boolean;
```
**Adaptation Guide**
Use the new API. The sample code is as follows:
```js
let result = radio.isNrSupported();
console.log("Result: "+ result);
```
```js
let slotId = 0;
let result = radio.isNRSupported(slotId);
console.log("Result: "+ result);
```
# Telephony Subsystem Changelog
## cl.telephony.1 Call Module reject API Change
Changed the `reject` API to the `rejectCall` API in the call module of the telephony subsystem since API version 9.
You need to adapt your application.
**Change Impact**
The `reject` API is deprecated and cannot be used anymore. Use the `rejectCall` API instead. Otherwise, relevant functions will be affected.
- Involved APIs:
```js
function reject(callId: number, callback: AsyncCallback<void>): void;
function reject(callId: number, options: RejectMessageOptions, callback: AsyncCallback<void>): void;
function reject(callId?: number, options?: RejectMessageOptions): Promise<void>;
function reject(callback: AsyncCallback<void>): void;
function reject(options: RejectMessageOptions, callback: AsyncCallback<void>): void;
```
- Before change:
```js
function reject(callId: number, callback: AsyncCallback<void>): void;
function reject(callId: number, options: RejectMessageOptions, callback: AsyncCallback<void>): void;
function reject(callId?: number, options?: RejectMessageOptions): Promise<void>;
function reject(callback: AsyncCallback<void>): void;
function reject(options: RejectMessageOptions, callback: AsyncCallback<void>): void;
```
- After change:
```js
function rejectCall(callId: number, callback: AsyncCallback<void>): void;
function rejectCall(callId: number, options: RejectMessageOptions, callback: AsyncCallback<void>): void;
function rejectCall(callId?: number, options?: RejectMessageOptions): Promise<void>;
function rejectCall(callback: AsyncCallback<void>): void;
function rejectCall(options: RejectMessageOptions, callback: AsyncCallback<void>): void;
```
**Adaptation Guide**
The `reject` API is deprecated and cannot be used anymore. Use the `rejectCall` API instead.
The sample code is as follows:
```js
call.rejectCall("138xxxxxxxx", (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
let rejectMessageOptions={
messageContent: "Unknown number blocked"
}
let promise = call.rejectCall(1, rejectMessageOptions);
promise.then(data => {
console.log(`rejectCall success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`rejectCall fail, promise: err->${JSON.stringify(err)}`);
});
```
```js
let rejectMessageOptions={
messageContent: "Unknown number blocked"
}
let promise = call.rejectCall(1, rejectMessageOptions);
promise.then(data => {
console.log(`rejectCall success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`rejectCall fail, promise: err->${JSON.stringify(err)}`);
});
```
```js
call.rejectCall((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
let rejectMessageOptions={
messageContent: "Unknown number blocked"
}
call.rejectCall(rejectMessageOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## cl.telephony.2 Call Module answer API Change
Changed the `answer` API to the `answerCall` API in the call module of the telephony subsystem since API version 9.
You need to adapt your application.
**Change Impact**
The `answer` API is deprecated and cannot be used anymore. Use the `answerCall` API instead. Otherwise, relevant functions will be affected.
- Involved APIs:
```js
function answer(callId: number, callback: AsyncCallback<void>): void;
function answer(callId?: number): Promise<void>;
function answer(callback: AsyncCallback<void>): void;
```
- Before change:
```js
function answer(callId: number, callback: AsyncCallback<void>): void;
function answer(callId?: number): Promise<void>;
function answer(callback: AsyncCallback<void>): void;
```
- After change:
```js
function answerCall(callId: number, callback: AsyncCallback<void>): void;
function answerCall(callId?: number): Promise<void>;
function answerCall(callback: AsyncCallback<void>): void;
```
**Adaptation Guide**
The `answer` API is deprecated and cannot be used anymore. Use the `answerCall` API instead.
The sample code is as follows:
```js
call.answerCall(1, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
let promise = call.answerCall(1);
promise.then(data => {
console.log(`answerCall success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`answerCall fail, promise: err->${JSON.stringify(err)}`);
});
```
```js
call.answerCall((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## cl.telephony.1 Call Module hangup API Change
Changed the `hangup` API to the `hangUpCall` API in the call module of the telephony subsystem since API version 9.
You need to adapt your application.
**Change Impact**
The `hangup` API is deprecated and cannot be used anymore. Use the `hangUpCall` API instead. Otherwise, relevant functions will be affected.
- Involved APIs:
```js
function hangup(callId: number, callback: AsyncCallback<void>): void;
function hangup(callId?: number): Promise<void>;
function hangup(callback: AsyncCallback<void>): void;
```
- Before change:
```js
function hangup(callId: number, callback: AsyncCallback<void>): void;
function hangup(callId?: number): Promise<void>;
function hangup(callback: AsyncCallback<void>): void;
```
- After change:
```js
function hangUpCall(callId: number, callback: AsyncCallback<void>): void;
function hangUpCall(callId?: number): Promise<void>;
function hangUpCall(callback: AsyncCallback<void>): void;
```
**Adaptation Guide**
The `hangup` API is deprecated and cannot be used anymore. Use the `hangUpCall` API instead.
The sample code is as follows:
```js
call.hangUpCall(1, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
let promise = call.hangUpCall(1);
promise.then(data => {
console.log(`hangUpCall success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`hangUpCall fail, promise: err->${JSON.stringify(err)}`);
});
```
```js
call.hangUpCall((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
# Telephony Subsystem Changelog
## cl.telephony.1 Call Module dial API Change
Changed the `dial` API to the `dialCall` API in the call module of the telephony subsystem since API version 9.
You need to adapt your application.
**Change Impact**
The `dial` API is deprecated and cannot be used anymore. Use the `dialCall` API instead. Otherwise, relevant functions will be affected.
**Key API/Component Changes**
- Involved APIs:
```js
dial(phoneNumber: string, callback: AsyncCallback<boolean>): void;
dial(phoneNumber: string, options: DialOptions, callback: AsyncCallback<boolean>): void;
dial(phoneNumber: string, options?: DialOptions): Promise<boolean>;
```
- Before change:
```js
function dial(phoneNumber: string, callback: AsyncCallback<boolean>): void;
function dial(phoneNumber: string, options: DialOptions, callback: AsyncCallback<boolean>): void;
function dial(phoneNumber: string, options?: DialOptions): Promise<boolean>;
```
- After change:
```js
function dialCall(phoneNumber: string, callback: AsyncCallback<void>): void;
function dialCall(phoneNumber: string, options: DialCallOptions, callback: AsyncCallback<void>): void;
function dialCall(phoneNumber: string, options?: DialCallOptions): Promise<void>;
```
**Adaptation Guide**
The `dial` API is deprecated and cannot be used anymore. Use the `dialCall` API instead. Otherwise, relevant functions will be affected.
Use the new API. The sample code is as follows:
```js
call.dialCall("138xxxxxxxx", (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
call.dialCall("138xxxxxxxx", {
accountId: 0,
videoState: 0,
dialScene: 0,
dialType: 0,
}, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
try {
call.dialCall('138xxxxxxxx');
console.log(`dialCall success, promise: data->${JSON.stringify(data)}`);
} catch (error) {
console.log(`dialCall fail, promise: err->${JSON.stringify(error)}`);
}
```
# USB Subsystem API Changelog
## cl.usb_manager.1 Bundle Name Change
For applications developed based on earlier versions, you need to change the name of the imported bundle. Otherwise, the original service logic will be affected.
**Key API/Component Changes**
| Original Bundle Name | New Bundle Name |
|------------------ | ------------------- |
| ohos.usbV9.d.ts | ohos.usbManager.d.ts |
**Adaptation Guide**
Change **@ohos.usbV9** to **@ohos.usbManager** when importing the bundle.
## cl.usb_manager.2 API Parameter Type Change
For applications developed based on earlier versions, you need to modify the parameter type. Otherwise, the original service logic will be affected.
**Key API/Component Changes**
| Original Class Name | New Class Name |
|---------------| ------------- |
| interface USBConfig | interface USBConfiguration |
| Original Namespace | New Namespace |
|---------------| ------------- |
| @namespace usbV9 | @namespace usbManager |
| Bundle Name | Original API | New API |
| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.usbManager.d.ts | function setConfiguration(pipe: USBDevicePipe, config: USBConfig): number; | function setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number; |
**Adaptation Guide**
When calling **setConfiguration**, change the parameter type from **USBConfig** to **USBConfiguration**.
# Power Subsystem Changelog
## cl.powermgr.1 CommonEventBatteryChangedCode API Change
Changed the **CommonEventBatteryChangedCode** enum class in [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) as follows:
- Changed the class name to **CommonEventBatteryChangedKey**.
- Deleted **EXTRA_MAX_CURRENT**, **EXTRA_MAX_VOLTAGE**, and **EXTRA_CHARGE_COUNTER**.
- Changed the enum value type from numeric to string.
#### Change Impact
The JS API needs to be adapted for applications developed based on earlier versions. Otherwise, relevant functions will be affected.
#### Key API/Component Changes
Before change:
| Name | Value | Description |
| -------------------- | ---- | -------------------------------------------------- |
| EXTRA_SOC | 0 | Remaining battery level in percentage. |
| EXTRA_VOLTAGE | 1 | Battery voltage of the device. |
| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. |
| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. |
| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. |
| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. |
| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. |
| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. |
| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. |
| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.|
| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. |
| EXTRA_CAPACITY_LEVEL | 11 | Battery level of the device. |
After change:
| Name | Value | Description |
| -------------------- | --------------- | -------------------------------------------------- |
| EXTRA_SOC | "soc" | Remaining battery level in percentage. |
| EXTRA_CHARGE_STATE | "chargeState" | Battery charging status of the device. |
| EXTRA_HEALTH_STATE | "healthState" | Battery health status of the device. |
| EXTRA_PLUGGED_TYPE | "pluggedType" | Type of the charger connected to the device. |
| EXTRA_VOLTAGE | "voltage" | Battery voltage of the device. |
| EXTRA_TECHNOLOGY | "technology" | Battery technology of the device. |
| EXTRA_TEMPERATURE | "temperature" | Battery temperature of the device. |
| EXTRA_PRESENT | "present" | Whether the battery is supported by the device or installed.|
| EXTRA_CAPACITY_LEVEL | "capacityLevel" | Battery level of the device. |
#### Adaptation Guide
For details, see the API reference of the [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) API.
## cl.powermgr.2 estimatedRemainingChargeTime API Change
Changed the **estimatedRemainingChargeTime** API in [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) to a system API.
#### Change Impact
The JS API needs to be adapted for applications developed based on earlier versions. Otherwise, relevant functions will be affected.
#### Adaptation Guide
For details, see the API reference of the [@ohos.batteryInfo](../../../application-dev/reference/apis/js-apis-battery-info.md) API.
## cl.powermgr.3 System Common Event Behavior Change
The following common events are provided in the battery information through [@ohos.commonEventManager (common event module)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-commonEventManager.md):
- COMMON_EVENT_BATTERY_LOW: common event for low battery level. It includes the remaining battery in percentage.
- COMMON_EVENT_BATTERY_OKAY: common event for normal battery level. It includes the remaining battery in percentage.
- COMMON_EVENT_POWER_CONNECTED: common event for connection to an external power supply. It includes the type of the power supply to which the device is connected.
- COMMON_EVENT_POWER_DISCONNECTED: common event for disconnection from an external power supply. It includes the type of the power supply from which the device is disconnected.
- COMMON_EVENT_CHARGING: common event for starting of battery charging. It includes the battery charging status.
- COMMON_EVENT_DISCHARGING: common event for ending of battery charging. It includes the battery charging status.
Changed the method of obtaining data from common events from **CommonEventData.data** to **CommonEventData.code**.
#### Change Impact
The application developed based on earlier versions needs to adapt the method for obtaining common events in the battery information. Otherwise, the original service logic will be affected.
#### Adaptation Guide
For details, see the API reference of the [@ohos.commonEventManager (Common Event Manager)](../../../application-dev/reference/apis/js-apis-commonEventManager.md) API.
# Startup Subsystem JS API Changelog
## cl.startup.1 Bundle Name Change
**Change Impact**
The original bundle name **@ohos.systemParameterV9** will be deleted and cannot be used anymore. Use the new bundle name **@ohos.systemParameterEnhance** instead.
**Adaptation Guide**
Change the bundle name from **@ohos.systemParameterV9** to **@ohos.systemParameterEnhance**. The APIs remain unchanged. The following is the sample code:
```js
import @ohos.systemParameterEnhance
```
...@@ -64,7 +64,7 @@ const config = { ...@@ -64,7 +64,7 @@ const config = {
language: 'Zh-Hans', // 简体中文 language: 'Zh-Hans', // 简体中文
colorMode: COLOR_MODE_LIGHT, // 浅色模式 colorMode: COLOR_MODE_LIGHT, // 浅色模式
direction: DIRECTION_VERTICAL, // 垂直方向 direction: DIRECTION_VERTICAL, // 垂直方向
screenDensity: SCREEN_DENSITY_SDPI, // 屏幕分辨率为'sdpi' screenDensity: SCREEN_DENSITY_SDPI, // 屏幕像素密度为'sdpi'
displayId: 1, // 应用在Id为1的物理屏上显示 displayId: 1, // 应用在Id为1的物理屏上显示
hasPointerDevice: true, // 指针类型设备已连接 hasPointerDevice: true, // 指针类型设备已连接
}; };
...@@ -76,7 +76,7 @@ try { ...@@ -76,7 +76,7 @@ try {
} else { } else {
console.log('updateConfiguration success.'); console.log('updateConfiguration success.');
} }
}) });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message));
...@@ -122,7 +122,7 @@ const config = { ...@@ -122,7 +122,7 @@ const config = {
language: 'Zh-Hans', // 简体中文 language: 'Zh-Hans', // 简体中文
colorMode: COLOR_MODE_LIGHT, // 浅色模式 colorMode: COLOR_MODE_LIGHT, // 浅色模式
direction: DIRECTION_VERTICAL, // 垂直方向 direction: DIRECTION_VERTICAL, // 垂直方向
screenDensity: SCREEN_DENSITY_SDPI, // 屏幕分辨率为'sdpi' screenDensity: SCREEN_DENSITY_SDPI, // 屏幕像素密度为'sdpi'
displayId: 1, // 应用在Id为1的物理屏上显示 displayId: 1, // 应用在Id为1的物理屏上显示
hasPointerDevice: true, // 指针类型设备已连接 hasPointerDevice: true, // 指针类型设备已连接
}; };
...@@ -132,7 +132,7 @@ try { ...@@ -132,7 +132,7 @@ try {
console.log('updateConfiguration success.'); console.log('updateConfiguration success.');
}).catch((err) => { }).catch((err) => {
console.log('updateConfiguration fail, err: ' + JSON.stringify(err)); console.log('updateConfiguration fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message));
...@@ -311,7 +311,7 @@ try { ...@@ -311,7 +311,7 @@ try {
console.log('getExtensionRunningInfos success, data: ' + JSON.stringify(data)); console.log('getExtensionRunningInfos success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('getExtensionRunningInfos fail, err: ' + JSON.stringify(err)); console.log('getExtensionRunningInfos fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message));
...@@ -385,5 +385,5 @@ abilityManager.getTopAbility().then((data) => { ...@@ -385,5 +385,5 @@ abilityManager.getTopAbility().then((data) => {
console.log('getTopAbility success, data: ' + JSON.stringify(data)); console.log('getTopAbility success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('getTopAbility fail, err: ' + JSON.stringify(err)); console.log('getTopAbility fail, err: ' + JSON.stringify(err));
}) });
``` ```
\ No newline at end of file
...@@ -45,7 +45,7 @@ appManager.isRunningInStabilityTest((err, flag) => { ...@@ -45,7 +45,7 @@ appManager.isRunningInStabilityTest((err, flag) => {
} else { } else {
console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag));
} }
}) });
``` ```
...@@ -151,7 +151,7 @@ appManager.isRamConstrainedDevice((err, data) => { ...@@ -151,7 +151,7 @@ appManager.isRamConstrainedDevice((err, data) => {
} else { } else {
console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data));
} }
}) });
``` ```
## appManager.getAppMemorySize ## appManager.getAppMemorySize
...@@ -221,7 +221,7 @@ appManager.getAppMemorySize((err, data) => { ...@@ -221,7 +221,7 @@ appManager.getAppMemorySize((err, data) => {
} else { } else {
console.log('The size of app memory is:' + JSON.stringify(data)); console.log('The size of app memory is:' + JSON.stringify(data));
} }
}) });
``` ```
## appManager.getRunningProcessInformation ## appManager.getRunningProcessInformation
...@@ -295,7 +295,7 @@ appManager.getRunningProcessInformation((err, data) => { ...@@ -295,7 +295,7 @@ appManager.getRunningProcessInformation((err, data) => {
} else { } else {
console.log('The process running information is:' + JSON.stringify(data)); console.log('The process running information is:' + JSON.stringify(data));
} }
}) });
``` ```
## appManager.on ## appManager.on
...@@ -352,7 +352,7 @@ let applicationStateObserver = { ...@@ -352,7 +352,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
try { try {
const observerId = appManager.on('applicationState', applicationStateObserver); const observerId = appManager.on('applicationState', applicationStateObserver);
console.log(`[appManager] observerCode: ${observerId}`); console.log(`[appManager] observerCode: ${observerId}`);
...@@ -416,7 +416,7 @@ let applicationStateObserver = { ...@@ -416,7 +416,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
let bundleNameList = ['bundleName1', 'bundleName2']; let bundleNameList = ['bundleName1', 'bundleName2'];
try { try {
const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
...@@ -478,7 +478,7 @@ let applicationStateObserver = { ...@@ -478,7 +478,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
let bundleNameList = ['bundleName1', 'bundleName2']; let bundleNameList = ['bundleName1', 'bundleName2'];
try { try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
...@@ -559,7 +559,7 @@ let applicationStateObserver = { ...@@ -559,7 +559,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
let bundleNameList = ['bundleName1', 'bundleName2']; let bundleNameList = ['bundleName1', 'bundleName2'];
try { try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
...@@ -574,7 +574,7 @@ try { ...@@ -574,7 +574,7 @@ try {
console.log('unregisterApplicationStateObserver success, data: ' + JSON.stringify(data)); console.log('unregisterApplicationStateObserver success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('unregisterApplicationStateObserver faile, err: ' + JSON.stringify(err)); console.log('unregisterApplicationStateObserver faile, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -660,7 +660,7 @@ appManager.getForegroundApplications().then((data) => { ...@@ -660,7 +660,7 @@ appManager.getForegroundApplications().then((data) => {
console.log('getForegroundApplications success, data: ' + JSON.stringify(data)); console.log('getForegroundApplications success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('getForegroundApplications fail, err: ' + JSON.stringify(err)); console.log('getForegroundApplications fail, err: ' + JSON.stringify(err));
}) });
``` ```
## appManager.killProcessWithAccount ## appManager.killProcessWithAccount
...@@ -702,7 +702,7 @@ try { ...@@ -702,7 +702,7 @@ try {
console.log('killProcessWithAccount success'); console.log('killProcessWithAccount success');
}).catch((err) => { }).catch((err) => {
console.error('killProcessWithAccount fail, err: ' + JSON.stringify(err)); console.error('killProcessWithAccount fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.error('error: ' + paramError.code + ', ' + paramError.message); console.error('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -844,7 +844,7 @@ try { ...@@ -844,7 +844,7 @@ try {
console.log('killProcessesByBundleName success.'); console.log('killProcessesByBundleName success.');
}).catch((err) => { }).catch((err) => {
console.log('killProcessesByBundleName fail, err: ' + JSON.stringify(err)); console.log('killProcessesByBundleName fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -940,7 +940,7 @@ try { ...@@ -940,7 +940,7 @@ try {
console.log('clearUpApplicationData success.'); console.log('clearUpApplicationData success.');
}).catch((err) => { }).catch((err) => {
console.log('clearUpApplicationData fail, err: ' + JSON.stringify(err)); console.log('clearUpApplicationData fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
| language | string | 是 | 是 | 表示应用程序的当前语言。例如:zh。 | | language | string | 是 | 是 | 表示应用程序的当前语言。例如:zh。 |
| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:未设置(COLOR_MODE_NOT_SET),浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | | colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:未设置(COLOR_MODE_NOT_SET),浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 |
| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | 是 | 否 | 表示屏幕方向,取值范围:未设置(DIRECTION_NOT_SET),水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | | direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | 是 | 否 | 表示屏幕方向,取值范围:未设置(DIRECTION_NOT_SET),水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 |
| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | 是 | 否 | 表示屏幕分辨率,取值范围:未设置(SCREEN_DENSITY_NOT_SET),SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | | screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | 是 | 否 | 表示屏幕像素密度,取值范围:未设置(SCREEN_DENSITY_NOT_SET),SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 |
| displayId | number | 是 | 否 | 表示应用所在的物理屏幕Id。 | | displayId | number | 是 | 否 | 表示应用所在的物理屏幕Id。 |
| hasPointerDevice | boolean | 是 | 否 | 指示指针类型设备是否已连接,如键鼠、触控板等。 | | hasPointerDevice | boolean | 是 | 否 | 指示指针类型设备是否已连接,如键鼠、触控板等。 |
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
onCreate(want, launchParam) { onCreate(want, launchParam) {
let envCallback = { let envCallback = {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`);
let language = config.language; let language = config.language;
let colorMode = config.colorMode; let colorMode = config.colorMode;
let direction = config.direction; let direction = config.direction;
......
...@@ -46,10 +46,10 @@ import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; ...@@ -46,10 +46,10 @@ import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant';
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| SCREEN_DENSITY_NOT_SET | 0 | 未设置屏幕分辨率。 | | SCREEN_DENSITY_NOT_SET | 0 | 未设置屏幕像素密度。 |
| SCREEN_DENSITY_SDPI | 120 | 屏幕分辨率为'sdpi'。 | | SCREEN_DENSITY_SDPI | 120 | 屏幕像素密度为'sdpi'。 |
| SCREEN_DENSITY_MDPI | 160 | 屏幕分辨率为'mdpi'。 | | SCREEN_DENSITY_MDPI | 160 | 屏幕像素密度为'mdpi'。 |
| SCREEN_DENSITY_LDPI | 240 | 屏幕分辨率为'ldpi'。 | | SCREEN_DENSITY_LDPI | 240 | 屏幕像素密度为'ldpi'。 |
| SCREEN_DENSITY_XLDPI | 320 | 屏幕分辨率为'xldpi'。 | | SCREEN_DENSITY_XLDPI | 320 | 屏幕像素密度为'xldpi'。 |
| SCREEN_DENSITY_XXLDPI | 480 | 屏幕分辨率为'xxldpi'。 | | SCREEN_DENSITY_XXLDPI | 480 | 屏幕像素密度为'xxldpi'。 |
| SCREEN_DENSITY_XXXLDPI | 640 | 屏幕分辨率为'xxxldpi'。 | | SCREEN_DENSITY_XXXLDPI | 640 | 屏幕像素密度为'xxxldpi'。 |
...@@ -53,7 +53,7 @@ let callbackId; ...@@ -53,7 +53,7 @@ let callbackId;
export default class MyAbility extends Ability { export default class MyAbility extends Ability {
onCreate() { onCreate() {
console.log('MyAbility onCreate') console.log('MyAbility onCreate');
globalThis.applicationContext = this.context.getApplicationContext(); globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = { let EnvironmentCallback = {
onConfigurationUpdated(config){ onConfigurationUpdated(config){
...@@ -62,7 +62,7 @@ export default class MyAbility extends Ability { ...@@ -62,7 +62,7 @@ export default class MyAbility extends Ability {
onMemoryLevel(level){ onMemoryLevel(level){
console.log('onMemoryLevel level: ${JSON.stringify(level)}'); console.log('onMemoryLevel level: ${JSON.stringify(level)}');
} }
} };
// 1.获取applicationContext // 1.获取applicationContext
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
// 2.通过applicationContext注册监听应用内生命周期 // 2.通过applicationContext注册监听应用内生命周期
......
...@@ -33,7 +33,7 @@ let observer = { ...@@ -33,7 +33,7 @@ let observer = {
onUnhandledException(errorMsg) { onUnhandledException(errorMsg) {
console.log('onUnhandledException, errorMsg: ', errorMsg) console.log('onUnhandledException, errorMsg: ', errorMsg)
} }
} };
try { try {
errorManager.on('error', observer); errorManager.on('error', observer);
} catch (paramError) { } catch (paramError) {
...@@ -106,7 +106,7 @@ try { ...@@ -106,7 +106,7 @@ try {
}) })
.catch((err) => { .catch((err) => {
console.log('----------- unregisterErrorObserver fail ----------', err); console.log('----------- unregisterErrorObserver fail ----------', err);
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
......
...@@ -9,7 +9,7 @@ missionManager模块提供系统任务管理能力,包括对系统任务执行 ...@@ -9,7 +9,7 @@ missionManager模块提供系统任务管理能力,包括对系统任务执行
## 导入模块 ## 导入模块
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager';
``` ```
## 权限列表 ## 权限列表
...@@ -51,7 +51,7 @@ on(type:'mission', listener: MissionListener): number; ...@@ -51,7 +51,7 @@ on(type:'mission', listener: MissionListener): number;
onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');},
onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');} onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}
}; };
console.log('registerMissionListener') console.log('registerMissionListener');
try { try {
let listenerid = missionManager.on('mission', listener); let listenerid = missionManager.on('mission', listener);
} catch (paramError) { } catch (paramError) {
...@@ -90,13 +90,13 @@ off(type: 'mission', listenerId: number, callback: AsyncCallback&lt;void&gt;): v ...@@ -90,13 +90,13 @@ off(type: 'mission', listenerId: number, callback: AsyncCallback&lt;void&gt;): v
onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');},
onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');} onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}
}; };
console.log('registerMissionListener') console.log('registerMissionListener');
try { try {
let listenerid = missionManager.registerMissionListener(listener); let listenerid = missionManager.registerMissionListener(listener);
missionManager.unregisterMissionListener(listenerid, (error) => { missionManager.unregisterMissionListener(listenerid, (error) => {
console.log('unregisterMissionListener'); console.log('unregisterMissionListener');
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -138,7 +138,7 @@ off(type: 'mission', listenerId: number): Promise&lt;void&gt;; ...@@ -138,7 +138,7 @@ off(type: 'mission', listenerId: number): Promise&lt;void&gt;;
onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');},
onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');} onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}
}; };
console.log('registerMissionListener') console.log('registerMissionListener');
try { try {
let listenerid = missionManager.registerMissionListener(listener); let listenerid = missionManager.registerMissionListener(listener);
...@@ -174,7 +174,7 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback&lt;M ...@@ -174,7 +174,7 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback&lt;M
**示例:** **示例:**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager';
try { try {
let allMissions=missionManager.getMissionInfos('',10).catch(function(err){console.log(err);}); let allMissions=missionManager.getMissionInfos('',10).catch(function(err){console.log(err);});
...@@ -221,7 +221,7 @@ getMissionInfo(deviceId: string, missionId: number): Promise&lt;MissionInfo&gt;; ...@@ -221,7 +221,7 @@ getMissionInfo(deviceId: string, missionId: number): Promise&lt;MissionInfo&gt;;
**示例:** **示例:**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager';
try { try {
let mission = missionManager.getMissionInfo('', 10).catch(function (err){ let mission = missionManager.getMissionInfo('', 10).catch(function (err){
...@@ -256,14 +256,14 @@ getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback&lt;Arr ...@@ -256,14 +256,14 @@ getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback&lt;Arr
**示例:** **示例:**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager';
try { try {
missionManager.getMissionInfos('', 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
console.log('getMissionInfos is called, error.code = ' + error.code); console.log('getMissionInfos is called, error.code = ' + error.code);
console.log('size = ' + missions.length); console.log('size = ' + missions.length);
console.log('missions = ' + JSON.stringify(missions)); console.log('missions = ' + JSON.stringify(missions));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -298,7 +298,7 @@ getMissionInfos(deviceId: string, numMax: number): Promise&lt;Array&lt;MissionIn ...@@ -298,7 +298,7 @@ getMissionInfos(deviceId: string, numMax: number): Promise&lt;Array&lt;MissionIn
**示例:** **示例:**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager';
try { try {
let allMissions = missionManager.getMissionInfos('', 10).catch(function (err){ let allMissions = missionManager.getMissionInfos('', 10).catch(function (err){
...@@ -333,7 +333,7 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback& ...@@ -333,7 +333,7 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback&
**示例:** **示例:**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager';
try { try {
missionManager.getMissionInfos('', 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
...@@ -345,8 +345,8 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback& ...@@ -345,8 +345,8 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback&
missionManager.getMissionSnapShot('', id, (error, snapshot) => { missionManager.getMissionSnapShot('', id, (error, snapshot) => {
console.log('getMissionSnapShot is called, error.code = ' + error.code); console.log('getMissionSnapShot is called, error.code = ' + error.code);
console.log('bundleName = ' + snapshot.ability.bundleName); console.log('bundleName = ' + snapshot.ability.bundleName);
}) });
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -435,8 +435,8 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: A ...@@ -435,8 +435,8 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: A
missionManager.getLowResolutionMissionSnapShot('', id, (error, snapshot) => { missionManager.getLowResolutionMissionSnapShot('', id, (error, snapshot) => {
console.log('getLowResolutionMissionSnapShot is called, error.code = ' + error.code); console.log('getLowResolutionMissionSnapShot is called, error.code = ' + error.code);
console.log('bundleName = ' + snapshot.ability.bundleName); console.log('bundleName = ' + snapshot.ability.bundleName);
}) });
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
......
...@@ -77,7 +77,7 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<v ...@@ -77,7 +77,7 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<v
} else { } else {
console.info( 'applyQuickFix success'); console.info( 'applyQuickFix success');
} }
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -118,7 +118,7 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>; ...@@ -118,7 +118,7 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>;
console.info('applyQuickFix success'); console.info('applyQuickFix success');
}).catch((error) => { }).catch((error) => {
console.info(`applyQuickFix err: + ${error}`); console.info(`applyQuickFix err: + ${error}`);
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -156,7 +156,7 @@ getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\<Applicat ...@@ -156,7 +156,7 @@ getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\<Applicat
} else { } else {
console.info(`getApplicationQuickFixInfo success: + ${data}`); console.info(`getApplicationQuickFixInfo success: + ${data}`);
} }
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -197,7 +197,7 @@ getApplicationQuickFixInfo(bundleName: string): Promise\<ApplicationQuickFixInfo ...@@ -197,7 +197,7 @@ getApplicationQuickFixInfo(bundleName: string): Promise\<ApplicationQuickFixInfo
console.info(`getApplicationQuickFixInfo success: + ${data}`); console.info(`getApplicationQuickFixInfo success: + ${data}`);
}).catch((error) => { }).catch((error) => {
console.info(`getApplicationQuickFixInfo err: + ${error}`); console.info(`getApplicationQuickFixInfo err: + ${error}`);
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
......
...@@ -34,7 +34,7 @@ import Want from '@ohos.app.ability.Want'; ...@@ -34,7 +34,7 @@ import Want from '@ohos.app.ability.Want';
- 基础用法 - 基础用法
```ts ```ts
var want = { let want = {
'deviceId': '', // deviceId为空表示本设备 'deviceId': '', // deviceId为空表示本设备
'bundleName': 'com.extreme.test', 'bundleName': 'com.extreme.test',
'abilityName': 'MainAbility', 'abilityName': 'MainAbility',
...@@ -110,13 +110,13 @@ import Want from '@ohos.app.ability.Want'; ...@@ -110,13 +110,13 @@ import Want from '@ohos.app.ability.Want';
* 文件描述符(FD) * 文件描述符(FD)
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
var fd; let fd;
try { try {
fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); fd = fileio.openSync('/data/storage/el2/base/haps/pic.png');
} catch(e) { } catch(e) {
console.log('openSync fail:' + JSON.stringify(e)); console.log('openSync fail:' + JSON.stringify(e));
} }
var want = { let want = {
'deviceId': '', // deviceId为空表示本设备 'deviceId': '', // deviceId为空表示本设备
'bundleName': 'com.extreme.test', 'bundleName': 'com.extreme.test',
'abilityName': 'MainAbility', 'abilityName': 'MainAbility',
......
...@@ -37,7 +37,7 @@ function getWantAgentCallback(err, data) { ...@@ -37,7 +37,7 @@ function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>'); console.info('==========================>getWantAgentCallback=======================>');
} }
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -62,7 +62,7 @@ var wantAgentInfo = { ...@@ -62,7 +62,7 @@ var wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
...@@ -100,7 +100,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -100,7 +100,7 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -160,7 +160,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -160,7 +160,7 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//getWantAgent回调 //getWantAgent回调
function getWantAgentCallback(err, data) { function getWantAgentCallback(err, data) {
...@@ -172,7 +172,7 @@ function getWantAgentCallback(err, data) { ...@@ -172,7 +172,7 @@ function getWantAgentCallback(err, data) {
} }
} }
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -241,10 +241,10 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -241,10 +241,10 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -309,7 +309,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -309,7 +309,7 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//getWantAgent回调 //getWantAgent回调
function getWantAgentCallback(err, data) { function getWantAgentCallback(err, data) {
...@@ -321,7 +321,7 @@ function getWantAgentCallback(err, data) { ...@@ -321,7 +321,7 @@ function getWantAgentCallback(err, data) {
} }
} }
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -390,10 +390,10 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -390,10 +390,10 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -460,7 +460,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -460,7 +460,7 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//getWantAgent回调 //getWantAgent回调
function getWantAgentCallback(err, data) { function getWantAgentCallback(err, data) {
...@@ -472,7 +472,7 @@ function getWantAgentCallback(err, data) { ...@@ -472,7 +472,7 @@ function getWantAgentCallback(err, data) {
} }
} }
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -543,10 +543,10 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -543,10 +543,10 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -611,7 +611,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -611,7 +611,7 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//getWantAgent回调 //getWantAgent回调
function getWantAgentCallback(err, data) { function getWantAgentCallback(err, data) {
...@@ -623,7 +623,7 @@ function getWantAgentCallback(err, data) { ...@@ -623,7 +623,7 @@ function getWantAgentCallback(err, data) {
} }
} }
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -692,10 +692,10 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -692,10 +692,10 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -761,7 +761,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -761,7 +761,7 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//getWantAgent回调 //getWantAgent回调
function getWantAgentCallback(err, data) { function getWantAgentCallback(err, data) {
...@@ -773,7 +773,7 @@ function getWantAgentCallback(err, data) { ...@@ -773,7 +773,7 @@ function getWantAgentCallback(err, data) {
} }
} }
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -809,7 +809,7 @@ try { ...@@ -809,7 +809,7 @@ try {
} }
var triggerInfo = { let triggerInfo = {
code:0 code:0
}; };
WantAgent.trigger(wantAgent, triggerInfo, triggerCallback); WantAgent.trigger(wantAgent, triggerInfo, triggerCallback);
...@@ -843,8 +843,8 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -843,8 +843,8 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent1; let wantAgent1;
var wantAgent2; let wantAgent2;
//getWantAgent回调 //getWantAgent回调
function getWantAgentCallback(err, data) { function getWantAgentCallback(err, data) {
...@@ -857,7 +857,7 @@ function getWantAgentCallback(err, data) { ...@@ -857,7 +857,7 @@ function getWantAgentCallback(err, data) {
} }
} }
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -927,11 +927,11 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -927,11 +927,11 @@ import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent1; let wantAgent1;
var wantAgent2; let wantAgent2;
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -994,10 +994,10 @@ getOperationType(agent: WantAgent, callback: AsyncCallback\<number>): void; ...@@ -994,10 +994,10 @@ getOperationType(agent: WantAgent, callback: AsyncCallback\<number>): void;
import WantAgent from '@ohos.app.ability.wantAgent'; import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
...@@ -1064,10 +1064,10 @@ getOperationType(agent: WantAgent): Promise\<number>; ...@@ -1064,10 +1064,10 @@ getOperationType(agent: WantAgent): Promise\<number>;
import WantAgent from '@ohos.app.ability.wantAgent'; import WantAgent from '@ohos.app.ability.wantAgent';
//wantAgent对象 //wantAgent对象
var wantAgent; let wantAgent;
//WantAgentInfo对象 //WantAgentInfo对象
var wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
......
...@@ -4569,7 +4569,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt; ...@@ -4569,7 +4569,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
表示返回码的枚举。 表示返回码的枚举。
> **说明:**<br/> > **说明:**<br/>
> 从API version 8开始支持,从API version 9开始废弃。建议查看[错误码文档](../errorcodes/errorcode-app-account.md)替代。 > 从API version 8开始支持,从API version 9开始废弃。相关信息建议查看[错误码文档](../errorcodes/errorcode-account.md)替代。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。
......
...@@ -11,17 +11,17 @@ AbilityMonitor模块提供匹配满足指定条件的受监视能力对象的方 ...@@ -11,17 +11,17 @@ AbilityMonitor模块提供匹配满足指定条件的受监视能力对象的方
通过abilityDelegator中的addAbilityMonitor来设置。 通过abilityDelegator中的addAbilityMonitor来设置。
```js ```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info("onAbilityCreateCallback");
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: "abilityname",
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (err : any) => { abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
......
...@@ -18,7 +18,6 @@ ...@@ -18,7 +18,6 @@
**示例:** **示例:**
```ts ```ts
import hilog from '@ohos.hilog';
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
import Window from '@ohos.window' import Window from '@ohos.window'
...@@ -43,12 +42,10 @@ export default class MainAbility extends Ability { ...@@ -43,12 +42,10 @@ export default class MainAbility extends Ability {
windowStage.loadContent('pages/index', (err, data) => { windowStage.loadContent('pages/index', (err, data) => {
if (err.code) { if (err.code) {
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR); console.error('failed to load the content, error: + ${JSON.stringify(err)}');
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return; return;
} }
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); console.info('Succeeded in loading the content, data: + ${JSON.stringify(data)}');
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
}); });
} }
} }
......
...@@ -34,7 +34,7 @@ deleteForm(formId: string, callback: AsyncCallback&lt;void&gt;): void ...@@ -34,7 +34,7 @@ deleteForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.deleteForm(formId, (error, data) => { formHost.deleteForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost deleteForm, error:' + JSON.stringify(error)); console.log('formHost deleteForm, error:' + JSON.stringify(error));
...@@ -67,7 +67,7 @@ deleteForm(formId: string): Promise&lt;void&gt; ...@@ -67,7 +67,7 @@ deleteForm(formId: string): Promise&lt;void&gt;
**参数:** **参数:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.deleteForm(formId).then(() => { formHost.deleteForm(formId).then(() => {
console.log('formHost deleteForm success'); console.log('formHost deleteForm success');
}).catch((error) => { }).catch((error) => {
...@@ -95,7 +95,7 @@ releaseForm(formId: string, callback: AsyncCallback&lt;void&gt;): void ...@@ -95,7 +95,7 @@ releaseForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.releaseForm(formId, (error, data) => { formHost.releaseForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost releaseForm, error:' + JSON.stringify(error)); console.log('formHost releaseForm, error:' + JSON.stringify(error));
...@@ -124,7 +124,7 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback&lt; ...@@ -124,7 +124,7 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback&lt;
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.releaseForm(formId, true, (error, data) => { formHost.releaseForm(formId, true, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost releaseForm, error:' + JSON.stringify(error)); console.log('formHost releaseForm, error:' + JSON.stringify(error));
...@@ -158,7 +158,7 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise&lt;void&gt; ...@@ -158,7 +158,7 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.releaseForm(formId, true).then(() => { formHost.releaseForm(formId, true).then(() => {
console.log('formHost releaseForm success'); console.log('formHost releaseForm success');
}).catch((error) => { }).catch((error) => {
...@@ -186,7 +186,7 @@ requestForm(formId: string, callback: AsyncCallback&lt;void&gt;): void ...@@ -186,7 +186,7 @@ requestForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.requestForm(formId, (error, data) => { formHost.requestForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost requestForm, error:' + JSON.stringify(error)); console.log('formHost requestForm, error:' + JSON.stringify(error));
...@@ -219,7 +219,7 @@ requestForm(formId: string): Promise&lt;void&gt; ...@@ -219,7 +219,7 @@ requestForm(formId: string): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.requestForm(formId).then(() => { formHost.requestForm(formId).then(() => {
console.log('formHost requestForm success'); console.log('formHost requestForm success');
}).catch((error) => { }).catch((error) => {
...@@ -247,7 +247,7 @@ castTempForm(formId: string, callback: AsyncCallback&lt;void&gt;): void ...@@ -247,7 +247,7 @@ castTempForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.castTempForm(formId, (error, data) => { formHost.castTempForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost castTempForm, error:' + JSON.stringify(error)); console.log('formHost castTempForm, error:' + JSON.stringify(error));
...@@ -280,7 +280,7 @@ castTempForm(formId: string): Promise&lt;void&gt; ...@@ -280,7 +280,7 @@ castTempForm(formId: string): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.castTempForm(formId).then(() => { formHost.castTempForm(formId).then(() => {
console.log('formHost castTempForm success'); console.log('formHost castTempForm success');
}).catch((error) => { }).catch((error) => {
...@@ -308,7 +308,7 @@ notifyVisibleForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void ...@@ -308,7 +308,7 @@ notifyVisibleForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.notifyVisibleForms(formId, (error, data) => { formHost.notifyVisibleForms(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
...@@ -341,7 +341,7 @@ notifyVisibleForms(formIds: Array&lt;string&gt;): Promise&lt;void&gt; ...@@ -341,7 +341,7 @@ notifyVisibleForms(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.notifyVisibleForms(formId).then(() => { formHost.notifyVisibleForms(formId).then(() => {
console.log('formHost notifyVisibleForms success'); console.log('formHost notifyVisibleForms success');
}).catch((error) => { }).catch((error) => {
...@@ -369,7 +369,7 @@ notifyInvisibleForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;vo ...@@ -369,7 +369,7 @@ notifyInvisibleForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;vo
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.notifyInvisibleForms(formId, (error, data) => { formHost.notifyInvisibleForms(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
...@@ -402,7 +402,7 @@ notifyInvisibleForms(formIds: Array&lt;string&gt;): Promise&lt;void&gt; ...@@ -402,7 +402,7 @@ notifyInvisibleForms(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.notifyInvisibleForms(formId).then(() => { formHost.notifyInvisibleForms(formId).then(() => {
console.log('formHost notifyInvisibleForms success'); console.log('formHost notifyInvisibleForms success');
}).catch((error) => { }).catch((error) => {
...@@ -430,7 +430,7 @@ enableFormsUpdate(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void& ...@@ -430,7 +430,7 @@ enableFormsUpdate(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void&
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.enableFormsUpdate(formId, (error, data) => { formHost.enableFormsUpdate(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
...@@ -463,7 +463,7 @@ enableFormsUpdate(formIds: Array&lt;string&gt;): Promise&lt;void&gt; ...@@ -463,7 +463,7 @@ enableFormsUpdate(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.enableFormsUpdate(formId).then(() => { formHost.enableFormsUpdate(formId).then(() => {
console.log('formHost enableFormsUpdate success'); console.log('formHost enableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
...@@ -491,7 +491,7 @@ disableFormsUpdate(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void ...@@ -491,7 +491,7 @@ disableFormsUpdate(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.disableFormsUpdate(formId, (error, data) => { formHost.disableFormsUpdate(formId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
...@@ -524,7 +524,7 @@ disableFormsUpdate(formIds: Array&lt;string&gt;): Promise&lt;void&gt; ...@@ -524,7 +524,7 @@ disableFormsUpdate(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = ['12400633174999288']; let formId = ['12400633174999288'];
formHost.disableFormsUpdate(formId).then(() => { formHost.disableFormsUpdate(formId).then(() => {
console.log('formHost disableFormsUpdate success'); console.log('formHost disableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
...@@ -549,7 +549,7 @@ isSystemReady(callback: AsyncCallback&lt;void&gt;): void ...@@ -549,7 +549,7 @@ isSystemReady(callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.isSystemReady((error, data) => { formHost.isSystemReady((error, data) => {
if (error.code) { if (error.code) {
console.log('formHost isSystemReady, error:' + JSON.stringify(error)); console.log('formHost isSystemReady, error:' + JSON.stringify(error));
...@@ -574,7 +574,7 @@ isSystemReady(): Promise&lt;void&gt; ...@@ -574,7 +574,7 @@ isSystemReady(): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formHost.isSystemReady().then(() => { formHost.isSystemReady().then(() => {
console.log('formHost isSystemReady success'); console.log('formHost isSystemReady success');
}).catch((error) => { }).catch((error) => {
...@@ -748,7 +748,7 @@ deleteInvalidForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;numb ...@@ -748,7 +748,7 @@ deleteInvalidForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;numb
**示例:** **示例:**
```ts ```ts
var formIds = new Array('12400633174999288', '12400633174999289'); let formIds = new Array('12400633174999288', '12400633174999289');
formHost.deleteInvalidForms(formIds, (error, data) => { formHost.deleteInvalidForms(formIds, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
...@@ -783,7 +783,7 @@ deleteInvalidForms(formIds: Array&lt;string&gt;): Promise&lt;number&gt; ...@@ -783,7 +783,7 @@ deleteInvalidForms(formIds: Array&lt;string&gt;): Promise&lt;number&gt;
**示例:** **示例:**
```ts ```ts
var formIds = new Array('12400633174999288', '12400633174999289'); let formIds = new Array('12400633174999288', '12400633174999289');
formHost.deleteInvalidForms(formIds).then((data) => { formHost.deleteInvalidForms(formIds).then((data) => {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
...@@ -811,7 +811,7 @@ acquireFormState(want: Want, callback: AsyncCallback&lt;formInfo.FormStateInfo&g ...@@ -811,7 +811,7 @@ acquireFormState(want: Want, callback: AsyncCallback&lt;formInfo.FormStateInfo&g
**示例:** **示例:**
```ts ```ts
var want = { let want = {
'deviceId': '', 'deviceId': '',
'bundleName': 'ohos.samples.FormApplication', 'bundleName': 'ohos.samples.FormApplication',
'abilityName': 'FormAbility', 'abilityName': 'FormAbility',
...@@ -855,7 +855,7 @@ acquireFormState(want: Want): Promise&lt;formInfo.FormStateInfo&gt; ...@@ -855,7 +855,7 @@ acquireFormState(want: Want): Promise&lt;formInfo.FormStateInfo&gt;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
'deviceId': '', 'deviceId': '',
'bundleName': 'ohos.samples.FormApplication', 'bundleName': 'ohos.samples.FormApplication',
'abilityName': 'FormAbility', 'abilityName': 'FormAbility',
...@@ -941,7 +941,7 @@ notifyFormsVisible(formIds: Array&lt;string&gt;, isVisible: boolean, callback: A ...@@ -941,7 +941,7 @@ notifyFormsVisible(formIds: Array&lt;string&gt;, isVisible: boolean, callback: A
**示例:** **示例:**
```ts ```ts
var formIds = new Array('12400633174999288', '12400633174999289'); let formIds = new Array('12400633174999288', '12400633174999289');
formHost.notifyFormsVisible(formIds, true, (error, data) => { formHost.notifyFormsVisible(formIds, true, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
...@@ -975,7 +975,7 @@ notifyFormsVisible(formIds: Array&lt;string&gt;, isVisible: boolean): Promise&lt ...@@ -975,7 +975,7 @@ notifyFormsVisible(formIds: Array&lt;string&gt;, isVisible: boolean): Promise&lt
**示例:** **示例:**
```ts ```ts
var formIds = new Array('12400633174999288', '12400633174999289'); let formIds = new Array('12400633174999288', '12400633174999289');
formHost.notifyFormsVisible(formIds, true).then(() => { formHost.notifyFormsVisible(formIds, true).then(() => {
console.log('formHost notifyFormsVisible success'); console.log('formHost notifyFormsVisible success');
}).catch((error) => { }).catch((error) => {
...@@ -1004,7 +1004,7 @@ notifyFormsEnableUpdate(formIds: Array&lt;string&gt;, isEnableUpdate: boolean, c ...@@ -1004,7 +1004,7 @@ notifyFormsEnableUpdate(formIds: Array&lt;string&gt;, isEnableUpdate: boolean, c
**示例:** **示例:**
```ts ```ts
var formIds = new Array('12400633174999288', '12400633174999289'); let formIds = new Array('12400633174999288', '12400633174999289');
formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
...@@ -1038,7 +1038,7 @@ notifyFormsEnableUpdate(formIds: Array&lt;string&gt;, isEnableUpdate: boolean): ...@@ -1038,7 +1038,7 @@ notifyFormsEnableUpdate(formIds: Array&lt;string&gt;, isEnableUpdate: boolean):
**示例:** **示例:**
```ts ```ts
var formIds = new Array('12400633174999288', '12400633174999289'); let formIds = new Array('12400633174999288', '12400633174999289');
formHost.notifyFormsEnableUpdate(formIds, true).then(() => { formHost.notifyFormsEnableUpdate(formIds, true).then(() => {
console.log('formHost notifyFormsEnableUpdate success'); console.log('formHost notifyFormsEnableUpdate success');
}).catch((error) => { }).catch((error) => {
...@@ -1066,8 +1066,8 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback&lt;void&gt;) ...@@ -1066,8 +1066,8 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback&lt;void&gt;)
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
var deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2';
formHost.shareForm(formId, deviceId, (error, data) => { formHost.shareForm(formId, deviceId, (error, data) => {
if (error.code) { if (error.code) {
console.log('formHost shareForm, error:' + JSON.stringify(error)); console.log('formHost shareForm, error:' + JSON.stringify(error));
...@@ -1101,8 +1101,8 @@ shareForm(formId: string, deviceId: string): Promise&lt;void&gt; ...@@ -1101,8 +1101,8 @@ shareForm(formId: string, deviceId: string): Promise&lt;void&gt;
**参数:** **参数:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
var deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2';
formHost.shareForm(formId, deviceId).then(() => { formHost.shareForm(formId, deviceId).then(() => {
console.log('formHost shareForm success'); console.log('formHost shareForm success');
}).catch((error) => { }).catch((error) => {
...@@ -1126,7 +1126,7 @@ notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callb ...@@ -1126,7 +1126,7 @@ notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callb
| deviceId | string | 是 | 远程设备标识。 | | deviceId | string | 是 | 远程设备标识。 |
```ts ```ts
var formIds = new Array('12400633174999288', '12400633174999289'); let formIds = new Array('12400633174999288', '12400633174999289');
formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => {
console.log('formHost shareForm success'); console.log('formHost shareForm success');
}).catch((error) => { }).catch((error) => {
......
...@@ -31,7 +31,7 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l ...@@ -31,7 +31,7 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => {
if (error.code) { if (error.code) {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
...@@ -63,7 +63,7 @@ setFormNextRefreshTime(formId: string, minute: number): Promise&lt;void&gt; ...@@ -63,7 +63,7 @@ setFormNextRefreshTime(formId: string, minute: number): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var formId = '12400633174999288'; let formId = '12400633174999288';
formProvider.setFormNextRefreshTime(formId, 5).then(() => { formProvider.setFormNextRefreshTime(formId, 5).then(() => {
console.log('formProvider setFormNextRefreshTime success'); console.log('formProvider setFormNextRefreshTime success');
}).catch((error) => { }).catch((error) => {
...@@ -91,7 +91,7 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call ...@@ -91,7 +91,7 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
var formId = '12400633174999288'; let formId = '12400633174999288';
let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
formProvider.updateForm(formId, obj, (error, data) => { formProvider.updateForm(formId, obj, (error, data) => {
if (error.code) { if (error.code) {
...@@ -125,7 +125,7 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr ...@@ -125,7 +125,7 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
var formId = '12400633174999288'; let formId = '12400633174999288';
let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
formProvider.updateForm(formId, obj).then(() => { formProvider.updateForm(formId, obj).then(() => {
console.log('formProvider updateForm success'); console.log('formProvider updateForm success');
...@@ -248,7 +248,7 @@ requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, ...@@ -248,7 +248,7 @@ requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData,
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
var want = { let want = {
abilityName: 'FormAbility', abilityName: 'FormAbility',
parameters: { parameters: {
'ohos.extra.param.key.form_dimension': 2, 'ohos.extra.param.key.form_dimension': 2,
...@@ -286,7 +286,7 @@ requestPublishForm(want: Want, callback: AsyncCallback&lt;string&gt;): void ...@@ -286,7 +286,7 @@ requestPublishForm(want: Want, callback: AsyncCallback&lt;string&gt;): void
**示例:** **示例:**
```ts ```ts
var want = { let want = {
abilityName: 'FormAbility', abilityName: 'FormAbility',
parameters: { parameters: {
'ohos.extra.param.key.form_dimension': 2, 'ohos.extra.param.key.form_dimension': 2,
...@@ -329,7 +329,7 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData ...@@ -329,7 +329,7 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData
**示例:** **示例:**
```ts ```ts
var want = { let want = {
abilityName: 'FormAbility', abilityName: 'FormAbility',
parameters: { parameters: {
'ohos.extra.param.key.form_dimension': 2, 'ohos.extra.param.key.form_dimension': 2,
...@@ -368,7 +368,7 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => { ...@@ -368,7 +368,7 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
} else { } else {
if (isSupported) { if (isSupported) {
var want = { let want = {
abilityName: 'FormAbility', abilityName: 'FormAbility',
parameters: { parameters: {
'ohos.extra.param.key.form_dimension': 2, 'ohos.extra.param.key.form_dimension': 2,
...@@ -409,7 +409,7 @@ isRequestPublishFormSupported(): Promise&lt;boolean&gt; ...@@ -409,7 +409,7 @@ isRequestPublishFormSupported(): Promise&lt;boolean&gt;
```ts ```ts
formProvider.isRequestPublishFormSupported().then((isSupported) => { formProvider.isRequestPublishFormSupported().then((isSupported) => {
if (isSupported) { if (isSupported) {
var want = { let want = {
abilityName: 'FormAbility', abilityName: 'FormAbility',
parameters: { parameters: {
'ohos.extra.param.key.form_dimension': 2, 'ohos.extra.param.key.form_dimension': 2,
......
...@@ -34,7 +34,7 @@ import Want from '@ohos.application.Want'; ...@@ -34,7 +34,7 @@ import Want from '@ohos.application.Want';
- 基础用法 - 基础用法
```ts ```ts
var want = { let want = {
'deviceId': '', // deviceId为空表示本设备 'deviceId': '', // deviceId为空表示本设备
'bundleName': 'com.extreme.test', 'bundleName': 'com.extreme.test',
'abilityName': 'MainAbility', 'abilityName': 'MainAbility',
...@@ -110,13 +110,13 @@ import Want from '@ohos.application.Want'; ...@@ -110,13 +110,13 @@ import Want from '@ohos.application.Want';
* 文件描述符(FD) * 文件描述符(FD)
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
var fd; let fd;
try { try {
fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); fd = fileio.openSync('/data/storage/el2/base/haps/pic.png');
} catch(e) { } catch(e) {
console.log('openSync fail:' + JSON.stringify(e)); console.log('openSync fail:' + JSON.stringify(e));
} }
var want = { let want = {
'deviceId': '', // deviceId为空表示本设备 'deviceId': '', // deviceId为空表示本设备
'bundleName': 'com.extreme.test', 'bundleName': 'com.extreme.test',
'abilityName': 'MainAbility', 'abilityName': 'MainAbility',
......
...@@ -101,9 +101,9 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { ...@@ -101,9 +101,9 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility {
window.loadContent('WindowExtAbility/pages/index1').then(() => { window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => { window.getProperties().then((pro) => {
console.log('WindowExtension ' + JSON.stringify(pro)); console.log('WindowExtension ' + JSON.stringify(pro));
}) });
window.show(); window.show();
}) });
} }
} }
......
...@@ -35,13 +35,13 @@ addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): void ...@@ -35,13 +35,13 @@ addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): void
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: 'abilityname', abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
...@@ -75,13 +75,13 @@ addAbilityMonitor(monitor: AbilityMonitor): Promise\<void>; ...@@ -75,13 +75,13 @@ addAbilityMonitor(monitor: AbilityMonitor): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: 'abilityname', abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
...@@ -112,13 +112,13 @@ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): v ...@@ -112,13 +112,13 @@ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): v
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: 'abilityname', abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
...@@ -154,13 +154,13 @@ removeAbilityMonitor(monitor: AbilityMonitor): Promise\<void>; ...@@ -154,13 +154,13 @@ removeAbilityMonitor(monitor: AbilityMonitor): Promise\<void>;
- 示例 - 示例
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: 'abilityname', abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
...@@ -191,13 +191,13 @@ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<UIAbility>) ...@@ -191,13 +191,13 @@ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<UIAbility>)
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: 'abilityname', abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
...@@ -227,14 +227,14 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCall ...@@ -227,14 +227,14 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCall
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var timeout = 100; let timeout = 100;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: 'abilityname', abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
...@@ -271,13 +271,13 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\<UIAbilit ...@@ -271,13 +271,13 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\<UIAbilit
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: 'abilityname', abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
...@@ -307,10 +307,10 @@ getAppContext(): Context; ...@@ -307,10 +307,10 @@ getAppContext(): Context;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
var context = abilityDelegator.getAppContext(); let context = abilityDelegator.getAppContext();
``` ```
...@@ -338,14 +338,14 @@ getAbilityState(ability: UIAbility): number; ...@@ -338,14 +338,14 @@ getAbilityState(ability: UIAbility): number;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
console.info('getCurrentTopAbility callback'); console.info('getCurrentTopAbility callback');
ability = data; ability = data;
var state = abilityDelegator.getAbilityState(ability); let state = abilityDelegator.getAbilityState(ability);
console.info('getAbilityState' + state); console.info('getAbilityState' + state);
}); });
``` ```
...@@ -369,8 +369,8 @@ getCurrentTopAbility(callback: AsyncCallback\<UIAbility>): void; ...@@ -369,8 +369,8 @@ getCurrentTopAbility(callback: AsyncCallback\<UIAbility>): void;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
...@@ -398,8 +398,8 @@ getCurrentTopAbility(): Promise\<UIAbility>; ...@@ -398,8 +398,8 @@ getCurrentTopAbility(): Promise\<UIAbility>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility().then((data : any) => { abilityDelegator.getCurrentTopAbility().then((data : any) => {
...@@ -428,8 +428,8 @@ startAbility(want: Want, callback: AsyncCallback\<void>): void; ...@@ -428,8 +428,8 @@ startAbility(want: Want, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var want = { let want = {
bundleName: 'bundleName', bundleName: 'bundleName',
abilityName: 'abilityName' abilityName: 'abilityName'
}; };
...@@ -465,8 +465,8 @@ startAbility(want: Want): Promise\<void>; ...@@ -465,8 +465,8 @@ startAbility(want: Want): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var want = { let want = {
bundleName: 'bundleName', bundleName: 'bundleName',
abilityName: 'abilityName' abilityName: 'abilityName'
}; };
...@@ -497,8 +497,8 @@ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\<void>): void; ...@@ -497,8 +497,8 @@ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
...@@ -535,8 +535,8 @@ doAbilityForeground(ability: UIAbility): Promise\<void>; ...@@ -535,8 +535,8 @@ doAbilityForeground(ability: UIAbility): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
...@@ -568,8 +568,8 @@ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\<void>): void; ...@@ -568,8 +568,8 @@ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
...@@ -606,8 +606,8 @@ doAbilityBackground(ability: UIAbility): Promise\<void>; ...@@ -606,8 +606,8 @@ doAbilityBackground(ability: UIAbility): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
...@@ -638,8 +638,8 @@ printSync(msg: string): void; ...@@ -638,8 +638,8 @@ printSync(msg: string): void;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.printSync(msg); abilityDelegator.printSync(msg);
...@@ -665,8 +665,8 @@ print(msg: string, callback: AsyncCallback\<void>): void; ...@@ -665,8 +665,8 @@ print(msg: string, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.print(msg, (err : any) => { abilityDelegator.print(msg, (err : any) => {
...@@ -699,8 +699,8 @@ print(msg: string): Promise\<void>; ...@@ -699,8 +699,8 @@ print(msg: string): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.print(msg).then(() => { abilityDelegator.print(msg).then(() => {
...@@ -728,8 +728,8 @@ executeShellCommand(cmd: string, callback: AsyncCallback\<ShellCmdResult>): void ...@@ -728,8 +728,8 @@ executeShellCommand(cmd: string, callback: AsyncCallback\<ShellCmdResult>): void
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var cmd = 'cmd'; let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => {
...@@ -758,9 +758,9 @@ executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\<S ...@@ -758,9 +758,9 @@ executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\<S
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var cmd = 'cmd'; let cmd = 'cmd';
var timeout = 100; let timeout = 100;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => {
...@@ -794,9 +794,9 @@ executeShellCommand(cmd: string, timeoutSecs?: number): Promise\<ShellCmdResult> ...@@ -794,9 +794,9 @@ executeShellCommand(cmd: string, timeoutSecs?: number): Promise\<ShellCmdResult>
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var cmd = 'cmd'; let cmd = 'cmd';
var timeout = 100; let timeout = 100;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => {
...@@ -825,8 +825,8 @@ finishTest(msg: string, code: number, callback: AsyncCallback\<void>): void; ...@@ -825,8 +825,8 @@ finishTest(msg: string, code: number, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.finishTest(msg, 0, (err : any) => { abilityDelegator.finishTest(msg, 0, (err : any) => {
...@@ -860,8 +860,8 @@ finishTest(msg: string, code: number): Promise\<void>; ...@@ -860,8 +860,8 @@ finishTest(msg: string, code: number): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.finishTest(msg, 0).then(() => { abilityDelegator.finishTest(msg, 0).then(() => {
...@@ -887,9 +887,9 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<vo ...@@ -887,9 +887,9 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<vo
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
srcEntrance: 'srcEntrance', srcEntrance: 'srcEntrance',
}; };
...@@ -925,9 +925,9 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>; ...@@ -925,9 +925,9 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
srcEntrance: 'srcEntrance', srcEntrance: 'srcEntrance',
}; };
...@@ -956,9 +956,9 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ ...@@ -956,9 +956,9 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
srcEntrance: 'srcEntrance', srcEntrance: 'srcEntrance',
}; };
...@@ -994,9 +994,9 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>; ...@@ -994,9 +994,9 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
srcEntrance: 'srcEntrance', srcEntrance: 'srcEntrance',
}; };
...@@ -1025,13 +1025,13 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<A ...@@ -1025,13 +1025,13 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<A
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
srcEntrance: 'srcEntrance', srcEntrance: 'srcEntrance',
}; };
...@@ -1066,13 +1066,13 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise ...@@ -1066,13 +1066,13 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
srcEntrance: 'srcEntrance', srcEntrance: 'srcEntrance',
}; };
...@@ -1102,14 +1102,14 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: ...@@ -1102,14 +1102,14 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback:
**示例:** **示例:**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var timeout = 100; let timeout = 100;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
srcEntrance: 'srcEntrance', srcEntrance: 'srcEntrance',
}; };
......
...@@ -50,7 +50,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void ...@@ -50,7 +50,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.example.formstartability', bundleName: 'com.example.formstartability',
abilityName: 'MainAbility', abilityName: 'MainAbility',
...@@ -94,7 +94,7 @@ startAbility(want: Want): Promise&lt;void&gt; ...@@ -94,7 +94,7 @@ startAbility(want: Want): Promise&lt;void&gt;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.example.formstartability', bundleName: 'com.example.formstartability',
abilityName: 'MainAbility', abilityName: 'MainAbility',
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
**示例:** **示例:**
```ts ```ts
import appManager from '@ohos.application.appManager' import appManager from '@ohos.application.appManager';
let applicationStateObserver = { let applicationStateObserver = {
onForegroundApplicationChanged(appStateData) { onForegroundApplicationChanged(appStateData) {
...@@ -38,6 +38,6 @@ let applicationStateObserver = { ...@@ -38,6 +38,6 @@ let applicationStateObserver = {
console.log('onProcessStateChanged processData.isContinuousTask : ' + JSON.stringify(processData.isContinuousTask)); console.log('onProcessStateChanged processData.isContinuousTask : ' + JSON.stringify(processData.isContinuousTask));
console.log('onProcessStateChanged processData.isKeepAlive : ' + JSON.stringify(processData.isKeepAlive)); console.log('onProcessStateChanged processData.isKeepAlive : ' + JSON.stringify(processData.isKeepAlive));
} }
} };
let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver);
``` ```
\ No newline at end of file
...@@ -66,7 +66,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void; ...@@ -66,7 +66,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
bundleName: 'com.example.myapp', bundleName: 'com.example.myapp',
abilityName: 'MyAbility' abilityName: 'MyAbility'
}; };
...@@ -138,12 +138,12 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void& ...@@ -138,12 +138,12 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -218,11 +218,11 @@ startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;; ...@@ -218,11 +218,11 @@ startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
bundleName: 'com.example.myapp', bundleName: 'com.example.myapp',
abilityName: 'MyAbility' abilityName: 'MyAbility'
}; };
var options = { let options = {
windowMode: 0, windowMode: 0,
}; };
...@@ -295,7 +295,7 @@ startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): ...@@ -295,7 +295,7 @@ startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;):
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
...@@ -371,12 +371,12 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback ...@@ -371,12 +371,12 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var options = { let options = {
windowMode: 0, windowMode: 0,
}; };
...@@ -457,11 +457,11 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityRes ...@@ -457,11 +457,11 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityRes
**示例:** **示例:**
```ts ```ts
var want = { let want = {
bundleName: 'com.example.myapp', bundleName: 'com.example.myapp',
abilityName: 'MyAbility' abilityName: 'MyAbility'
}; };
var options = { let options = {
windowMode: 0, windowMode: 0,
}; };
...@@ -531,12 +531,12 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC ...@@ -531,12 +531,12 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => {
...@@ -607,13 +607,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp ...@@ -607,13 +607,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -691,13 +691,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO ...@@ -691,13 +691,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -756,7 +756,7 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void; ...@@ -756,7 +756,7 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
...@@ -816,7 +816,7 @@ startServiceExtensionAbility(want: Want): Promise\<void>; ...@@ -816,7 +816,7 @@ startServiceExtensionAbility(want: Want): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
...@@ -877,12 +877,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: ...@@ -877,12 +877,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => {
...@@ -942,12 +942,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ ...@@ -942,12 +942,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startServiceExtensionAbilityWithAccount(want, accountId) this.context.startServiceExtensionAbilityWithAccount(want, accountId)
...@@ -1000,7 +1000,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void; ...@@ -1000,7 +1000,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
...@@ -1057,7 +1057,7 @@ stopServiceExtensionAbility(want: Want): Promise\<void>; ...@@ -1057,7 +1057,7 @@ stopServiceExtensionAbility(want: Want): Promise\<void>;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
...@@ -1119,12 +1119,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: ...@@ -1119,12 +1119,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => {
...@@ -1181,12 +1181,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< ...@@ -1181,12 +1181,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.stopServiceExtensionAbilityWithAccount(want, accountId) this.context.stopServiceExtensionAbilityWithAccount(want, accountId)
...@@ -1315,13 +1315,13 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;voi ...@@ -1315,13 +1315,13 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;voi
**示例:** **示例:**
```ts ```ts
var want = { let want = {
bundleName: 'com.extreme.myapplication', bundleName: 'com.extreme.myapplication',
abilityName: 'SecondAbility' abilityName: 'SecondAbility'
} }
var resultCode = 100; let resultCode = 100;
// 返回给接口调用方AbilityResult信息 // 返回给接口调用方AbilityResult信息
var abilityResult = { let abilityResult = {
want, want,
resultCode resultCode
} }
...@@ -1380,13 +1380,13 @@ terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;; ...@@ -1380,13 +1380,13 @@ terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
bundleName: 'com.extreme.myapplication', bundleName: 'com.extreme.myapplication',
abilityName: 'SecondAbility' abilityName: 'SecondAbility'
} }
var resultCode = 100; let resultCode = 100;
// 返回给接口调用方AbilityResult信息 // 返回给接口调用方AbilityResult信息
var abilityResult = { let abilityResult = {
want, want,
resultCode resultCode
} }
...@@ -1445,18 +1445,18 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; ...@@ -1445,18 +1445,18 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var options = { let options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') } onFailed(code) { console.log('----------- onFailed -----------') }
} }
var connection = null; let connection = null;
try { try {
connection = this.context.connectServiceExtensionAbility(want, options); connection = this.context.connectServiceExtensionAbility(want, options);
} catch (paramError) { } catch (paramError) {
...@@ -1509,19 +1509,19 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options ...@@ -1509,19 +1509,19 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') } onFailed(code) { console.log('----------- onFailed -----------') }
} }
var connection = null; let connection = null;
try { try {
connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options);
} catch (paramError) { } catch (paramError) {
...@@ -1568,7 +1568,7 @@ disconnectServiceExtensionAbility(connection: number): Promise\<void>; ...@@ -1568,7 +1568,7 @@ disconnectServiceExtensionAbility(connection: number): Promise\<void>;
```ts ```ts
// connection为connectServiceExtensionAbility中的返回值 // connection为connectServiceExtensionAbility中的返回值
var connection = 1; let connection = 1;
try { try {
this.context.disconnectServiceExtensionAbility(connection) this.context.disconnectServiceExtensionAbility(connection)
...@@ -1620,7 +1620,7 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\<vo ...@@ -1620,7 +1620,7 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\<vo
```ts ```ts
// connection为connectServiceExtensionAbility中的返回值 // connection为connectServiceExtensionAbility中的返回值
var connection = 1; let connection = 1;
try { try {
this.context.disconnectServiceExtensionAbility(connection, (error) => { this.context.disconnectServiceExtensionAbility(connection, (error) => {
...@@ -1670,10 +1670,10 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;; ...@@ -1670,10 +1670,10 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
后台启动: 后台启动:
```ts ```ts
var caller = undefined; let caller = undefined;
// 后台启动Ability,不配置parameters // 后台启动Ability,不配置parameters
var wantBackground = { let wantBackground = {
bundleName: 'com.example.myservice', bundleName: 'com.example.myservice',
moduleName: 'entry', moduleName: 'entry',
abilityName: 'MainAbility', abilityName: 'MainAbility',
...@@ -1701,10 +1701,10 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;; ...@@ -1701,10 +1701,10 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
前台启动: 前台启动:
```ts ```ts
var caller = undefined; let caller = undefined;
// 前台启动Ability,将parameters中的'ohos.aafwk.param.callAbilityToForeground'配置为true // 前台启动Ability,将parameters中的'ohos.aafwk.param.callAbilityToForeground'配置为true
var wantForeground = { let wantForeground = {
bundleName: 'com.example.myservice', bundleName: 'com.example.myservice',
moduleName: 'entry', moduleName: 'entry',
abilityName: 'MainAbility', abilityName: 'MainAbility',
...@@ -1780,12 +1780,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< ...@@ -1780,12 +1780,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startAbilityWithAccount(want, accountId, (error) => { this.context.startAbilityWithAccount(want, accountId, (error) => {
...@@ -1855,13 +1855,13 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca ...@@ -1855,13 +1855,13 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -1932,13 +1932,13 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): ...@@ -1932,13 +1932,13 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
**示例:** **示例:**
```ts ```ts
var want = { let want = {
deviceId: '', deviceId: '',
bundleName: 'com.extreme.test', bundleName: 'com.extreme.test',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -1978,7 +1978,7 @@ requestPermissionsFromUser(permissions: Array&lt;string&gt;, requestCallback: As ...@@ -1978,7 +1978,7 @@ requestPermissionsFromUser(permissions: Array&lt;string&gt;, requestCallback: As
**示例:** **示例:**
```ts ```ts
var permissions=['com.example.permission'] let permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions,(result) => { this.context.requestPermissionsFromUser(permissions,(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
}); });
...@@ -2009,7 +2009,7 @@ requestPermissionsFromUser(permissions: Array&lt;string&gt;) : Promise&lt;Permis ...@@ -2009,7 +2009,7 @@ requestPermissionsFromUser(permissions: Array&lt;string&gt;) : Promise&lt;Permis
**示例:** **示例:**
```ts ```ts
var permissions=['com.example.permission'] let permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions).then((data) => { this.context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success:' + JSON.stringify(data)); console.log('success:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
...@@ -2093,9 +2093,9 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\<void>): void; ...@@ -2093,9 +2093,9 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\<void>): void;
```ts ```ts
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
var imagePixelMap; let imagePixelMap;
var color = new ArrayBuffer(0); let color = new ArrayBuffer(0);
var initializationOptions = { let initializationOptions = {
size: { size: {
height: 100, height: 100,
width: 100 width: 100
...@@ -2140,9 +2140,9 @@ setMissionIcon(icon: image.PixelMap): Promise\<void>; ...@@ -2140,9 +2140,9 @@ setMissionIcon(icon: image.PixelMap): Promise\<void>;
```ts ```ts
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
var imagePixelMap; let imagePixelMap;
var color = new ArrayBuffer(0); let color = new ArrayBuffer(0);
var initializationOptions = { let initializationOptions = {
size: { size: {
height: 100, height: 100,
width: 100 width: 100
...@@ -2180,7 +2180,7 @@ restoreWindowStage(localStorage: LocalStorage) : void; ...@@ -2180,7 +2180,7 @@ restoreWindowStage(localStorage: LocalStorage) : void;
**示例:** **示例:**
```ts ```ts
var storage = new LocalStorage(); let storage = new LocalStorage();
this.context.restoreWindowStage(storage); this.context.restoreWindowStage(storage);
``` ```
...@@ -2201,6 +2201,6 @@ isTerminating(): boolean; ...@@ -2201,6 +2201,6 @@ isTerminating(): boolean;
**示例:** **示例:**
```ts ```ts
var isTerminating = this.context.isTerminating(); let isTerminating = this.context.isTerminating();
console.log('ability state :' + isTerminating); console.log('ability state :' + isTerminating);
``` ```
\ No newline at end of file
...@@ -46,11 +46,11 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void& ...@@ -46,11 +46,11 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&
**示例:** **示例:**
```ts ```ts
var want = { let want = {
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var options = { let options = {
windowMode: 102 windowMode: 102
}; };
...@@ -96,11 +96,11 @@ startAbility(want: Want, options?: StartOptions): Promise\<void> ...@@ -96,11 +96,11 @@ startAbility(want: Want, options?: StartOptions): Promise\<void>
**示例:** **示例:**
```ts ```ts
var want = { let want = {
bundleName: 'com.example.myapp', bundleName: 'com.example.myapp',
abilityName: 'MainAbility' abilityName: 'MainAbility'
}; };
var options = { let options = {
windowMode: 102, windowMode: 102,
}; };
......
# @ohos.multimedia.medialibrary (媒体库管理) # @ohos.multimedia.medialibrary (媒体库管理)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
> 该组件从API Version 6开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 6开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 导入模块 ## 导入模块
...@@ -33,6 +33,7 @@ getMediaLibrary(context: Context): MediaLibrary ...@@ -33,6 +33,7 @@ getMediaLibrary(context: Context): MediaLibrary
**示例:(从API Version 9开始)** **示例:(从API Version 9开始)**
```ts ```ts
// 获取mediaLibrary实例,后续用到此实例均采用此处获取的实例
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
``` ```
...@@ -91,46 +92,59 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileRe ...@@ -91,46 +92,59 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileRe
**示例:** **示例:**
```js ```js
let fileKeyObj = mediaLibrary.FileKey; async function example() {
let imageType = mediaLibrary.MediaType.IMAGE; let fileKeyObj = mediaLibrary.FileKey;
let imagesFetchOp = { let imageType = mediaLibrary.MediaType.IMAGE;
// 创建文件获取选项,此处参数为获取image类型的文件资源
let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
}; };
media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { // 获取文件资源,使用callback方式返回异步结果
media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
// 判断获取的文件资源的检索结果集是否为undefined,若为undefined则接口调用失败
if (fetchFileResult == undefined) { if (fetchFileResult == undefined) {
console.error('Failed to get fetchFileResult: ' + error); console.error('get fetchFileResult failed with error: ' + error);
return; return;
} }
// 获取文件检索结果集中的总数
const count = fetchFileResult.getCount(); const count = fetchFileResult.getCount();
// 判断结果集中的数量是否小于0,小于0时表示接口调用失败
if (count < 0) { if (count < 0) {
console.error('Failed to get count from fetchFileResult: count: ' + count); console.error('get count from fetchFileResult failed, count: ' + count);
return; return;
} }
// 判断结果集中的数量是否等于0,等于0时表示接口调用成功,但是检索结果集为空,请检查文件获取选项参数配置是否有误和设备中是否存在相应文件
if (count == 0) { if (count == 0) {
console.info('The count of fetchFileResult is zero'); console.info('The count of fetchFileResult is zero');
return; return;
} }
console.info('Get fetchFileResult successfully, count: ' + count);
console.info('Get fetchFileResult success, count: ' + count); // 获取文件检索结果集中的第一个资源,使用callback方式返回异步结果
fetchFileResult.getFirstObject((err, fileAsset) => { fetchFileResult.getFirstObject((error, fileAsset) => {
// 检查获取的第一个资源是否为undefined,若为undefined则接口调用失败
if (fileAsset == undefined) { if (fileAsset == undefined) {
console.error('Failed to get first object: ' + err); console.error('get first object failed with error: ' + error);
return; return;
} }
console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
// 调用 getNextObject 接口获取下一个资源,直到最后一个
for (let i = 1; i < count; i++) { for (let i = 1; i < count; i++) {
fetchFileResult.getNextObject((err, fileAsset) => { fetchFileResult.getNextObject((error, fileAsset) => {
if (fileAsset == undefined) { if (fileAsset == undefined) {
console.error('Failed to get next object: ' + err); console.error('get next object failed with error: ' + error);
return; return;
} }
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}) })
} }
}); });
}); // 释放FetchFileResult实例并使其失效。无法调用其他方法
fetchFileResult.close();
});
}
``` ```
### getFileAssets<sup>7+</sup> ### getFileAssets<sup>7+</sup>
getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt; getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt;
...@@ -156,38 +170,51 @@ getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt; ...@@ -156,38 +170,51 @@ getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt;
**示例:** **示例:**
```js ```js
let fileKeyObj = mediaLibrary.FileKey; async function example() {
let imageType = mediaLibrary.MediaType.IMAGE; let fileKeyObj = mediaLibrary.FileKey;
let imagesFetchOp = { let imageType = mediaLibrary.MediaType.IMAGE;
// 创建文件获取选项,此处参数为获取image类型的文件资源
let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
}; };
media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) { // 获取文件资源,使用Promise方式返回结果
media.getFileAssets(imagesFetchOp).then((fetchFileResult) => {
// 获取文件检索结果集中的总数
const count = fetchFileResult.getCount(); const count = fetchFileResult.getCount();
// 判断结果集中的数量是否小于0,小于0时表示接口调用失败
if (count < 0) { if (count < 0) {
console.error('Failed to get count from fetchFileResult: count: ' + count); console.error('get count from fetchFileResult failed, count: ' + count);
return; return;
} }
// 判断结果集中的数量是否等于0,等于0时表示接口调用成功,但是检索结果集为空,请检查文件获取选项参数配置是否有误和设备中是否存在相应文件
if (count == 0) { if (count == 0) {
console.info('The count of fetchFileResult is zero'); console.info('The count of fetchFileResult is zero');
return; return;
} }
console.info('Get fetchFileResult success, count: ' + count); console.info('Get fetchFileResult successfully, count: ' + count);
fetchFileResult.getFirstObject().then(function(fileAsset) { // 获取文件检索结果集中的第一个资源,使用Promise方式返回异步结果
console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); fetchFileResult.getFirstObject().then((fileAsset) => {
console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
// 调用 getNextObject 接口获取下一个资源,直到最后一个
for (let i = 1; i < count; i++) { for (let i = 1; i < count; i++) {
fetchFileResult.getNextObject().then(function(fileAsset) { fetchFileResult.getNextObject().then((fileAsset) => {
console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}).catch(function(err) { }).catch((error) => {
console.error('Failed to get next object: ' + err); console.error('get next object failed with error: ' + error);
}) })
} }
}).catch(function(err) { }).catch((error) => {
console.error('Failed to get first object: ' + err); // 调用getFirstObject接口失败
console.error('get first object failed with error: ' + error);
}); });
}).catch(function(err){ // 释放FetchFileResult实例并使其失效。无法调用其他方法
console.error("Failed to get file assets: " + err); fetchFileResult.close();
}); }).catch((error) => {
// 调用getFileAssets接口失败
console.error('get file assets failed with error: ' + error);
});
}
``` ```
### on<sup>8+</sup> ### on<sup>8+</sup>
...@@ -231,7 +258,7 @@ off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange ...@@ -231,7 +258,7 @@ off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange
```js ```js
media.off('imageChange', () => { media.off('imageChange', () => {
// stop listening success // stop listening successfully
}) })
``` ```
...@@ -262,11 +289,11 @@ async function example() { ...@@ -262,11 +289,11 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => { media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (error, fileAsset) => {
if (fileAsset != undefined) { if (fileAsset != undefined) {
console.info('createAsset successfully, message'); console.info('createAsset successfully, message');
} else { } else {
console.error('createAsset failed, message = ' + err); console.error('createAsset failed with error: ' + error);
} }
}); });
} }
...@@ -306,8 +333,8 @@ async function example() { ...@@ -306,8 +333,8 @@ async function example() {
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => { media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => {
console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset)); console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset));
}).catch((err) => { }).catch((error) => {
console.error('createAsset failed, message = ' + err); console.error('createAsset failed with error: ' + error);
}); });
} }
``` ```
...@@ -348,14 +375,15 @@ async function example() { ...@@ -348,14 +375,15 @@ async function example() {
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset == undefined) {
console.error('asset not exist') console.error('asset not exist');
return return;
} }
media.deleteAsset(asset.uri).then(() => { media.deleteAsset(asset.uri).then(() => {
console.info("deleteAsset successfully"); console.info('deleteAsset successfully');
}).catch((err) => { }).catch((error) => {
console.error("deleteAsset failed with error:"+ err); console.error('deleteAsset failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -390,16 +418,17 @@ async function example() { ...@@ -390,16 +418,17 @@ async function example() {
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset == undefined) {
console.error('asset not exist') console.error('asset not exist');
return return;
} }
media.deleteAsset(asset.uri, (err) => { media.deleteAsset(asset.uri, (error) => {
if (err != undefined) { if (error != undefined) {
console.info("deleteAsset successfully"); console.error('deleteAsset failed with error: ' + error);
} else { } else {
console.error("deleteAsset failed with error:"+ err); console.info('deleteAsset successfully');
} }
}); });
fetchFileResult.close();
} }
``` ```
...@@ -422,11 +451,11 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;): ...@@ -422,11 +451,11 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;):
```js ```js
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { media.getPublicDirectory(DIR_CAMERA, (error, dicResult) => {
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed'); console.info('getPublicDirectory DIR_CAMERA successfully');
} else { } else {
console.error('mediaLibraryTest : getPublicDirectory failed'); console.error('getPublicDirectory DIR_CAMERA failed with error: ' + error);
} }
}); });
``` ```
...@@ -456,12 +485,15 @@ getPublicDirectory(type: DirectoryType): Promise&lt;string&gt; ...@@ -456,12 +485,15 @@ getPublicDirectory(type: DirectoryType): Promise&lt;string&gt;
```js ```js
async function example() { async function example() {
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA); media.getPublicDirectory(DIR_CAMERA).then((dicResult) => {
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
console.info('MediaLibraryTest : getPublicDirectory'); console.info('getPublicDirectory DIR_CAMERA successfully');
} else { } else {
console.error('MediaLibraryTest : getPublicDirectory failed'); console.error('getPublicDirectory DIR_CAMERA failed');
} }
}).catch((error) => {
console.error('getPublicDirectory failed with error: ' + error);
});
} }
``` ```
...@@ -485,19 +517,19 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array&lt;Album&gt; ...@@ -485,19 +517,19 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array&lt;Album&gt;
**示例:** **示例:**
```js ```js
let AlbumNoArgsfetchOp = { async function example() {
let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
}; };
media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => {
if (albumList != undefined) { if (albumList != undefined) {
const album = albumList[0]; console.info('getAlbums successfully: ' + JSON.stringify(albumList));
console.info('album.albumName = ' + album.albumName);
console.info('album.count = ' + album.count);
} else { } else {
console.error('getAlbum fail, message = ' + err); console.error('getAlbums failed with error: ' + error);
} }
}) })
}
``` ```
### getAlbums<sup>7+</sup> ### getAlbums<sup>7+</sup>
...@@ -525,15 +557,17 @@ getAlbums(options: MediaFetchOptions): Promise<Array&lt;Album&gt;> ...@@ -525,15 +557,17 @@ getAlbums(options: MediaFetchOptions): Promise<Array&lt;Album&gt;>
**示例:** **示例:**
```js ```js
let AlbumNoArgsfetchOp = { async function example() {
let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
}; };
media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => {
console.info("getAlbums successfully:"+ JSON.stringify(albumList)); console.info('getAlbums successfully: ' + JSON.stringify(albumList));
}).catch(function(err){ }).catch((error) => {
console.error("getAlbums failed with error: " + err); console.error('getAlbums failed with error: ' + error);
}); });
}
``` ```
### release<sup>8+</sup> ### release<sup>8+</sup>
...@@ -549,12 +583,12 @@ release(callback: AsyncCallback&lt;void&gt;): void ...@@ -549,12 +583,12 @@ release(callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------- | | -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调表示成功还是失败 | | callback | AsyncCallback&lt;void&gt; | 是 | 无返回值 |
**示例:** **示例:**
```js ```js
media.release((err) => { media.release(() => {
// do something // do something
}); });
``` ```
...@@ -601,16 +635,16 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback&lt;string&gt;) ...@@ -601,16 +635,16 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback&lt;string&gt;)
```js ```js
let option = { let option = {
src : "/data/storage/el2/base/haps/entry/image.png", src : '/data/storage/el2/base/haps/entry/image.png',
mimeType : "image/*", mimeType : 'image/*',
relativePath : "Pictures/" relativePath : 'Pictures/'
}; };
mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { mediaLibrary.getMediaLibrary().storeMediaAsset(option, (error, value) => {
if (err) { if (error) {
console.error("An error occurred when storing media resources."); console.error('storeMediaAsset failed with error: ' + error);
return; return;
} }
console.info("Media resources stored. "); console.info('Media resources stored. ');
// Obtain the URI that stores media resources. // Obtain the URI that stores media resources.
}); });
``` ```
...@@ -642,15 +676,15 @@ storeMediaAsset(option: MediaAssetOption): Promise&lt;string&gt; ...@@ -642,15 +676,15 @@ storeMediaAsset(option: MediaAssetOption): Promise&lt;string&gt;
```js ```js
let option = { let option = {
src : "/data/storage/el2/base/haps/entry/image.png", src : '/data/storage/el2/base/haps/entry/image.png',
mimeType : "image/*", mimeType : 'image/*',
relativePath : "Pictures/" relativePath : 'Pictures/'
}; };
mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
console.info("Media resources stored."); console.info('Media resources stored.');
// Obtain the URI that stores media resources. // Obtain the URI that stores media resources.
}).catch((err) => { }).catch((error) => {
console.error("An error occurred when storing media resources."); console.error('storeMediaAsset failed with error: ' + error);
}); });
``` ```
...@@ -669,7 +703,7 @@ startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCal ...@@ -669,7 +703,7 @@ startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCal
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------- | ---- | ---------------------------------------- |
| images | Array&lt;string&gt; | 是 | 预览的图片URI("https://","datashare://")列表。 | | images | Array&lt;string&gt; | 是 | 预览的图片URI('https://','datashare://')列表。 |
| index | number | 是 | 开始显示的图片序号。 | | index | number | 是 | 开始显示的图片序号。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 图片预览回调,失败时返回错误信息。 | | callback | AsyncCallback&lt;void&gt; | 是 | 图片预览回调,失败时返回错误信息。 |
...@@ -677,22 +711,22 @@ startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCal ...@@ -677,22 +711,22 @@ startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCal
```js ```js
let images = [ let images = [
"datashare:///media/xxxx/2", 'datashare:///media/xxxx/2',
"datashare:///media/xxxx/3" 'datashare:///media/xxxx/3'
]; ];
/* 网络图片使用方式 /* 网络图片使用方式
let images = [ let images = [
"https://media.xxxx.com/image1.jpg", 'https://media.xxxx.com/image1.jpg',
"https://media.xxxx.com/image2.jpg" 'https://media.xxxx.com/image2.jpg'
]; ];
*/ */
let index = 1; let index = 1;
mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => {
if (err) { if (error) {
console.error("An error occurred when previewing the images."); console.error('startImagePreview failed with error: ' + error);
return; return;
} }
console.info("Succeeded in previewing the images."); console.info('Succeeded in previewing the images.');
}); });
``` ```
...@@ -711,28 +745,28 @@ startImagePreview(images: Array&lt;string&gt;, callback: AsyncCallback&lt;void&g ...@@ -711,28 +745,28 @@ startImagePreview(images: Array&lt;string&gt;, callback: AsyncCallback&lt;void&g
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------- | ---- | ---------------------------------------- |
| images | Array&lt;string&gt; | 是 | 预览的图片URI("https://","datashare://")列表。 | | images | Array&lt;string&gt; | 是 | 预览的图片URI('https://','datashare://')列表。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 图片预览回调,失败时返回错误信息。 | | callback | AsyncCallback&lt;void&gt; | 是 | 图片预览回调,失败时返回错误信息。 |
**示例:** **示例:**
```js ```js
let images = [ let images = [
"datashare:///media/xxxx/2", 'datashare:///media/xxxx/2',
"datashare:///media/xxxx/3" 'datashare:///media/xxxx/3'
]; ];
/* 网络图片使用方式 /* 网络图片使用方式
let images = [ let images = [
"https://media.xxxx.com/image1.jpg", 'https://media.xxxx.com/image1.jpg',
"https://media.xxxx.com/image2.jpg" 'https://media.xxxx.com/image2.jpg'
]; ];
*/ */
mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => {
if (err) { if (error) {
console.error("An error occurred when previewing the images."); console.error('startImagePreview failed with error: ' + error);
return; return;
} }
console.info("Succeeded in previewing the images."); console.info('Succeeded in previewing the images.');
}); });
``` ```
...@@ -751,7 +785,7 @@ startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void& ...@@ -751,7 +785,7 @@ startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void&
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------- | ---- | ---------------------------------------- | | ------ | ------------------- | ---- | ---------------------------------------- |
| images | Array&lt;string&gt; | 是 | 预览的图片URI("https://","datashare://")列表。 | | images | Array&lt;string&gt; | 是 | 预览的图片URI('https://','datashare://')列表。 |
| index | number | 否 | 开始显示的图片序号,不选择时默认为0。 | | index | number | 否 | 开始显示的图片序号,不选择时默认为0。 |
**返回值:** **返回值:**
...@@ -764,20 +798,20 @@ startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void& ...@@ -764,20 +798,20 @@ startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void&
```js ```js
let images = [ let images = [
"datashare:///media/xxxx/2", 'datashare:///media/xxxx/2',
"datashare:///media/xxxx/3" 'datashare:///media/xxxx/3'
]; ];
/* 网络图片使用方式 /* 网络图片使用方式
let images = [ let images = [
"https://media.xxxx.com/image1.jpg", 'https://media.xxxx.com/image1.jpg',
"https://media.xxxx.com/image2.jpg" 'https://media.xxxx.com/image2.jpg'
]; ];
*/ */
let index = 1; let index = 1;
mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => {
console.info("Succeeded in previewing the images."); console.info('Succeeded in previewing the images.');
}).catch((err) => { }).catch((error) => {
console.error("An error occurred when previewing the images."); console.error('startImagePreview failed with error: ' + error);
}); });
``` ```
...@@ -803,15 +837,15 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback&lt;Array&lt; ...@@ -803,15 +837,15 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback&lt;Array&lt;
```js ```js
let option : mediaLibrary.MediaSelectOption = { let option : mediaLibrary.MediaSelectOption = {
type : "media", type : 'media',
count : 2 count : 2
}; };
mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, value) => {
if (err) { if (error) {
console.error("An error occurred when selecting media resources."); console.error('startMediaSelect failed with error: ' + error);
return; return;
} }
console.info("Media resources selected."); console.info('Media resources selected.');
// Obtain the media selection value. // Obtain the media selection value.
}); });
``` ```
...@@ -843,14 +877,14 @@ startMediaSelect(option: MediaSelectOption): Promise&lt;Array&lt;string&gt;&gt; ...@@ -843,14 +877,14 @@ startMediaSelect(option: MediaSelectOption): Promise&lt;Array&lt;string&gt;&gt;
```js ```js
let option : mediaLibrary.MediaSelectOption = { let option : mediaLibrary.MediaSelectOption = {
type : "media", type : 'media',
count : 2 count : 2
}; };
mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
console.info("Media resources selected."); console.info('Media resources selected.');
// Obtain the media selection value. // Obtain the media selection value.
}).catch((err) => { }).catch((error) => {
console.error("An error occurred when selecting media resources."); console.error('startMediaSelect failed with error: ' + error);
}); });
``` ```
...@@ -878,14 +912,12 @@ getActivePeers(): Promise\<Array\<PeerInfo>>; ...@@ -878,14 +912,12 @@ getActivePeers(): Promise\<Array\<PeerInfo>>;
async function example() { async function example() {
media.getActivePeers().then((devicesInfo) => { media.getActivePeers().then((devicesInfo) => {
if (devicesInfo != undefined) { if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + JSON.stringify(devicesInfo));
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else { } else {
console.info('get distributed info is undefined!') console.info('get distributed info is undefined!');
} }
}).catch((err) => { }).catch((error) => {
console.error("get distributed info failed with error:" + err); console.error('get distributed info failed with error: ' + error);
}); });
} }
``` ```
...@@ -912,15 +944,13 @@ getActivePeers(callback: AsyncCallback\<Array\<PeerInfo>>): void; ...@@ -912,15 +944,13 @@ getActivePeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
```js ```js
async function example() { async function example() {
media.getActivePeers((err, devicesInfo) => { media.getActivePeers((error, devicesInfo) => {
if (devicesInfo != undefined) { if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + JSON.stringify(devicesInfo));
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else { } else {
console.error('get distributed fail, message = ' + err) console.error('get distributed failed with error: ' + error);
} }
}) });
} }
``` ```
...@@ -949,14 +979,12 @@ getAllPeers(): Promise\<Array\<PeerInfo>>; ...@@ -949,14 +979,12 @@ getAllPeers(): Promise\<Array\<PeerInfo>>;
async function example() { async function example() {
media.getAllPeers().then((devicesInfo) => { media.getAllPeers().then((devicesInfo) => {
if (devicesInfo != undefined) { if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + JSON.stringify(devicesInfo));
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else { } else {
console.info('get distributed info is undefined!') console.info('get distributed info is undefined!');
} }
}).catch((err) => { }).catch((error) => {
console.error("get distributed info failed with error: " + err); console.error('get distributed info failed with error: ' + error);
}); });
} }
``` ```
...@@ -983,15 +1011,13 @@ getAllPeers(callback: AsyncCallback\<Array\<PeerInfo>>): void; ...@@ -983,15 +1011,13 @@ getAllPeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
```js ```js
async function example() { async function example() {
media.getAllPeers((err, devicesInfo) => { media.getAllPeers((error, devicesInfo) => {
if (devicesInfo != undefined) { if (devicesInfo != undefined) {
for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + JSON.stringify(devicesInfo));
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else { } else {
console.error('get distributed fail, message = ' + err) console.error('get distributed failed with error: ' + error);
} }
}) });
} }
``` ```
...@@ -999,7 +1025,7 @@ async function example() { ...@@ -999,7 +1025,7 @@ async function example() {
提供封装文件属性的方法。 提供封装文件属性的方法。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
> 1. title字段默认为去掉后缀的文件名,音频和视频文件会尝试解析文件内容,部分设备写入后在触发扫描时会被还原。 > 1. title字段默认为去掉后缀的文件名,音频和视频文件会尝试解析文件内容,部分设备写入后在触发扫描时会被还原。
> 2. orientation字段部分设备可能不支持修改,建议使用image组件的[ModifyImageProperty](js-apis-image.md#modifyimageproperty9)接口。 > 2. orientation字段部分设备可能不支持修改,建议使用image组件的[ModifyImageProperty](js-apis-image.md#modifyimageproperty9)接口。
...@@ -1052,19 +1078,23 @@ isDirectory(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -1052,19 +1078,23 @@ isDirectory(callback: AsyncCallback&lt;boolean&gt;): void
```js ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isDirectory((err, isDirectory) => { asset.isDirectory((error, isDirectory) => {
// do something if (error) {
console.error('isDirectory failed with error: ' + error);
} else {
console.info('isDirectory result:' + isDirectory);
}
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1088,21 +1118,21 @@ isDirectory():Promise&lt;boolean&gt; ...@@ -1088,21 +1118,21 @@ isDirectory():Promise&lt;boolean&gt;
```js ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isDirectory().then(function(isDirectory){ asset.isDirectory().then((isDirectory) => {
console.info("isDirectory result:"+ isDirectory); console.info('isDirectory result:' + isDirectory);
}).catch(function(err){ }).catch((error) => {
console.error("isDirectory failed with error: " + err); console.error('isDirectory failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1126,20 +1156,20 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void ...@@ -1126,20 +1156,20 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void
```js ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle'; asset.title = 'newtitle';
asset.commitModify(() => { asset.commitModify(() => {
console.info('commitModify success'); console.info('commitModify successfully');
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1163,18 +1193,18 @@ commitModify(): Promise&lt;void&gt; ...@@ -1163,18 +1193,18 @@ commitModify(): Promise&lt;void&gt;
```js ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle'; asset.title = 'newtitle';
asset.commitModify(); await asset.commitModify();
fetchFileResult.close();
} }
``` ```
...@@ -1184,7 +1214,7 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void ...@@ -1184,7 +1214,7 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void
打开当前文件,使用callback方式返回异步结果。 打开当前文件,使用callback方式返回异步结果。
**注意**当前写操作是互斥的操作,写操作完成后需要调用close进行释放 **注意**以 'w' 模式打开文件时,返回的fd无法进行读取。但由于不同文件系统实现上的差异,部分用户态文件系统在 'w' 模式打开时会允许用fd读取。若有针对fd的读写行为,建议使用 'rw' 模式打开文件。当前写操作是互斥的操作,写操作完成后需要调用close进行释放。
**需要权限**:ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **需要权限**:ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
...@@ -1204,12 +1234,12 @@ async function example() { ...@@ -1204,12 +1234,12 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
const asset = await media.createAsset(mediaType, "image00003.jpg", path); const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
asset.open('rw', (openError, fd) => { asset.open('rw', (error, fd) => {
if(fd > 0){ if (fd > 0) {
asset.close(fd); asset.close(fd);
}else{ } else {
console.error('File Open Failed!' + openError); console.error('File Open failed with error: ' + error);
} }
}); });
} }
...@@ -1221,7 +1251,7 @@ open(mode: string): Promise&lt;number&gt; ...@@ -1221,7 +1251,7 @@ open(mode: string): Promise&lt;number&gt;
打开当前文件,使用promise方式返回异步结果。 打开当前文件,使用promise方式返回异步结果。
**注意**当前写操作是互斥的操作,写操作完成后需要调用close进行释放 **注意**以 'w' 模式打开文件时,返回的fd无法进行读取。但由于不同文件系统实现上的差异,部分用户态文件系统在 'w' 模式打开时会允许用fd读取。若有针对fd的读写行为,建议使用 'rw' 模式打开文件。当前写操作是互斥的操作,写操作完成后需要调用close进行释放。
**需要权限**:ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **需要权限**:ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
...@@ -1246,13 +1276,11 @@ async function example() { ...@@ -1246,13 +1276,11 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
const asset = await media.createAsset(mediaType, "image00003.jpg", path); const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
asset.open('rw') asset.open('rw').then((fd) => {
.then((fd) => { console.info('File open fd: ' + fd);
console.info('File fd!' + fd); }).catch((error) => {
}) console.error('File open failed with error: ' + error);
.catch((err) => {
console.error('File err!' + err);
}); });
} }
``` ```
...@@ -1278,30 +1306,28 @@ close(fd: number, callback: AsyncCallback&lt;void&gt;): void ...@@ -1278,30 +1306,28 @@ close(fd: number, callback: AsyncCallback&lt;void&gt;): void
```js ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => { asset.open('rw').then((fd) => {
console.info('File fd!' + fd); console.info('File open fd: ' + fd);
asset.close(fd, (closeErr) => { asset.close(fd, (error) => {
if (closeErr != undefined) { if (error) {
console.error('mediaLibraryTest : close : FAIL ' + closeErr); console.error('asset.close failed with error: ' + error);
console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL');
} else { } else {
console.info("=======asset.close success====>"); console.info('asset.close successfully');
} }
}); });
}) }).catch((error) => {
.catch((err) => { console.error('File open failed with error: ' + error);
console.error('File err!' + err);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1331,31 +1357,26 @@ close(fd: number): Promise&lt;void&gt; ...@@ -1331,31 +1357,26 @@ close(fd: number): Promise&lt;void&gt;
```js ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => { asset.open('rw').then((fd) => {
console.info('File fd!' + fd); console.info('File fd!' + fd);
asset.close(fd).then((closeErr) => { asset.close(fd).then(() => {
if (closeErr != undefined) { console.info('asset.close successfully');
console.error('mediaLibraryTest : close : FAIL ' + closeErr); }).catch((closeErr) => {
console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL'); console.error('asset.close fail, closeErr: ' + closeErr);
} else {
console.info("=======asset.close success====>");
}
}); });
}) }).catch((error) => {
.catch((err) => { console.error('open File failed with error: ' + error);
console.error('File err!' + err);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1379,19 +1400,23 @@ getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void ...@@ -1379,19 +1400,23 @@ getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void
```js ```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail((err, pixelmap) => { asset.getThumbnail((error, pixelmap) => {
console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); if (error) {
console.error('mediaLibrary getThumbnail failed with error: ' + error);
} else {
console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
}
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1421,15 +1446,19 @@ async function example() { ...@@ -1421,15 +1446,19 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size, (err, pixelmap) => { asset.getThumbnail(size, (error, pixelmap) => {
console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); if (error) {
console.error('mediaLibrary getThumbnail failed with error: ' + error);
} else {
console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
}
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1464,19 +1493,17 @@ async function example() { ...@@ -1464,19 +1493,17 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size) asset.getThumbnail(size).then((pixelmap) => {
.then((pixelmap) => { console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); }).catch((error) => {
}) console.error('mediaLibrary getThumbnail failed with error: ' + error);
.catch((err) => {
console.error('mediaLibraryTest : getThumbnail fail, err: ' + err);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1506,14 +1533,18 @@ async function example() { ...@@ -1506,14 +1533,18 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.favorite(true,function(err){ asset.favorite(true,(error) => {
// do something if (error) {
console.error('mediaLibrary favorite failed with error: ' + error);
} else {
console.info('mediaLibrary favorite Successful');
}
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1548,16 +1579,16 @@ async function example() { ...@@ -1548,16 +1579,16 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.favorite(true).then(function() { asset.favorite(true).then(() => {
console.info("favorite successfully"); console.info('mediaLibrary favorite Successful');
}).catch(function(err){ }).catch((error) => {
console.error("favorite failed with error: " + err); console.error('mediaLibrary favorite failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1586,18 +1617,18 @@ async function example() { ...@@ -1586,18 +1617,18 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isFavorite((err, isFavorite) => { asset.isFavorite((error, isFavorite) => {
if (isFavorite) { if (error) {
console.info('FileAsset is favorite'); console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
}else{ } else {
console.info('FileAsset is not favorite'); console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
} }
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1626,16 +1657,16 @@ async function example() { ...@@ -1626,16 +1657,16 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isFavorite().then(function(isFavorite){ asset.isFavorite().then((isFavorite) => {
console.info("isFavorite result:"+ isFavorite); console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
}).catch(function(err){ }).catch((error) => {
console.error("isFavorite failed with error: " + err); console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1667,15 +1698,18 @@ async function example() { ...@@ -1667,15 +1698,18 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.trash(true, trashCallBack); asset.trash(true, (error) => {
function trashCallBack(err, trash) { if (error) {
console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash'); console.error('mediaLibrary trash failed with error: ' + error);
} else {
console.info('mediaLibrary trash Successful');
} }
});
fetchFileResult.close();
} }
``` ```
...@@ -1712,16 +1746,16 @@ async function example() { ...@@ -1712,16 +1746,16 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.trash(true).then(function() { asset.trash(true).then(() => {
console.info("trash successfully"); console.info('trash successfully');
}).catch(function(err){ }).catch((error) => {
console.error("trash failed with error: " + err); console.error('trash failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1750,18 +1784,18 @@ async function example() { ...@@ -1750,18 +1784,18 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isTrash((err, isTrash) => { asset.isTrash((error, isTrash) => {
if (isTrash == undefined) { if (error) {
console.error('Failed to get trash state: ' + err); console.error('Failed to get trash state failed with error: ' + error);
return; return;
} }
console.info('Get trash state success: ' + isTrash); console.info('Get trash state successfully, isTrash result: ' + isTrash);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1790,15 +1824,16 @@ async function example() { ...@@ -1790,15 +1824,16 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
}; };
const fetchFileResult = await media.getFileAssets(getImageOp); const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.isTrash().then(function(isTrash){ asset.isTrash().then((isTrash) => {
console.info("isTrash result: " + isTrash); console.info('isTrash result: ' + isTrash);
}).catch(function(err){ }).catch((error) => {
console.error("isTrash failed with error: " + err); console.error('isTrash failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1829,11 +1864,12 @@ async function example() { ...@@ -1829,11 +1864,12 @@ async function example() {
let getFileCountOneOp = { let getFileCountOneOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getFileCountOneOp); let fetchFileResult = await media.getFileAssets(getFileCountOneOp);
const fetchCount = fetchFileResult.getCount(); const fetchCount = fetchFileResult.getCount();
console.info('fetchCount result: ' + fetchCount);
fetchFileResult.close();
} }
``` ```
...@@ -1860,23 +1896,20 @@ async function example() { ...@@ -1860,23 +1896,20 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
const fetchCount = fetchFileResult.getCount(); const fetchCount = fetchFileResult.getCount();
console.info('mediaLibraryTest : count:' + fetchCount); console.info('mediaLibrary fetchFileResult.getCount, count:' + fetchCount);
let fileAsset = await fetchFileResult.getFirstObject(); let fileAsset = await fetchFileResult.getFirstObject();
for (var i = 1; i < fetchCount; i++) { for (var i = 1; i < fetchCount; i++) {
fileAsset = await fetchFileResult.getNextObject(); fileAsset = await fetchFileResult.getNextObject();
if(i == fetchCount - 1) { if(i == fetchCount - 1) {
console.info('mediaLibraryTest : isLast');
var result = fetchFileResult.isAfterLast(); var result = fetchFileResult.isAfterLast();
console.info('mediaLibraryTest : isAfterLast:' + result); console.info('mediaLibrary fileAsset isAfterLast result: ' + result);
console.info('mediaLibraryTest : isAfterLast end');
fetchFileResult.close();
} }
} }
fetchFileResult.close();
} }
``` ```
...@@ -1897,8 +1930,7 @@ async function example() { ...@@ -1897,8 +1930,7 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.close(); fetchFileResult.close();
...@@ -1928,17 +1960,17 @@ async function example() { ...@@ -1928,17 +1960,17 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getFirstObject((err, fileAsset) => { fetchFileResult.getFirstObject((error, fileAsset) => {
if (err) { if (error) {
console.error('Failed '); console.error('fetchFileResult getFirstObject failed with error: ' + error);
return; return;
} }
console.info('fileAsset.displayName : ' + fileAsset.displayName); console.info('getFirstObject successfully, displayName : ' + fileAsset.displayName);
}) })
fetchFileResult.close();
} }
``` ```
...@@ -1965,15 +1997,15 @@ async function example() { ...@@ -1965,15 +1997,15 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getFirstObject().then(function(fileAsset){ fetchFileResult.getFirstObject().then((fileAsset) => {
console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName);
}).catch(function(err){ }).catch((error) => {
console.error("getFirstObject failed with error: " + err); console.error('getFirstObject failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -1981,7 +2013,9 @@ async function example() { ...@@ -1981,7 +2013,9 @@ async function example() {
getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void
获取文件检索结果中的下一个文件资产。此方法使用callback形式返回结果。 获取文件检索结果中的下一个文件资产,此方法使用callback形式返回结果。
> **说明**: 在使用前需要先使用[getFirstObject](#getfirstobject7)接口获取第一个文件资产,然后使用[isAfterLast](#isafterlast7)确认文件检索集当前不是指向最后一个时方可使用此接口。
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2000,18 +2034,22 @@ async function example() { ...@@ -2000,18 +2034,22 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getNextObject((err, fileAsset) => { let fileAsset = await fetchFileResult.getFirstObject();
if (err) { if (fetchFileResult.isAfterLast) {
console.error('Failed '); fetchFileResult.getNextObject((error, fileAsset) => {
if (error) {
console.error('fetchFileResult getNextObject failed with error: ' + error);
return; return;
} }
console.log('fileAsset.displayName : ' + fileAsset.displayName); console.log('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
}) })
}
fetchFileResult.close();
} }
``` ```
### getNextObject<sup>7+</sup> ### getNextObject<sup>7+</sup>
...@@ -2020,6 +2058,8 @@ async function example() { ...@@ -2020,6 +2058,8 @@ async function example() {
获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回FileAsset。 获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回FileAsset。
> **说明**: 在使用前需要先使用[getFirstObject](#getfirstobject7)接口获取第一个文件资产,然后使用[isAfterLast](#isafterlast7)确认文件检索集当前不是指向最后一个时方可使用此接口。
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core **系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
**返回值** **返回值**
...@@ -2037,13 +2077,18 @@ async function example() { ...@@ -2037,13 +2077,18 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
const fetchCount = fetchFileResult.getCount(); let fileAsset = await fetchFileResult.getFirstObject();
console.info('mediaLibraryTest : count:' + fetchCount); if (fetchFileResult.isAfterLast) {
let fileAsset = await fetchFileResult.getNextObject(); fetchFileResult.getNextObject().then((fileAsset) => {
console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
}).catch((error) => {
console.error('fetchFileResult getNextObject failed with error: ' + error);
})
}
fetchFileResult.close();
} }
``` ```
...@@ -2070,17 +2115,17 @@ async function example() { ...@@ -2070,17 +2115,17 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getLastObject((err, fileAsset) => { fetchFileResult.getLastObject((error, fileAsset) => {
if (err) { if (error) {
console.error('Failed '); console.error('getLastObject failed with error: ' + error);
return; return;
} }
console.info('fileAsset.displayName : ' + fileAsset.displayName); console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
}) })
fetchFileResult.close();
} }
``` ```
...@@ -2107,11 +2152,15 @@ async function example() { ...@@ -2107,11 +2152,15 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
let lastObject = await fetchFileResult.getLastObject(); fetchFileResult.getLastObject().then((fileAsset) => {
console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
}).catch((error) => {
console.error('getLastObject failed with error: ' + error);
});
fetchFileResult.close();
} }
``` ```
...@@ -2127,7 +2176,7 @@ getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void ...@@ -2127,7 +2176,7 @@ getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------ | | -------- | ---------------------------------------- | ---- | ------------------ |
| index | number | 是 | 要获取的文件的索引,从0开始 | | index | number | 是 | 要获取的文件的索引,从0开始(注意该值要小于文件检索集的count值) |
| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | 是 | 异步返回FileAsset之后的回调 | | callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | 是 | 异步返回FileAsset之后的回调 |
**示例** **示例**
...@@ -2139,17 +2188,17 @@ async function example() { ...@@ -2139,17 +2188,17 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getPositionObject(0, (err, fileAsset) => { fetchFileResult.getPositionObject(0, (error, fileAsset) => {
if (err) { if (error) {
console.error('Failed '); console.error('getPositionObject failed with error: ' + error);
return; return;
} }
console.info('fileAsset.displayName : ' + fileAsset.displayName); console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
}) })
fetchFileResult.close();
} }
``` ```
...@@ -2165,7 +2214,7 @@ getPositionObject(index: number): Promise&lt;FileAsset&gt; ...@@ -2165,7 +2214,7 @@ getPositionObject(index: number): Promise&lt;FileAsset&gt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ----- | ------ | ---- | -------------- | | ----- | ------ | ---- | -------------- |
| index | number | 是 | 要获取的文件的索引,从0开始 | | index | number | 是 | 要获取的文件的索引,从0开始(注意该值要小于文件检索集的count值) |
**返回值** **返回值**
...@@ -2182,15 +2231,15 @@ async function example() { ...@@ -2182,15 +2231,15 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getPositionObject(1) .then(function (fileAsset){ fetchFileResult.getPositionObject(0).then((fileAsset) => {
console.info('fileAsset.displayName : ' + fileAsset.displayName); console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
}).catch(function (err) { }).catch((error) => {
console.error("getFileAssets failed with error: " + err); console.error('getPositionObject failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -2206,7 +2255,7 @@ getAllObject(callback: AsyncCallback&lt;Array&lt;FileAsset&gt;&gt;): void ...@@ -2206,7 +2255,7 @@ getAllObject(callback: AsyncCallback&lt;Array&lt;FileAsset&gt;&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | -------------------- | | -------- | ---------------------------------------- | ---- | -------------------- |
| callback | AsyncCallback<Array<[FileAsset](#fileasset7)>> | 是 | 异步返回FileAsset列表之后的回调 | | callback | AsyncCallback&lt;Array&lt;[FileAsset](#fileasset7)&gt;&gt; | 是 | 异步返回FileAsset列表之后的回调 |
**示例** **示例**
...@@ -2217,19 +2266,19 @@ async function example() { ...@@ -2217,19 +2266,19 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.getAllObject((err, fileAsset) => { fetchFileResult.getAllObject((error, fileAssetList) => {
if (err) { if (error) {
console.error('Failed '); console.error('getAllObject failed with error: ' + error);
return; return;
} }
for (let i = 0; i < fetchFileResult.getCount(); i++) { for (let i = 0; i < fetchFileResult.getCount(); i++) {
console.info('fileAsset.displayName : ' + fileAsset[i].displayName); console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
} }
}) })
fetchFileResult.close();
} }
``` ```
...@@ -2245,7 +2294,7 @@ getAllObject(): Promise&lt;Array&lt;FileAsset&gt;&gt; ...@@ -2245,7 +2294,7 @@ getAllObject(): Promise&lt;Array&lt;FileAsset&gt;&gt;
| 类型 | 说明 | | 类型 | 说明 |
| ---------------------------------------- | --------------------- | | ---------------------------------------- | --------------------- |
| Promise<Array<[FileAsset](#fileasset7)>> | 返回FileAsset对象列表 | | Promise&lt;Array&lt;[FileAsset](#fileasset7)&gt;&gt; | 返回FileAsset对象列表 |
**示例** **示例**
...@@ -2256,11 +2305,17 @@ async function example() { ...@@ -2256,11 +2305,17 @@ async function example() {
let getImageOp = { let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + ' DESC',
extendArgs: "",
}; };
let fetchFileResult = await media.getFileAssets(getImageOp); let fetchFileResult = await media.getFileAssets(getImageOp);
var data = fetchFileResult.getAllObject(); fetchFileResult.getAllObject().then((fileAssetList) => {
for (let i = 0; i < fetchFileResult.getCount(); i++) {
console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
}
}).catch((error) => {
console.error('getAllObject failed with error: ' + error);
});
fetchFileResult.close();
} }
``` ```
...@@ -2309,12 +2364,12 @@ async function example() { ...@@ -2309,12 +2364,12 @@ async function example() {
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0]; const album = albumList[0];
album.albumName = 'hello'; album.albumName = 'hello';
album.commitModify((err) => { album.commitModify((error) => {
if (err) { if (error) {
console.error('Failed '); console.error('commitModify failed with error: ' + error);
return; return;
} }
console.info('Modify successful.'); console.info('commitModify successful.');
}) })
} }
``` ```
...@@ -2346,10 +2401,10 @@ async function example() { ...@@ -2346,10 +2401,10 @@ async function example() {
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0]; const album = albumList[0];
album.albumName = 'hello'; album.albumName = 'hello';
album.commitModify().then(function() { album.commitModify().then(() => {
console.info("commitModify successfully"); console.info('commitModify successfully');
}).catch(function(err){ }).catch((error) => {
console.error("commitModify failed with error: " + err); console.error('commitModify failed with error: ' + error);
}); });
} }
``` ```
...@@ -2383,12 +2438,19 @@ async function example() { ...@@ -2383,12 +2438,19 @@ async function example() {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
} }
// 获取符合检索要求的相册,返回相册列表
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0]; const album = albumList[0];
album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack); // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源
function getFileAssetsCallBack(err, fetchFileResult) { album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => {
// do something if (error) {
console.error('album getFileAssets failed with error: ' + error);
return;
} }
let count = fetchFileResult.getcount();
console.info('album getFileAssets successfully, count: ' + count);
});
fetchFileResult.close();
} }
``` ```
...@@ -2426,13 +2488,17 @@ async function example() { ...@@ -2426,13 +2488,17 @@ async function example() {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
}; };
// 获取符合检索要求的相册,返回相册列表
const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0]; const album = albumList[0];
album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源
console.info("getFileAssets successfully: " + JSON.stringify(albumFetchFileResult)); album.getFileAssets(fileNoArgsfetchOp).then((albumFetchFileResult) => {
}).catch(function(err){ let count = fetchFileResult.getcount();
console.error("getFileAssets failed with error: " + err); console.info('album getFileAssets successfully, count: ' + count);
}).catch((error) => {
console.error('album getFileAssets failed with error: ' + error);
}); });
fetchFileResult.close();
} }
``` ```
...@@ -2470,32 +2536,32 @@ async function example() { ...@@ -2470,32 +2536,32 @@ async function example() {
枚举,文件关键信息。 枚举,文件关键信息。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
> bucket_id字段在文件重命名或移动后可能会发生变化,开发者使用前需要重新获取。 > bucket_id字段在文件重命名或移动后可能会发生变化,开发者使用前需要重新获取。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ------------- | ------------------- | ---------------------------------------------------------- | | ------------- | ------------------- | ---------------------------------------------------------- |
| ID | "file_id" | 文件编号 | | ID | 'file_id' | 文件编号 |
| RELATIVE_PATH | "relative_path" | 相对公共目录路径 | | RELATIVE_PATH | 'relative_path' | 相对公共目录路径 |
| DISPLAY_NAME | "display_name" | 显示名字 | | DISPLAY_NAME | 'display_name' | 显示名字 |
| PARENT | "parent" | 父目录id | | PARENT | 'parent' | 父目录id |
| MIME_TYPE | "mime_type" | 文件扩展属性 | | MIME_TYPE | 'mime_type' | 文件扩展属性(如:image/*、video/*、file/*) |
| MEDIA_TYPE | "media_type" | 媒体类型 | | MEDIA_TYPE | 'media_type' | 媒体类型 |
| SIZE | "size" | 文件大小(单位:字节) | | SIZE | 'size' | 文件大小(单位:字节) |
| DATE_ADDED | "date_added" | 添加日期(添加文件时间到1970年1月1日的秒数值) | | DATE_ADDED | 'date_added' | 添加日期(添加文件时间到1970年1月1日的秒数值) |
| DATE_MODIFIED | "date_modified" | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | | DATE_MODIFIED | 'date_modified' | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) |
| DATE_TAKEN | "date_taken" | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) | | DATE_TAKEN | 'date_taken' | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) |
| TITLE | "title" | 文件标题 | | TITLE | 'title' | 文件标题 |
| ARTIST | "artist" | 作者 | | ARTIST | 'artist' | 作者 |
| AUDIOALBUM | "audio_album" | 专辑 | | AUDIOALBUM | 'audio_album' | 专辑 |
| DURATION | "duration" | 持续时间(单位:毫秒) | | DURATION | 'duration' | 持续时间(单位:毫秒) |
| WIDTH | "width" | 图片宽度(单位:像素) | | WIDTH | 'width' | 图片宽度(单位:像素) |
| HEIGHT | "height" | 图片高度(单位:像素) | | HEIGHT | 'height' | 图片高度(单位:像素) |
| ORIENTATION | "orientation" | 图片显示方向,即顺时针旋转角度,如0,90,180。(单位:度) | | ORIENTATION | 'orientation' | 图片显示方向,即顺时针旋转角度,如0,90,180。(单位:度) |
| ALBUM_ID | "bucket_id" | 文件所归属的相册编号 | | ALBUM_ID | 'bucket_id' | 文件所归属的相册编号 |
| ALBUM_NAME | "bucket_display_name" | 文件所归属相册名称 | | ALBUM_NAME | 'bucket_display_name' | 文件所归属相册名称 |
## DirectoryType<sup>8+</sup> ## DirectoryType<sup>8+</sup>
...@@ -2538,9 +2604,9 @@ async function example() { ...@@ -2538,9 +2604,9 @@ async function example() {
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ | | ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ |
| selections | string | 是 | 是 | 检索条件,使用[FileKey](#filekey8)中的枚举值作为检索条件的列名。示例:<br/>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selections | string | 是 | 是 | 检索条件,使用[FileKey](#filekey8)中的枚举值作为检索条件的列名。示例:<br/>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
| selectionArgs | Array&lt;string&gt; | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。<br/>示例:<br/>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | | selectionArgs | Array&lt;string&gt; | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。<br/>示例:<br/>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
| order | string | 是 | 是 | 检索结果排序方式,使用[FileKey](#filekey8)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:<br/>升序排列:order: mediaLibrary.FileKey.DATE_ADDED + " ASC"<br/>降序排列:order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | | order | string | 是 | 是 | 检索结果排序方式,使用[FileKey](#filekey8)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:<br/>升序排列:order: mediaLibrary.FileKey.DATE_ADDED + ' ASC'<br/>降序排列:order: mediaLibrary.FileKey.DATE_ADDED + ' DESC' |
| uri<sup>8+</sup> | string | 是 | 是 | 文件URI | | uri<sup>8+</sup> | string | 是 | 是 | 文件URI |
| networkId<sup>8+</sup> | string | 是 | 是 | 注册设备网络ID | | networkId<sup>8+</sup> | string | 是 | 是 | 注册设备网络ID |
| extendArgs<sup>8+</sup> | string | 是 | 是 | 扩展的检索参数,目前没有扩展检索参数 | | extendArgs<sup>8+</sup> | string | 是 | 是 | 扩展的检索参数,目前没有扩展检索参数 |
...@@ -2584,4 +2650,3 @@ async function example() { ...@@ -2584,4 +2650,3 @@ async function example() {
| type | 'image' &#124; 'video' &#124; 'media' | 是 | 是 | 媒体类型,包括:image, video, media,当前仅支持media类型 | | type | 'image' &#124; 'video' &#124; 'media' | 是 | 是 | 媒体类型,包括:image, video, media,当前仅支持media类型 |
| count | number | 是 | 是 | 媒体选择,count = 1表示单选,count大于1表示多选。 | | count | number | 是 | 是 | 媒体选择,count = 1表示单选,count大于1表示多选。 |
...@@ -133,6 +133,8 @@ queryAppGroup(): Promise&lt;number&gt; ...@@ -133,6 +133,8 @@ queryAppGroup(): Promise&lt;number&gt;
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
**系统API**:此接口为系统接口。
**返回值** **返回值**
| 类型 | 说明 | | 类型 | 说明 |
...@@ -175,6 +177,8 @@ queryAppGroup(callback: AsyncCallback&lt;number&gt;): void ...@@ -175,6 +177,8 @@ queryAppGroup(callback: AsyncCallback&lt;number&gt;): void
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
**系统API**:此接口为系统接口。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -552,6 +556,8 @@ queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback&lt; ...@@ -552,6 +556,8 @@ queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback&lt;
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -601,6 +607,8 @@ queryCurrentBundleEvents(begin: number, end: number): Promise&lt;Array&lt;Bundle ...@@ -601,6 +607,8 @@ queryCurrentBundleEvents(begin: number, end: number): Promise&lt;Array&lt;Bundle
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -1558,6 +1566,8 @@ FA卡片的使用信息的属性集合。 ...@@ -1558,6 +1566,8 @@ FA卡片的使用信息的属性集合。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口。
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| --------------------- | ------ | ---- | ---------------------------------------- | | --------------------- | ------ | ---- | ---------------------------------------- |
| bundleName | string | 是 | 应用包名。 | | bundleName | string | 是 | 应用包名。 |
......
...@@ -63,8 +63,7 @@ ...@@ -63,8 +63,7 @@
- [时间时区服务错误码](errorcode-time.md) - [时间时区服务错误码](errorcode-time.md)
- [Webview错误码](errorcode-webview.md) - [Webview错误码](errorcode-webview.md)
- 帐号管理 - 帐号管理
- [Account错误码](errorcode-account.md) - [帐号管理错误码](errorcode-account.md)
- [应用帐号错误码](errorcode-app-account.md)
- 设备管理 - 设备管理
- [耗电统计错误码](errorcode-batteryStatistics.md) - [耗电统计错误码](errorcode-batteryStatistics.md)
- [屏幕亮度错误码](errorcode-brightness.md) - [屏幕亮度错误码](errorcode-brightness.md)
......
# Account错误码 # 帐号管理错误码
以下错误码包括系统帐号、分布式帐号和应用帐号错误码。 以下错误码包括系统帐号、分布式帐号和应用帐号错误码。
...@@ -448,5 +448,81 @@ The account authenticator service works abnormally. ...@@ -448,5 +448,81 @@ The account authenticator service works abnormally.
**处理步骤** **处理步骤**
1. 请重试或重启系统; 1. 请重试或重启系统。
2. 按照规范开发应用认证器; 2. 按照规范开发应用认证器。
## 12400001 应用不存在
**错误信息**
The application does not exist.
**可能原因**
该错误码表示应用不存在,可能原因如下:
1. 设置访问权限时,目标应用不存在。
2. 设置开放授权时,目标应用不存在。
**处理步骤**
请取消设置,或使用已安装的应用包名重试。
## 12400002 自定义数据不存在
**错误信息**
The custom data does not exist.
**可能原因**
该错误码表示自定义数据不存在,可能原因如下:
查询帐号的自定义数据时,输入的键名不存在。
**处理步骤**
请使用存在的自定义数据的键名查询。
## 12400003 自定义数据的数量已达上限
**错误信息**
The number of custom data reaches upper limit.
**可能原因**
该错误码表示自定义数据的数量已达上限,可能原因如下:
设置自定义数据时,目标帐号的自定义数据数量已达512。
**处理步骤**
请取消设置操作,或者删除已存在的自定义数据。
## 12400004 令牌数量已达上限
**错误信息**
The number of token reaches upper limit.
**可能原因**
该错误码表示令牌数量已达上限,可能原因如下:
添加令牌时,目标帐号的令牌数量已达1024。
**处理步骤**
请取消添加操作,或者删除已存在的令牌后再添加。
## 12400005 授权列表已达上限
**错误信息**
The size of authorization list reaches upper limit.
**可能原因**
该错误码表示授权列表已达上限,可能原因如下:
设置访问/开放授权时,授权列表的大小超过1024。
**处理步骤**
1. 请取消设置操作,或者撤销已存在的访问/开放授权后再设置。
\ No newline at end of file
# 应用帐号错误码
## 12400001 应用不存在
**错误信息**
The application does not exist.
**可能原因**
该错误码表示应用不存在,可能原因如下:
1. 设置访问权限时,目标应用不存在。
2. 设置开放授权时,目标应用不存在。
**处理步骤**
请取消设置,或使用已安装的应用包名重试。
## 12400002 自定义数据不存在
**错误信息**
The custom data does not exist.
**可能原因**
该错误码表示自定义数据不存在,可能原因如下:
查询帐号的自定义数据时,输入的键名不存在。
**处理步骤**
请使用存在的自定义数据的键名查询。
## 12400003 自定义数据的数量已达上限
**错误信息**
The number of custom data reaches upper limit.
**可能原因**
该错误码表示自定义数据的数量已达上限,可能原因如下:
设置自定义数据时,目标帐号的自定义数据数量已达512。
**处理步骤**
请取消设置操作,或者删除已存在的自定义数据。
## 12400004 令牌数量已达上限
**错误信息**
The number of token reaches upper limit.
**可能原因**
该错误码表示令牌数量已达上限,可能原因如下:
添加令牌时,目标帐号的令牌数量已达1024。
**处理步骤**
请取消添加操作,或者删除已存在的令牌后再添加。
## 12400005 授权列表已达上限
**错误信息**
The size of authorization list reaches upper limit.
**可能原因**
该错误码表示授权列表已达上限,可能原因如下:
设置访问/开放授权时,授权列表的大小超过1024。
**处理步骤**
1. 请取消设置操作,或者撤销已存在的访问/开放授权后再设置。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册