未验证 提交 bf77d85b 编写于 作者: O openharmony_ci 提交者: Gitee

!14886 翻译已完成14009

Merge pull request !14886 from shawn_he/14009-b
...@@ -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. |
# @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
...@@ -70,11 +346,11 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -70,11 +346,11 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```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
...@@ -114,11 +390,11 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -114,11 +390,11 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```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 {
...@@ -154,10 +430,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -154,10 +430,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```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 {
...@@ -192,10 +468,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -192,10 +468,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```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
...@@ -236,13 +512,13 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -236,13 +512,13 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```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
...@@ -279,13 +555,13 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -279,13 +555,13 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```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
...@@ -322,10 +598,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -322,10 +598,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301100 | The location switch is off. | |3301100 | The location switch is off. |
**Example** **Example**
```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
...@@ -365,10 +641,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -365,10 +641,10 @@ For details about the following error codes, see [Location Error Codes](../error
**Example** **Example**
```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 {
...@@ -408,10 +684,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -408,10 +684,10 @@ For details about the following error codes, see [Location Error Codes](../error
**Example** **Example**
```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));
} }
...@@ -451,10 +727,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -451,10 +727,10 @@ For details about the following error codes, see [Location Error Codes](../error
**Example** **Example**
```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**
...@@ -496,26 +772,26 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -496,26 +772,26 @@ For details about the following error codes, see [Location Error Codes](../error
|3301600 | Failed to operate the geofence. | |3301600 | Failed to operate the geofence. |
**Example** **Example**
```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**
...@@ -554,16 +830,16 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -554,16 +830,16 @@ For details about the following error codes, see [Location Error Codes](../error
|3301600 | Failed to operate the geofence. | |3301600 | Failed to operate the geofence. |
**Example** **Example**
```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);
...@@ -611,10 +887,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -611,10 +887,10 @@ For details about the following error codes, see [Location Error Codes](../error
**Example** **Example**
```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));
} }
...@@ -652,10 +928,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -652,10 +928,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301500 | Failed to query the area information. | |3301500 | Failed to query the area information. |
**Example** **Example**
```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
...@@ -697,11 +973,11 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -697,11 +973,11 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```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
...@@ -744,10 +1020,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -744,10 +1020,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```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
...@@ -796,10 +1072,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -796,10 +1072,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```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};
try { try {
geoLocationManager.getCurrentLocation(requestInfo).then((result) => { geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
console.log('current location: ' + JSON.stringify(result)); console.log('current location: ' + JSON.stringify(result));
...@@ -819,7 +1095,7 @@ getLastLocation(): Location ...@@ -819,7 +1095,7 @@ getLastLocation(): Location
Obtains the last location. 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
...@@ -840,11 +1116,11 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -840,11 +1116,11 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 |Failed to obtain the geographical location. | |3301200 |Failed to obtain the geographical location. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
var location = geoLocationManager.getLastLocation(); let location = geoLocationManager.getLastLocation();
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + err.code + ",errMessage:" + err.message);
} }
...@@ -874,97 +1150,11 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -874,97 +1150,11 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
var locationEnabled = geoLocationManager.isLocationEnabled();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
## geoLocationManager.requestEnableLocation
requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;): void
Requests to enable the location service. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core
**Parameters**
| 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.|
**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. |
|3301700 | No response to the request. |
**Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
geoLocationManager.requestEnableLocation((err, data) => { let locationEnabled = geoLocationManager.isLocationEnabled();
if (err) {
console.log('requestEnableLocation: err=' + JSON.stringify(err));
}
if (data) {
console.log('requestEnableLocation: data=' + JSON.stringify(data));
}
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
## geoLocationManager.requestEnableLocation
requestEnableLocation(): Promise&lt;boolean&gt;
Requests to enable the location service. This API uses a promise to return the result.
**Permission required**: ohos.permission.APPROXIMATELY_LOCATION
**System capability**: SystemCapability.Location.Location.Core
**Return value**
| 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.|
**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. |
|3301700 | No response to the request. |
**Example**
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
geoLocationManager.requestEnableLocation().then((result) => {
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);
} }
...@@ -998,7 +1188,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -998,7 +1188,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -1040,7 +1230,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1040,7 +1230,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -1076,7 +1266,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1076,7 +1266,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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
...@@ -1113,10 +1303,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1113,10 +1303,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301300 | Reverse geocoding query failed. | |3301300 | Reverse geocoding query failed. |
**Example** **Example**
```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
...@@ -1162,10 +1352,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1162,10 +1352,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301300 | Reverse geocoding query failed. | |3301300 | Reverse geocoding query failed. |
**Example** **Example**
```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
...@@ -1204,10 +1394,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1204,10 +1394,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301400 | Geocoding query failed. | |3301400 | Geocoding query failed. |
**Example** **Example**
```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
...@@ -1253,10 +1443,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1253,10 +1443,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301400 | Geocoding query failed. | |3301400 | Geocoding query failed. |
**Example** **Example**
```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));
...@@ -1292,11 +1482,11 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1292,11 +1482,11 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```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
...@@ -1329,7 +1519,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1329,7 +1519,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301100 | The location switch is off. | |3301100 | The location switch is off. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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
...@@ -1373,7 +1563,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1373,7 +1563,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301100 | The location switch is off. | |3301100 | The location switch is off. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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
...@@ -1416,7 +1606,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1416,7 +1606,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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
...@@ -1458,7 +1648,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1458,7 +1648,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301200 | Failed to obtain the geographical location. | |3301200 | Failed to obtain the geographical location. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -1498,10 +1688,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1498,10 +1688,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```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) {
...@@ -1543,10 +1733,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1543,10 +1733,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```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');
...@@ -1584,7 +1774,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1584,7 +1774,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301500 | Failed to query the area information.| |3301500 | Failed to query the area information.|
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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**
...@@ -1626,7 +1816,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1626,7 +1816,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301500 | Failed to query the area information.| |3301500 | Failed to query the area information.|
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -1663,7 +1853,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1663,7 +1853,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301100 | The location switch is off.| |3301100 | The location switch is off.|
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -1694,7 +1884,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1694,7 +1884,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301100 | The location switch is off.| |3301100 | The location switch is off.|
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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.
...@@ -1731,18 +1923,19 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1731,18 +1923,19 @@ For details about the following error codes, see [Location Error Codes](../error
|3301100 | The location switch is off.| |3301100 | The location switch is off.|
**Example** **Example**
```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);
...@@ -1769,7 +1962,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1769,7 +1962,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -1799,7 +1992,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1799,7 +1992,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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**
...@@ -1835,10 +2030,10 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1835,10 +2030,10 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```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**
...@@ -1884,11 +2080,11 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1884,11 +2080,11 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```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);
} }
...@@ -1923,7 +2119,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1923,7 +2119,7 @@ For details about the following error codes, see [Location Error Codes](../error
|3301000 | Location service is unavailable. | |3301000 | Location service is unavailable. |
**Example** **Example**
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
try { try {
...@@ -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**
...@@ -331,7 +331,7 @@ promise.then(data => { ...@@ -331,7 +331,7 @@ promise.then(data => {
getSignalInformation\(slotId: number, callback: AsyncCallback<Array<SignalInformation\>\>\): void getSignalInformation\(slotId: number, callback: AsyncCallback<Array<SignalInformation\>\>\): void
Obtains a list of signal strengths of the network with which the SIM card in the specified slot is registered. This API uses an asynchronous callback to return the result. Obtains a list of signal strengths of the network with which the SIM card in the specified slot is registered. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
...@@ -356,7 +356,7 @@ radio.getSignalInformation(slotId, (err, data) => { ...@@ -356,7 +356,7 @@ radio.getSignalInformation(slotId, (err, data) => {
getSignalInformation\(slotId: number\): Promise<Array<SignalInformation\>\> getSignalInformation\(slotId: number\): Promise<Array<SignalInformation\>\>
Obtains a list of signal strengths of the network with which the SIM card in the specified slot is registered. This API uses a promise to return the result. Obtains a list of signal strengths of the network with which the SIM card in the specified slot is registered. This API uses a promise to return the result.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
...@@ -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
...@@ -596,7 +654,7 @@ Sets the ID of the slot in which the primary card is located. This API uses an a ...@@ -596,7 +654,7 @@ Sets the ID of the slot in which the primary card is located. This API uses an a
| 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|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -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
...@@ -1192,7 +1250,7 @@ promise.then(data => { ...@@ -1192,7 +1250,7 @@ promise.then(data => {
getNetworkSearchInformation\(slotId: number, callback: AsyncCallback<NetworkSearchResult\>\): void getNetworkSearchInformation\(slotId: number, callback: AsyncCallback<NetworkSearchResult\>\): void
Obtains network search information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Obtains network search information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -1205,7 +1263,7 @@ Obtains network search information for the SIM card in the specified slot. This ...@@ -1205,7 +1263,7 @@ Obtains network search information for the SIM card in the specified slot. This
| 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|
| callback | AsyncCallback\<[NetworkSearchResult](#networksearchresult)\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<[NetworkSearchResult](#networksearchresult)\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -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,13 +2007,13 @@ Defines the CDMA cell information. ...@@ -1949,13 +2007,13 @@ 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. |
| nid | number | Yes | Network ID.| | nid | number | Yes | Network ID.|
| sid | number | Yes | System ID.| | sid | number | Yes | System ID.|
## GsmCellInformation<sup>8+</sup> ## GsmCellInformation<sup>8+</sup>
...@@ -1965,50 +2023,50 @@ Defines the GSM cell information. ...@@ -1965,50 +2023,50 @@ 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.|
| bsic | number | Yes | Base station ID. | | bsic | number | Yes | Base station ID. |
| mcc | string | Yes | Mobile country code. | | mcc | string | Yes | Mobile country code. |
| mnc | string | Yes | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## 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. |
| earfcn | number | Yes | Absolute radio frequency channel number. | | earfcn | number | Yes | Absolute radio frequency channel number. |
| 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. |
| nci | number | Yes | 5G network cell ID.| | nci | number | Yes | 5G network cell ID.|
| mcc | string | Yes | Mobile country code. | | mcc | string | Yes | Mobile country code. |
| mnc | string | Yes | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## TdscdmaCellInformation<sup>8+</sup> ## TdscdmaCellInformation<sup>8+</sup>
...@@ -2018,14 +2076,14 @@ Defines the TD-SCDMA cell information. ...@@ -2018,14 +2076,14 @@ 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.|
| uarfcn | number | Yes | Absolute radio frequency number.| | uarfcn | number | Yes | Absolute radio frequency number.|
| mcc | string | Yes | Mobile country code.| | mcc | string | Yes | Mobile country code.|
| mnc | string | Yes | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## WcdmaCellInformation<sup>8+</sup> ## WcdmaCellInformation<sup>8+</sup>
...@@ -2035,14 +2093,14 @@ Defines the WCDMA cell information. ...@@ -2035,14 +2093,14 @@ 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. |
| uarfcn | number | Yes | Absolute radio frequency number.| | uarfcn | number | Yes | Absolute radio frequency number.|
| mcc | string | Yes | Mobile country code.| | mcc | string | Yes | Mobile country code.|
| mnc | string | Yes | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## NrOptionMode<sup>8+</sup> ## NrOptionMode<sup>8+</sup>
...@@ -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,10 +2125,10 @@ Defines the network search result. ...@@ -2067,10 +2125,10 @@ 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.|
## NetworkInformation ## NetworkInformation
...@@ -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,12 +2168,12 @@ Defines the network selection mode. ...@@ -2110,12 +2168,12 @@ 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. |
| resumeSelection | boolean | Yes | Whether to resume selection. | | resumeSelection | boolean | Yes | Whether to resume selection. |
## ImsRegState<sup>9+</sup> ## ImsRegState<sup>9+</sup>
...@@ -2153,10 +2211,10 @@ Defines the IMS registration information. ...@@ -2153,10 +2211,10 @@ 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.|
## ImsServiceType<sup>9+</sup> ## ImsServiceType<sup>9+</sup>
......
...@@ -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.|
# 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 - Event name<br>Indicates the events in an event domain. For details, see [EVENT\_NAMEA/EVENT\_NAMEB](#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 - Parameter<br>Defines the key values in an event name. For details, see [__BASE/NAME1/NAME2](#example) in the example YAML file.
Defines the key values in an event name. For details, see [__BASE/NAME1/NAME2](#section123181432175123) in the example YAML file.
### Constraints<a name="section123181432175114"></a> ### Constraints
Constraints on the event domain, event name, and parameter
- Each YAML file can contain only one event domain, and the domain name cannot be the same as that defined in other YAML files. - 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|
| -------- | -------- |
| type | Event type. This field is mandatory.<br>Value:<br>- FAULT: fault<br>- STATISTIC: statistics<br>- SECURITY: security<br>- BEHAVIOR: user behavior|
| level | Event level. This field is mandatory.<br>Value:<br>- CRITICAL: critical<br>- MINOR: minor|
| 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 | 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
| 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 | 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 |
| level | Indicates the level of the event. This field is mandatory. <br><br>Value: <ul><li>**CRITICAL**: critical </li><li>**MINOR**: minor</li></ul> | | arrsize | Length of the parameter of the array type. This field is optional.<br>Value:<br>1-100|
| 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>| | 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 (_).|
| 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>|
**Table 2** Description of custom parameters
| Field| Description| ## Writing a YAML File
| ----- | ----- |
| 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>|
| 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>| ### Writing Rules
| 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>|
- Event domain naming rules:
- The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;).
- The name contains 1 to 16 characters.
## Writing a YAML File<a name="section123181432175113"></a> - Event naming rules:
- 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 number of internal event names in an event domain cannot exceed 4096.
### Writing Rules<a name="section123181432175133"></a> - Parameter naming rules:
- 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 number of parameters in an event domain cannot exceed 128.
- Event domain naming rules:
- The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;).
- The name contains 1 to 16 characters.
- Event naming rules:
- The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;).
- The name contains 1 to 32 characters.
- The number of internal event names in an event domain cannot exceed 4096.
- Parameter naming rules:
- The name must start with a letter and can contain only uppercase letters, digits, and underscores (&#95;).
- The name contains 1 to 32 characters.
- The number of parameters in an event domain cannot exceed 128.
### Example<a name="section123181432175123"></a> ### Example
- In the example YAML file, the event domain name is **MODULEA**. The event domain contains two events named **EVENT\_NAMEA** and **EVENT\_NAMEB**. - In the example YAML file, the event domain name is **MODULEA**. The event domain contains two events named **EVENT_NAMEA** and **EVENT_NAMEB**.
- **EVENT\_NAMEA** is defined as a critical event of the fault type. The event contains the **NAME1** parameter of the string type, the **NAME2** parameter of the string type, and the **NAME3** parameter of the unsigned short integer type. Therefore, you can perform [real-time subscription](subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEA**.
- **EVENT\_NAMEB** is defined as a general event of the statistics type. The event contains the **NAME1** parameter of the unsigned short integer type and the **NAME2** parameter of the integer type. Because two event tags named **tag1** and **tag2** are defined for **EVENT\_NAMEB** in the **\__BASE** parameter, you can perform [real-time subscription](subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEB**, or based on the event tag.
``` - **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**.
##########################################
# HiSysEvent definition for MODULEA
##########################################
domain: MODULEA - **EVENT\_NAMEB** is defined as a general event of the statistics type. The event contains the **NAME1** parameter of the unsigned short integer type and the **NAME2** parameter of the integer type. Because two event tags named **tag1** and **tag2** are defined for **EVENT\_NAMEB** in the **\__BASE** parameter, you can perform [real-time subscription](../subsystems/subsys-dfx-hisysevent-listening.md) to the event based on the event domain **MODULEA** and event name **EVENT\_NAMEB**, or based on the event tag.
```
##########################################
# the hisysevent definition for module a #
##########################################
domain: MODULEA
EVENT_NAMEA:
__BASE: {type: FAULT, level: CRITICAL, desc: event name a}
NAME1: {type: STRING, desc: name1}
NAME2: {type: STRING, desc: name2}
NAME3: {type: UINT16, desc: name3}
EVENT_NAMEB:
__BASE: {type: STATISTIC, level: MINOR, tag: tag1 tag2, desc: event name b}
NAME1: {type: UINT16, desc: name1}
NAME2: {type: INT32, desc: name2}
```
EVENT_NAMEA:
__BASE: {type: FAULT, level: CRITICAL, desc: event name a}
NAME1: {type: STRING, desc: name1}
NAME2: {type: STRING, desc: name2}
NAME3: {type: UINT16, desc: name3}
EVENT_NAMEB: ## Verifying the YAML File
__BASE: {type: STATISTIC, level: MINOR, tag: tag1 tag2, desc: event name b}
NAME1: {type: UINT16, desc: name1}
NAME2: {type: INT32, desc: name2}
```
## Verifying the YAML File<a name="section123181432175115"></a>
### Configuring the YAML File Path<a name="section123181432175135"></a> ### Configuring the YAML File Path
In the **bundle.json** file, use the **hisysevent_config** attribute to specify the YAML file path.
In the **bundle.json** file, use the ```hisysevent_config``` attribute to specify the YAML file path.
``` ```
{ {
...@@ -131,45 +145,47 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif ...@@ -131,45 +145,47 @@ In the **bundle.json** file, use the ```hisysevent_config``` attribute to specif
} }
``` ```
>![](../public_sys-resources/icon-note.gif) **Note:**
>The YAML file can be placed in any directory of the component project as needed. You only need to specify the path in the **bundle.json** file.
### Compiling the YAML File<a name="section123181432175137"></a>
- Perform full compilation.
- During full compilation of the system, the configuration in the YAML files of all components are summarized. After the compilation is complete, the **hisysevent.def** file will be generated in the specified directory. > **NOTE**<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.
```
cd absolute path of the project's root directory
./build --product-name <product name>
```
- To obtain the **hisysevent.def** file generated after full compilation, run the following command: ### Compiling YAML Files
``` - Perform full compilation.
cd absolute path of the project's root directory - 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.
find out -name hisysevent.def -type f
``` ```
cd *absolute path of the project's root directory*
./build --product-name <product name>
```
- Single-file compilation: - To obtain the **hisysevent.def** file generated after full compilation, run the following commands:
```
cd absolute path of the project's root directory
find out -name hisysevent.def -type f
```
You can also compile the YAML file of a single component by running the following commands: - Single-file compilation:
You can also compile the YAML file of a single component by running the following commands:
```
cd absolute path of the project's root directory ```
./build/ohos/hisysevent/gen_def_from_all_yaml.py --yaml-list <yaml file list> --def-path <file store 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>
```
**Table 3** Parameters for single-file compilation **Table 3** Parameters for single-file compilation
| Option| Description|
| -------- | -------- |
| --yaml-list | Paths of the YAML files to be compiled. If there are multiple YAML file paths, separate each of them with a space.|
| --def-path | Path of the **hisysevent.def** file generated after compilation.|
| Parameter| Description|
| ------ | ------ |
| --yaml-list | Specifies the paths of the YAML files to be compiled. If there are multiple YAML file paths, separate each of them with a space.|
| --def-path | Specifies the path of the **hisysevent.def** file generated after compilation.|
### Logging and Querying Events<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
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册