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

!2037 位置/RPC资料内容交付&中英文目录调整

Merge pull request !2037 from zengyawen/master
# Application Development
- [Application Development Overview](application-dev-guide.md)
- [DevEco Studio \(OpenHarmony\) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- [Directory Structure](quick-start/package-structure.md)
- [ArkUI](ui/ui-arkui.md)
- [JavaScript-based Web-like Development Paradigm](ui/ui-arkui-js.md)
[Application Development Overview](application-dev-guide.md)
- [TypeScript-based Declarative Development Paradigm](ui/ui-arkui-ts.md)
- [Agent-Powered Scheduled Reminders ](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management ](background-task-management/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [USB Service](usb/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Development References](reference/Readme-EN.md)
- [JavaScript-based Web-like Development Paradigm](reference/arkui-js/Readme-EN.md)
- [TypeScript-based Declarative Development Paradigm](reference/arkui-ts/Readme-EN.md)
- [APIs](reference/apis/Readme-EN.md)
- Learn About the OpenHarmony Community
- [OpenHarmony Community](../OpenHarmony-Overview.md)
- [OpenHarmony OS](../readme)
- [Glossary ](../device-dev/glossary/glossary.md)
- [OpenHarmony Release Notes](../release-notes/Readme.md)
- Quick Start
- [Getting Started with Application Development](quick-start/Readme-EN.md)
- [Directory Structure](quick-start/package-structure.md)
- Development
- [ArkUI](ui/Readme-EN.md)
- Basic Functions
- [Agent-Powered Scheduled Reminders ](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management ](background-task-management/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [Device](device/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- Tools
- [DevEco Studio \(OpenHarmony\) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
- API References
- [Compent Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Compent Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [APIs](reference/apis/Readme-EN.md)
- Contribution
- [How to Contribute](../contribute/documentation-contribution.md)
# Device
- USB Service
- [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md)
- Location
- [Location Overview](device-location-overview.md)
- [Obtaining Device Location Information](device-location-info.md)
- [Geocoding and Reverse Geocoding Capabilities](device-location-geocoding.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 geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc.
## 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. 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, (data) => {
console.log('getAddressesFromLocation: ' + 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 the _API Reference_.
- Call **getAddressesFromLocationName** to convert geographic description into coordinates.
```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (data) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(data));
});
```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see the _API Reference_.
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.
**Table1** 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: CachedGnssLoactionsRequest, 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 function uses an asynchronous callback to return the result. |
| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This function uses a promise to return the result. |
| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This function uses an asynchronous callback to return the result. |
| getLastLocation() : Promise<Location> | Obtains the previous location. This function uses a promise to return the result. |
| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This function uses an asynchronous callback to return the result. |
| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This function uses a promise to return the result. |
| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This function uses an asynchronous callback to return the result. |
| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This function uses a promise to return the result. |
| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This function uses an asynchronous callback to return the result. |
| enableLocation() : Promise<boolean> | Enables the location service. This function uses a promise to return the result. |
| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This function uses an asynchronous callback to return the result. |
| disableLocation() : Promise<boolean> | Disables the location service. This function uses a promise to return the result. |
| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This function uses an asynchronous callback to return the result. |
| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This function uses a promise to return the result. |
| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses an asynchronous callback to return the result. |
| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses a promise to return the result. |
| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This function uses an asynchronous callback to return the result. |
| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This function 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 function 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 function 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 function 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 function uses a promise to return the result. |
## How to Develop
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. For details, see .
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 allowed to run on the background in the configuration file and also granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information even when your application moves to the background.
To allow your application to access device location information, you can declare the required permissions in the **config.json** file of your application. The sample code is as follows:
```
{
"module": {
"reqPermissions": [{
"name": "ohos.permission.LOCATION",
"reason": "$string:reason_description",
"usedScene": {
"ability": ["com.myapplication.LocationAbility"],
"when": "inuse"
}, {
...
}
]
}
}
```
For details about the fields, see .
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.
**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,
}
```
**Table2** Common use cases of the location function
| Use Case | Constant | Description |
| -------- | -------- | -------- |
| Navigation | NAVIGATION | Applicable&nbsp;when&nbsp;your&nbsp;application&nbsp;needs&nbsp;to&nbsp;obtain&nbsp;the&nbsp;real-time&nbsp;location&nbsp;of&nbsp;a&nbsp;mobile&nbsp;device&nbsp;outdoors,&nbsp;such&nbsp;as&nbsp;navigation&nbsp;for&nbsp;driving&nbsp;or&nbsp;walking.&nbsp;In&nbsp;this&nbsp;scenario,&nbsp;the&nbsp;GNSS&nbsp;positioning&nbsp;technology&nbsp;is&nbsp;mainly&nbsp;used&nbsp;to&nbsp;ensure&nbsp;the&nbsp;location&nbsp;accuracy.&nbsp;However,&nbsp;due&nbsp;to&nbsp;its&nbsp;limitations,&nbsp;the&nbsp;technology&nbsp;may&nbsp;be&nbsp;unable&nbsp;to&nbsp;provide&nbsp;the&nbsp;location&nbsp;service&nbsp;when&nbsp;navigation&nbsp;is&nbsp;just&nbsp;started&nbsp;or&nbsp;when&nbsp;the&nbsp;user&nbsp;moves&nbsp;into&nbsp;a&nbsp;shielded&nbsp;environment&nbsp;such&nbsp;as&nbsp;indoors&nbsp;or&nbsp;a&nbsp;garage.&nbsp;To&nbsp;resolve&nbsp;this&nbsp;issue,&nbsp;the&nbsp;system&nbsp;uses&nbsp;the&nbsp;network&nbsp;positioning&nbsp;technology&nbsp;as&nbsp;an&nbsp;alternative&nbsp;to&nbsp;provide&nbsp;the&nbsp;location&nbsp;service&nbsp;for&nbsp;your&nbsp;application&nbsp;until&nbsp;the&nbsp;GNSS&nbsp;can&nbsp;provide&nbsp;stable&nbsp;location&nbsp;results.&nbsp;This&nbsp;helps&nbsp;achieve&nbsp;a&nbsp;smooth&nbsp;navigation&nbsp;experience&nbsp;for&nbsp;users.<br/>By&nbsp;default,&nbsp;the&nbsp;system&nbsp;reports&nbsp;location&nbsp;results&nbsp;at&nbsp;a&nbsp;minimal&nbsp;interval&nbsp;of&nbsp;1s.&nbsp;To&nbsp;adopt&nbsp;this&nbsp;use&nbsp;case,&nbsp;you&nbsp;must&nbsp;declare&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
| Trajectory&nbsp;tracking | TRAJECTORY_TRACKING | Applicable&nbsp;when&nbsp;your&nbsp;application&nbsp;needs&nbsp;to&nbsp;record&nbsp;user&nbsp;trajectories,&nbsp;for&nbsp;example,&nbsp;the&nbsp;track&nbsp;recording&nbsp;function&nbsp;of&nbsp;sports&nbsp;applications.&nbsp;In&nbsp;this&nbsp;scenario,&nbsp;the&nbsp;GNSS&nbsp;positioning&nbsp;technology&nbsp;is&nbsp;mainly&nbsp;used&nbsp;to&nbsp;ensure&nbsp;the&nbsp;location&nbsp;accuracy.<br/>By&nbsp;default,&nbsp;the&nbsp;system&nbsp;reports&nbsp;location&nbsp;results&nbsp;at&nbsp;a&nbsp;minimal&nbsp;interval&nbsp;of&nbsp;1s.&nbsp;To&nbsp;adopt&nbsp;this&nbsp;use&nbsp;case,&nbsp;you&nbsp;must&nbsp;declare&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
| Ride&nbsp;hailing | CAR_HAILING | Applicable&nbsp;when&nbsp;your&nbsp;application&nbsp;needs&nbsp;to&nbsp;obtain&nbsp;the&nbsp;current&nbsp;location&nbsp;of&nbsp;a&nbsp;user&nbsp;who&nbsp;is&nbsp;hailing&nbsp;a&nbsp;taxi.<br/>By&nbsp;default,&nbsp;the&nbsp;system&nbsp;reports&nbsp;location&nbsp;results&nbsp;at&nbsp;a&nbsp;minimal&nbsp;interval&nbsp;of&nbsp;1s.&nbsp;To&nbsp;adopt&nbsp;this&nbsp;use&nbsp;case,&nbsp;you&nbsp;must&nbsp;declare&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
| Life&nbsp;service | DAILY_LIFE_SERVICE | Applicable&nbsp;when&nbsp;your&nbsp;application&nbsp;only&nbsp;needs&nbsp;the&nbsp;approximate&nbsp;user&nbsp;location&nbsp;for&nbsp;recommendations&nbsp;and&nbsp;push&nbsp;notifications&nbsp;in&nbsp;scenarios&nbsp;such&nbsp;as&nbsp;when&nbsp;the&nbsp;user&nbsp;is&nbsp;browsing&nbsp;news,&nbsp;shopping&nbsp;online,&nbsp;and&nbsp;ordering&nbsp;food.<br/>By&nbsp;default,&nbsp;the&nbsp;system&nbsp;reports&nbsp;location&nbsp;results&nbsp;at&nbsp;a&nbsp;minimal&nbsp;interval&nbsp;of&nbsp;1s.&nbsp;To&nbsp;adopt&nbsp;this&nbsp;use&nbsp;case,&nbsp;you&nbsp;must&nbsp;declare&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
| Power&nbsp;efficiency | NO_POWER | Applicable&nbsp;when&nbsp;your&nbsp;application&nbsp;does&nbsp;not&nbsp;proactively&nbsp;start&nbsp;the&nbsp;location&nbsp;service&nbsp;for&nbsp;a&nbsp;higher&nbsp;battery&nbsp;efficiency.&nbsp;When&nbsp;responding&nbsp;to&nbsp;another&nbsp;application&nbsp;requesting&nbsp;the&nbsp;same&nbsp;location&nbsp;service,&nbsp;the&nbsp;system&nbsp;marks&nbsp;a&nbsp;copy&nbsp;of&nbsp;the&nbsp;location&nbsp;result&nbsp;to&nbsp;your&nbsp;application.&nbsp;In&nbsp;this&nbsp;way,&nbsp;your&nbsp;application&nbsp;will&nbsp;not&nbsp;consume&nbsp;extra&nbsp;power&nbsp;for&nbsp;obtaining&nbsp;the&nbsp;user&nbsp;location.<br/>By&nbsp;default,&nbsp;the&nbsp;system&nbsp;reports&nbsp;location&nbsp;results&nbsp;at&nbsp;a&nbsp;minimal&nbsp;interval&nbsp;of&nbsp;1s.&nbsp;To&nbsp;adopt&nbsp;this&nbsp;use&nbsp;case,&nbsp;you&nbsp;must&nbsp;declare&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
The following example instantiates the **RequestParam** object for navigation:
```
var requestInfo = {'scenario': 0x301, '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,
}
```
**Table3** Location priority policies
| Policy | Constant | Description |
| -------- | -------- | -------- |
| Location&nbsp;accuracy&nbsp;priority | ACCURACY | This&nbsp;policy&nbsp;mainly&nbsp;uses&nbsp;the&nbsp;GNSS&nbsp;positioning&nbsp;technology.&nbsp;In&nbsp;an&nbsp;open&nbsp;area,&nbsp;the&nbsp;technology&nbsp;can&nbsp;achieve&nbsp;the&nbsp;meter-level&nbsp;location&nbsp;accuracy,&nbsp;depending&nbsp;on&nbsp;the&nbsp;hardware&nbsp;performance&nbsp;of&nbsp;the&nbsp;device.&nbsp;However,&nbsp;in&nbsp;a&nbsp;shielded&nbsp;environment,&nbsp;the&nbsp;location&nbsp;accuracy&nbsp;may&nbsp;significantly&nbsp;decrease.<br/>To&nbsp;use&nbsp;this&nbsp;policy,&nbsp;you&nbsp;must&nbsp;declare&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
| Fast&nbsp;location&nbsp;priority | FAST_FIRST_FIX | This&nbsp;policy&nbsp;uses&nbsp;the&nbsp;GNSS&nbsp;positioning,&nbsp;base&nbsp;station&nbsp;positioning,&nbsp;WLAN&nbsp;positioning,&nbsp;and&nbsp;Bluetooth&nbsp;positioning&nbsp;technologies&nbsp;simultaneously&nbsp;to&nbsp;obtain&nbsp;the&nbsp;device&nbsp;location&nbsp;in&nbsp;both&nbsp;the&nbsp;indoor&nbsp;and&nbsp;outdoor&nbsp;scenarios.&nbsp;When&nbsp;all&nbsp;positioning&nbsp;technologies&nbsp;provide&nbsp;a&nbsp;location&nbsp;result,&nbsp;the&nbsp;system&nbsp;provides&nbsp;the&nbsp;most&nbsp;accurate&nbsp;location&nbsp;result&nbsp;for&nbsp;your&nbsp;application.&nbsp;This&nbsp;policy&nbsp;can&nbsp;lead&nbsp;to&nbsp;significant&nbsp;hardware&nbsp;resource&nbsp;consumption&nbsp;and&nbsp;power&nbsp;consumption.<br/>To&nbsp;use&nbsp;this&nbsp;policy,&nbsp;you&nbsp;must&nbsp;declare&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
| Power&nbsp;efficiency&nbsp;priority | LOW_POWER | This&nbsp;policy&nbsp;mainly&nbsp;uses&nbsp;the&nbsp;base&nbsp;station&nbsp;positioning,&nbsp;WLAN&nbsp;positioning,&nbsp;and&nbsp;Bluetooth&nbsp;positioning&nbsp;technologies&nbsp;to&nbsp;obtain&nbsp;device&nbsp;location&nbsp;in&nbsp;both&nbsp;indoor&nbsp;and&nbsp;outdoor&nbsp;scenarios.&nbsp;The&nbsp;location&nbsp;accuracy&nbsp;depends&nbsp;on&nbsp;the&nbsp;distribution&nbsp;of&nbsp;surrounding&nbsp;base&nbsp;stations,&nbsp;visible&nbsp;WLANs,&nbsp;and&nbsp;Bluetooth&nbsp;devices&nbsp;and&nbsp;therefore&nbsp;may&nbsp;fluctuate&nbsp;greatly.&nbsp;This&nbsp;policy&nbsp;is&nbsp;recommended&nbsp;and&nbsp;can&nbsp;reduce&nbsp;power&nbsp;consumption&nbsp;when&nbsp;your&nbsp;application&nbsp;does&nbsp;not&nbsp;require&nbsp;high&nbsp;location&nbsp;accuracy&nbsp;or&nbsp;when&nbsp;base&nbsp;stations,&nbsp;visible&nbsp;WLANs,&nbsp;and&nbsp;Bluetooth&nbsp;devices&nbsp;are&nbsp;densely&nbsp;distributed.<br/>To&nbsp;use&nbsp;this&nbsp;policy,&nbsp;you&nbsp;must&nbsp;declare&nbsp;at&nbsp;least&nbsp;the&nbsp;**ohos.permission.LOCATION**&nbsp;permission&nbsp;and&nbsp;obtain&nbsp;users'&nbsp;authorization. |
The following example instantiates the **RequestParam** object for the location accuracy priority policy:
```
var requestInfo = {'priority': 0x201, '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 interface 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((data) => {
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.
......@@ -29,6 +29,5 @@ You can install your OpenHarmony app in either of the following methods:
hdc_std hilog
```
For details about how to use hdc and the command format, see [hdc\_std Usage Guidelines](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/oem_subsys_toolchain_hdc_guide.md).
For details about how to use hdc and the command format, see [hdc\_std Usage Guidelines](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-toolchain-hdc-guide.md).
......@@ -48,6 +48,7 @@
- Network and Connectivity
- [WLAN](js-apis-wifi.md)
- [Bluetooth](js-apis-bluetooth.md)
- [RPC](js-apis-rpc.md)
- Device Management
- [Sensor](js-apis-sensor.md)
- [Vibrator](js-apis-vibrator.md)
......@@ -63,6 +64,7 @@
- [Display](js-apis-display.md)
- [Update](js-apis-update.md)
- [USB](js-apis-usb.md)
- [Location](js-apis-geolocation.md)
- Basic Features
- [Application Context](js-apis-basic-features-app-context.md)
- [Console Logs](js-apis-basic-features-logs.md)
......
......@@ -1139,7 +1139,7 @@ Resets the **Query** object that contains common query options.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object reset.|
| [Query](#query8) |**Query** object reset.|
- Example
......@@ -1174,7 +1174,7 @@ Creates a **Query** object to match the specified field whose value is equal to
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1207,7 +1207,7 @@ Creates a **Query** object to match the specified field whose value is not equal
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1240,7 +1240,7 @@ Creates a **Query** object to match the specified field whose value is greater t
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1273,7 +1273,7 @@ Creates a **Query** object to match the specified field whose value is less than
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1306,7 +1306,7 @@ Creates a **Query** object to match the specified field whose value is greater t
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1339,7 +1339,7 @@ Creates a **Query** object to match the specified field whose value is less than
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1371,7 +1371,7 @@ Creates a **Query** object to match the specified field whose value is **null**.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1404,7 +1404,7 @@ Creates a **Query** object to match the specified field whose value is within th
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1438,7 +1438,7 @@ Creates a **Query** object to match the specified field whose value is within th
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1471,7 +1471,7 @@ Creates a **Query** object to match the specified field whose value is not withi
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1504,7 +1504,7 @@ Creates a **Query** object to match the specified field whose value is not withi
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1537,7 +1537,7 @@ Creates a **Query** object to match the specified field whose value is similar t
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1570,7 +1570,7 @@ Creates a **Query** object to match the specified field whose value is not simil
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1596,7 +1596,7 @@ Creates a **Query** object with the AND condition.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1624,7 +1624,7 @@ Creates a **Query** object with the OR condition.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1658,7 +1658,7 @@ Creates a **Query** object to sort the query results in ascending order.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1691,7 +1691,7 @@ Creates a **Query** object to sort the query results in descending order.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1726,7 +1726,7 @@ Creates a **Query** object to specify the number of results and where to start.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1759,7 +1759,7 @@ Creates a **Query** object with a specified field that is not null.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1785,7 +1785,7 @@ Creates a **Query** object for a query condition group with a left parenthesis.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1813,7 +1813,7 @@ Creates a **Query** object for a query condition group with a right parenthesis.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1847,7 +1847,7 @@ Creates a **Query** object with a specified key prefix.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1880,7 +1880,7 @@ Creates a **Query** object with an index preferentially used for query.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1914,7 +1914,7 @@ Creates a **Query** object with the device ID as the key prefix.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object created.|
| [Query](#query8) |**Query** object created.|
- Example
......@@ -1939,7 +1939,7 @@ Obtains the query statement of this **Query** object.
| Type| Description|
| ------ | ------- |
| [Query](#querysup8sup) |**Query** object.|
| [Query](#query8) |**Query** object.|
- Example
......@@ -2122,8 +2122,8 @@ Subscribes to data changes of the specified type. This method uses a synchronous
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| event |'dataChange' | Yes|Type of the events to subscribe to.|
| type |[SubscribeType](#subscribetypea) | Yes|Type of data changes.|
| observer |Callback&lt;[ChangeNotification](#changenotificationa)&gt; | Yes|Callback used to return the result.|
| type |[SubscribeType](#subscribetype) | Yes|Type of data changes.|
| observer |Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes|Callback used to return the result.|
- Example
......@@ -2170,7 +2170,7 @@ Unsubscribes from data change events. This method uses a synchronouscallback to
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| event |'dataChange' | Yes|Type of the events to unsubscribe from.|
| observer |Callback&lt;[ChangeNotification](#changenotificationa)&gt; |No|Callback used to return the result.|
| observer |Callback&lt;[ChangeNotification](#changenotification)&gt; |No|Callback used to return the result.|
- Example
......@@ -2962,7 +2962,7 @@ Obtains the KV pairs that match the specified **Query** object. This method uses
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;Entry[]&gt; | Yes|Callback used to return the KV pairs obtained.|
- Example
......@@ -3011,7 +3011,7 @@ Obtains the KV pairs that match the specified **Query** object. This method uses
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
......@@ -3067,7 +3067,7 @@ Obtains the result set with the specified key prefix from this single KV store.
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| keyPrefix |string | Yes|Key prefix to match.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; | Yes|Callback used to return the result set obtained.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes|Callback used to return the result set obtained.|
- Example
......@@ -3119,7 +3119,7 @@ Obtains the result set with the specified key prefix from this single KV store.
| Type| Description|
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; |Promise used to return the result set obtained.|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise used to return the result set obtained.|
- Example
......@@ -3172,7 +3172,7 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |Query | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -3217,13 +3217,13 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
| Type| Description|
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -3271,7 +3271,7 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#kvstoreresultsetsup8sup) | Yes|**KvStoreResultSet** object to close.|
| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes|**KvStoreResultSet** object to close.|
| callback |AsyncCallback&lt;void&gt; | Yes|Callback used to return the execution result.|
- Example
......@@ -3303,7 +3303,7 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#kvstoreresultsetsup8sup) | Yes|**KvStoreResultSet** object to close.|
| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes|**KvStoreResultSet** object to close.|
- Return value
......@@ -3338,7 +3338,7 @@ Obtains the number of results matching the specified **Query** object. This meth
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;number&gt; | Yes|Callback used to return the number of results obtained.|
- Example
......@@ -3382,7 +3382,7 @@ Obtains the number of results matching the specified **Query** object. This meth
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
......@@ -3910,7 +3910,7 @@ Obtains the KV pairs matching the specified **Query** object. This method uses a
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes|Callback used to return the KV pairs obtained.|
- Example
......@@ -3961,7 +3961,7 @@ Obtains the KV pairs matching the specified **Query** object. This method uses a
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
......@@ -4018,7 +4018,7 @@ Obtains the KV pairs matching the specified **Query** object for a device. This
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes|ID of the target device.|
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes|Callback used to return the KV pairs obtained.|
- Example
......@@ -4070,7 +4070,7 @@ Obtains the KV pairs matching the specified **Query** object for a device. This
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes|ID of the target device.|
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
......@@ -4129,7 +4129,7 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes|ID of the target device.|
| keyPrefix |string | Yes|Key prefix to match.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -4167,7 +4167,7 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo
| Type| Description|
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -4202,8 +4202,8 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -4252,13 +4252,13 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
| Type| Description|
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -4315,8 +4315,8 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes|ID of the target device.|
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | Yes|Callback used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -4365,13 +4365,13 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes|ID of the target device.|
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
| Type| Description|
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
- Example
......@@ -4428,7 +4428,7 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#getresultsetsup8sup) | Yes|**KvStoreResultSet** object to close.|
| resultSet |[KvStoreResultSet](#getresultset8) | Yes|**KvStoreResultSet** object to close.|
| callback |AsyncCallback&lt;void&gt; | Yes|Callback used to return the result.|
- Example
......@@ -4461,7 +4461,7 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#getresultsetsup8sup) | Yes|**KvStoreResultSet** object to close.|
| resultSet |[KvStoreResultSet](#getresultset8) | Yes|**KvStoreResultSet** object to close.|
- Return value
......@@ -4497,7 +4497,7 @@ Obtains the number of results that matches the specified **Query** object. This
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;number&gt; | Yes|Callback used to return the number of results obtained.|
- Example
......@@ -4542,7 +4542,7 @@ Obtains the number of results that matches the specified **Query** object. This
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
......@@ -4597,7 +4597,7 @@ Obtains the number of results that matches the specified **Query** object for a
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes|ID of the target device.|
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
| callback |AsyncCallback&lt;number&gt; | Yes|Callback used to return the number of results obtained.|
- Example
......@@ -4642,7 +4642,7 @@ Obtains the number of results that matches the specified **Query** object for a
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes|ID of the target device.|
| query |[Query](#querysup8sup) | Yes|**Query** object to match.|
| query |[Query](#query8) | Yes|**Query** object to match.|
- Return value
......
# Geolocation - New
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import geolocation from '@ohos.geolocation';
```
## Required Permissions
ohos.permission.LOCATION
ohos.permission.LOCATION_IN_BACKGROUND
## geolocation.on('locationChange')
on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;) : void
Registers a listener for location changes with a location request initiated.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**locationChange**&nbsp;indicates&nbsp;a&nbsp;location&nbsp;change&nbsp;event. |
| request | LocationRequest | Yes | Location&nbsp;request. |
| callback | Callback&lt;[Location](#location)&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;change&nbsp;event. |
- Example
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
geolocation.on('locationChange', requestInfo, locationChange);
```
## geolocation.off('locationChange')
off(type: 'locationChange', callback?: Callback&lt;Location&gt;) : void
Unregisters the listener for location changes with the corresponding location request deleted.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**locationChange**&nbsp;indicates&nbsp;a&nbsp;location&nbsp;change&nbsp;event. |
| callback | Callback&lt;[Location](#location)&gt; | No | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;change&nbsp;event. |
- Example
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
geolocation.on('locationChange', requestInfo, locationChange);
geolocation.off('locationChange', locationChange);
```
## geolocation.on('locationServiceState')
on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void
Registers a listener for location service status change events.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**locationServiceState**&nbsp;indicates&nbsp;a&nbsp;location&nbsp;service&nbsp;status&nbsp;change&nbsp;event. |
| callback | Callback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;service&nbsp;status&nbsp;change&nbsp;event. |
- Example
```
var locationServiceState = (state) => {
console.log('locationServiceState: ' + state);
}
geolocation.on('locationServiceState', locationServiceState);
```
## geolocation.off('locationServiceState')
off(type: 'locationServiceState', callback?: Callback&lt;boolean&gt;) : void;
Unregisters the listener for location service status change events.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**locationServiceState**&nbsp;indicates&nbsp;a&nbsp;location&nbsp;service&nbsp;status&nbsp;change&nbsp;event. |
| callback | Callback&lt;boolean&gt; | No | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;service&nbsp;status&nbsp;change&nbsp;event. |
- Example
```
var locationServiceState = (state) => {
console.log('locationServiceState: state: ' + state);
}
geolocation.on('locationServiceState', locationServiceState);
geolocation.off('locationServiceState', locationServiceState);
```
## geolocation.on('cachedGnssLocationsReporting')
on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;) : void;
Registers a listener for cached GNSS location reports.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**cachedGnssLocationsReporting**&nbsp;indicates&nbsp;reporting&nbsp;of&nbsp;cached&nbsp;GNSS&nbsp;locations. |
| request | CachedGnssLocationsRequest | Yes | Request&nbsp;for&nbsp;reporting&nbsp;cached&nbsp;GNSS&nbsp;location. |
| callback | Callback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;cached&nbsp;GNSS&nbsp;locations. |
- Example
```
var cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsReporting: locations: ' + locations);
}
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);
```
## geolocation.off('cachedGnssLocationsReporting')
off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;) : void;
Unregisters the listener for cached GNSS location reports.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**cachedGnssLocationsReporting**&nbsp;indicates&nbsp;reporting&nbsp;of&nbsp;cached&nbsp;GNSS&nbsp;locations. |
| callback | Callback&lt;boolean&gt; | No | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;cached&nbsp;GNSS&nbsp;locations. |
- Example
```
var cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsReporting: locations: ' + locations);
}
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);
geolocation.off('cachedGnssLocationsReporting');
```
## geolocation.on('gnssStatusChange')
on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) : void;
Registers a listener for GNSS satellite status change events.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**gnssStatusChange**&nbsp;indicates&nbsp;a&nbsp;GNSS&nbsp;satellite&nbsp;status&nbsp;change. |
| callback | Callback&lt;SatelliteStatusInfo&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;GNSS&nbsp;satellite&nbsp;status&nbsp;changes. |
- Example
```
var gnssStatusCb = (satelliteStatusInfo) => {
console.log('gnssStatusChange: ' + satelliteStatusInfo);
}
geolocation.on('gnssStatusChange', gnssStatusCb);
```
## geolocation.off('gnssStatusChange')
off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;) : void;
Unregisters the listener for GNSS satellite status change events.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**gnssStatusChange**&nbsp;indicates&nbsp;a&nbsp;GNSS&nbsp;satellite&nbsp;status&nbsp;change. |
| callback | Callback&lt;SatelliteStatusInfo&gt; | No | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;GNSS&nbsp;satellite&nbsp;status&nbsp;changes. |
- Example
```
var gnssStatusCb = (satelliteStatusInfo) => {
console.log('gnssStatusChange: ' + satelliteStatusInfo);
}
geolocation.on('gnssStatusChange', gnssStatusCb);
geolocation.off('gnssStatusChange', gnssStatusCb);
```
## geolocation.on('nmeaMessageChange')
on(type: 'nmeaMessageChange', callback: Callback&lt;string&gt;) : void;
Registers a listener for GNSS NMEA message change events.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**nmeaMessageChange**&nbsp;indicates&nbsp;a&nbsp;GNSS&nbsp;NMEA&nbsp;message&nbsp;change. |
| callback | Callback&lt;string&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;GNSS&nbsp;NMEA&nbsp;message&nbsp;changes. |
- Example
```
var nmeaCb = (str) => {
console.log('nmeaMessageChange: ' + str);
}
geolocation.on('nmeaMessageChange', nmeaCb );
```
## geolocation.off('nmeaMessageChange')
off(type: 'nmeaMessageChange', callback?: Callback&lt;string&gt;) : void;
Unregisters the listener for GNSS NMEA message change events.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**nmeaMessageChange**&nbsp;indicates&nbsp;a&nbsp;GNSS&nbsp;NMEA&nbsp;message&nbsp;change. |
| callback | Callback&lt;string&gt; | No | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;GNSS&nbsp;NMEA&nbsp;message&nbsp;changes. |
- Example
```
var nmeaCb = (str) => {
console.log('nmeaMessageChange: ' + str);
}
geolocation.on('nmeaMessageChange', nmeaCb);
geolocation.off('nmeaMessageChange', nmeaCb);
```
## geolocation.on('fenceStatusChange')
on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void;
Registers a listener for status change events of the specified geofence.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**fenceStatusChange**&nbsp;indicates&nbsp;a&nbsp;geofence&nbsp;status&nbsp;change. |
| request | GeofenceRequest | Yes | Geofencing&nbsp;request. |
| want | WantAgent | Yes | **WantAgent**&nbsp;used&nbsp;to&nbsp;return&nbsp;geofence&nbsp;(entrance&nbsp;or&nbsp;exit)&nbsp;events. |
- Example
```
import WantAgent from '@ohos.wantAgent';
import { OperationType, WantAgentFlags } from '@ohos.wantagent';
// WantAgent object
var wantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info("==========================>getWantAgentCallback=======================>");
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// WantAgentInfo object
var wantAgentInfo = {
wants: [
{
deviceId: "deviceId",
bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters:
{
mykey0: 2222,
mykey1: [1, 2, 3],
mykey2: "[1, 2, 3]",
mykey3: "ssssssssssssssssssssssssss",
mykey4: [false, true, false],
mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
mykey6: true,
}
}
],
operationType: OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG]
}
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
geolocation.on('fenceStatusChange', requestInfo, wantAgent);
```
## geolocation.off('fenceStatusChange')
off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void;
Unregisters the listener for status change events of the specified geofence.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | string | Yes | Event&nbsp;type.&nbsp;The&nbsp;value&nbsp;**fenceStatusChange**&nbsp;indicates&nbsp;a&nbsp;geofence&nbsp;status&nbsp;change. |
| request | GeofenceRequest | Yes | Geofencing&nbsp;request. |
| want | WantAgent | Yes | **WantAgent**&nbsp;used&nbsp;to&nbsp;return&nbsp;geofence&nbsp;(entrance&nbsp;or&nbsp;exit)&nbsp;events. |
- Example
```
import WantAgent from '@ohos.wantAgent';
import { OperationType, WantAgentFlags } from '@ohos.wantagent';
// WantAgent object
var wantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info("==========================>getWantAgentCallback=======================>");
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// WantAgentInfo object
var wantAgentInfo = {
wants: [
{
deviceId: "deviceId",
bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters:
{
mykey0: 2222,
mykey1: [1, 2, 3],
mykey2: "[1, 2, 3]",
mykey3: "ssssssssssssssssssssssssss",
mykey4: [false, true, false],
mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
mykey6: true,
}
}
],
operationType: OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG]
}
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
geolocation.on('fenceStatusChange', requestInfo, wantAgent);
geolocation.off('fenceStatusChange', requestInfo, wantAgent);
```
## geolocation.getCurrentLocation
getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;) : void
Obtains the current location. This method uses an asynchronous callback to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| request | [CurrentLocationRequest](#currentlocationrequest) | No | Location&nbsp;request. |
| callback | AsyncCallback&lt;[Location](#location)&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;current&nbsp;location. |
- Example
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
var locationChange = (err, location) => {
console.log('locationChanger: ' + err + 'data: ' + location);
};
geolocation.getCurrentLocation(requestInfo, locationChange);
geolocation.getCurrentLocation(locationChange);
```
## geolocation.getCurrentLocation
getCurrentLocation(request?: CurrentLocationRequest) : Promise&lt;Location&gt;
Obtains the current location. This method uses a promise to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| request | [CurrentLocationRequest](#currentlocationrequest) | No | Location&nbsp;request. |
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;[Location](#location)&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;current&nbsp;location. |
- Example
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
locationEventListener.getCurrentLocation(requestInfo).then((result) => {
console.log('current location: ' + JSON.stringify(result));
});
```
## geolocation.getLastLocation
getLastLocation(callback: AsyncCallback&lt;Location&gt;) : void
Obtains the previous location. This method uses an asynchronous callback to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[Location](#location)&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;previous&nbsp;location. |
- Example
```
geolocation.getLastLocation((err, data) => {
console.log('getLastLocation: ' + err + " data: " + JSON.stringify(data));
});
```
## geolocation.getLastLocation
getLastLocation() : Promise&lt;Location&gt;
Obtains the previous location. This method uses a promise to return the result.
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;[Location](#location)&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;previous&nbsp;location. |
- Example
```
geolocation.getLastLocation().then((result) => {
console.log('getLastLocation: result: ' + JSON.stringify(result));
});
```
## geolocation.isLocationEnabled
isLocationEnabled(callback: AsyncCallback&lt;boolean&gt;) : void
Checks whether the location service is enabled. This method uses an asynchronous callback to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;service&nbsp;status. |
- Example
```
geolocation.isLocationEnabled((err, data) => {
console.log('isLocationEnabled: ' + err + " data: " + data);
});
```
## geolocation.isLocationEnabled
isLocationEnabled() : Promise&lt;boolean&gt;
Checks whether the location service is enabled. This method uses a promise to return the result.
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;service&nbsp;status. |
- Example
```
geolocation.isLocationEnabled().then((result) => {
console.log('promise, isLocationEnabled: ' + result);
});
```
## geolocation.requestEnableLocation
requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;) : void
Requests to enable the location service. This method uses an asynchronous callback to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;service&nbsp;status. |
- Example
```
geolocation.requestEnableLocation((err, data) => {
console.log('requestEnableLocation: ' + err + " data: " + data);
});
```
## geolocation.requestEnableLocation
requestEnableLocation() : Promise&lt;boolean&gt;
Requests to enable the location service. This method uses a promise to return the result.
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;location&nbsp;service&nbsp;status. |
- Example
```
geolocation.requestEnableLocation().then((result) => {
console.log('promise, requestEnableLocation: ' + result);
});
```
## geolocation.isGeoServiceAvailable
isGeoServiceAvailable(callback: AsyncCallback&lt;boolean&gt;) : void
Checks whether the (reverse) geocoding service is available. This method uses an asynchronous callback to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;(reverse)&nbsp;geocoding&nbsp;service&nbsp;status. |
- Example
```
geolocation.isGeoServiceAvailable((err, data) => {
console.log('isGeoServiceAvailable: ' + err + " data: " + data);
});
```
## geolocation.isGeoServiceAvailable
isGeoServiceAvailable() : Promise&lt;boolean&gt;
Checks whether the (reverse) geocoding service is available. This method uses a promise to return the result.
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;(reverse)&nbsp;geocoding&nbsp;service&nbsp;status. |
- Example
```
geolocation.isGeoServiceAvailable().then((result) => {
console.log('promise, isGeoServiceAvailable: ' + result);
});
```
## geolocation.getAddressesFromLocation
getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void
Converts coordinates into geographic description through reverse geocoding. This method uses an asynchronous callback to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes | Reverse&nbsp;geocoding&nbsp;request. |
| callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;reverse&nbsp;geocoding&nbsp;result. |
- Example
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
console.log('getAddressesFromLocation: ' + err + " data: " + JSON.stringify(data));
});
```
## geolocation.getAddressesFromLocation
getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt;;
Converts coordinates into geographic description through reverse geocoding. This method uses a promise to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes | Reverse&nbsp;geocoding&nbsp;request. |
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;reverse&nbsp;geocoding&nbsp;result. |
- Example
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data));
});
```
## geolocation.getAddressesFromLocationName
getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void
Converts geographic description into coordinates through geocoding. This method uses an asynchronous callback to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| request | [GeoCodeRequest](#geocoderequest) | Yes | Geocoding&nbsp;request. |
| callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;geocoding&nbsp;result. |
- Example
```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
console.log('getAddressesFromLocationName: ' + err + " data: " + JSON.stringify(data));
});
```
## geolocation.getAddressesFromLocationName
getAddressesFromLocationName(request: GeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt;
Converts geographic description into coordinates through geocoding. This method uses a promise to return the result.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| request | [GeoCodeRequest](#geocoderequest) | Yes | Geocoding&nbsp;request. |
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;geocoding&nbsp;result. |
- Example
```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(result));
});
```
## geolocation.getCachedGnssLocationsSize
getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;) : void;
Obtains the number of cached GNSS locations.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;number&nbsp;of&nbsp;cached&nbsp;GNSS&nbsp;locations. |
- Example
```
geolocation.getCachedGnssLocationsSize((err, size) => {
console.log('getCachedGnssLocationsSize: err:' + err + " size: " + size);
});
```
## geolocation.getCachedGnssLocationsSize
getCachedGnssLocationsSize() : Promise&lt;number&gt;;
Obtains the number of cached GNSS locations.
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;number&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;number&nbsp;of&nbsp;cached&nbsp;GNSS&nbsp;locations. |
- Example
```
geolocation.getCachedGnssLocationsSize().then((result) => {
console.log('promise, getCachedGnssLocationsSize: ' + result);
});
```
## geolocation.flushCachedGnssLocations
flushCachedGnssLocations(callback: AsyncCallback&lt;boolean&gt;) : void;
Obtains all cached GNSS locations and clears the GNSS cache queue.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;operation&nbsp;result. |
- Example
```
geolocation.flushCachedGnssLocations((err, result) => {
console.log('flushCachedGnssLocations: err:' + err + " result: " + result);
});
```
## geolocation.flushCachedGnssLocations
flushCachedGnssLocations() : Promise&lt;boolean&gt;;
Obtains all cached GNSS locations and clears the GNSS cache queue.
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;operation&nbsp;result. |
- Example
```
geolocation.flushCachedGnssLocations().then((result) => {
console.log('promise, flushCachedGnssLocations: ' + result);
});
```
## geolocation.sendCommand
sendCommand(command: LocationCommand, callback: AsyncCallback&lt;boolean&gt;) : void;
Sends an extended command to the location subsystem. This function can only be called by system applications.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| command | LocationCommand | Yes | Extended&nbsp;command&nbsp;(string)&nbsp;to&nbsp;be&nbsp;sent. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;operation&nbsp;result. |
- Example
```
var requestInfo = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo, (err, result) => {
console.log('sendCommand: err:' + err + " result: " + result);
});
```
## geolocation.sendCommand
sendCommand(command: LocationCommand) : Promise&lt;boolean&gt;;
Sends extended commands to the location subsystem. This function can only be called by system applications.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| command | LocationCommand | Yes | Extended&nbsp;command&nbsp;(string)&nbsp;to&nbsp;be&nbsp;sent. |
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;operation&nbsp;result. |
- Example
```
var requestInfo = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo).then((result) => {
console.log('promise, sendCommand: ' + result);
});
```
## geolocation.isLocationPrivacyConfirmed
isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback&lt;boolean&gt;) : void;
Checks whether a user agrees with the privacy statement of the location service. This function can only be called by system applications.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | Yes | Privacy&nbsp;statement&nbsp;type,&nbsp;for&nbsp;example,&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;in&nbsp;the&nbsp;startup&nbsp;wizard&nbsp;or&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;when&nbsp;enabling&nbsp;the&nbsp;location&nbsp;service. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result,&nbsp;which&nbsp;indicates&nbsp;whether&nbsp;the&nbsp;user&nbsp;agrees&nbsp;with&nbsp;the&nbsp;privacy&nbsp;statement. |
- Example
```
geolocation.isLocationPrivacyConfirmed(1, (err, result) => {
console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result);
});
```
## geolocation.isLocationPrivacyConfirmed
isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise&lt;boolean&gt;;
Checks whether a user agrees with the privacy statement of the location service. This function can only be called by system applications.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | Yes | Privacy&nbsp;statement&nbsp;type,&nbsp;for&nbsp;example,&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;in&nbsp;the&nbsp;startup&nbsp;wizard&nbsp;or&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;when&nbsp;enabling&nbsp;the&nbsp;location&nbsp;service. |
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result,&nbsp;which&nbsp;indicates&nbsp;whether&nbsp;the&nbsp;user&nbsp;agrees&nbsp;with&nbsp;the&nbsp;privacy&nbsp;statement. |
- Example
```
geolocation.isLocationPrivacyConfirmed(1).then((result) => {
console.log('promise, isLocationPrivacyConfirmed: ' + result);
});
```
## geolocation.setLocationPrivacyConfirmStatus
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback&lt;boolean&gt;) : void;
Sets the user confirmation status for the privacy statement of the location service. This function can only be called by system applications.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | Yes | Privacy&nbsp;statement&nbsp;type,&nbsp;for&nbsp;example,&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;in&nbsp;the&nbsp;startup&nbsp;wizard&nbsp;or&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;when&nbsp;enabling&nbsp;the&nbsp;location&nbsp;service. |
| isConfirmed | boolean | Yes | Whether&nbsp;the&nbsp;user&nbsp;agrees&nbsp;with&nbsp;the&nbsp;privacy&nbsp;statement&nbsp;of&nbsp;the&nbsp;location&nbsp;service. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;operation&nbsp;result. |
- Example
```
geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => {
console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result);
});
```
## geolocation.setLocationPrivacyConfirmStatus
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise&lt;boolean&gt;;
Sets the user confirmation status for the privacy statement of the location service. This function can only be called by system applications.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | Yes | Privacy&nbsp;statement&nbsp;type,&nbsp;for&nbsp;example,&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;in&nbsp;the&nbsp;startup&nbsp;wizard&nbsp;or&nbsp;privacy&nbsp;statement&nbsp;displayed&nbsp;when&nbsp;enabling&nbsp;the&nbsp;location&nbsp;service. |
| isConfirmed | boolean | Yes | Whether&nbsp;the&nbsp;user&nbsp;agrees&nbsp;with&nbsp;the&nbsp;privacy&nbsp;statement&nbsp;of&nbsp;the&nbsp;location&nbsp;service. |
- Return values
| Name | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;operation&nbsp;result. |
- Example
```
geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => {
console.log('promise, setLocationPrivacyConfirmStatus: ' + result);
});
```
## LocationRequestPriority
Sets the priority of the location request.
| Name | Default&nbsp;Value | Description |
| -------- | -------- | -------- |
| UNSET | 0x200 | Priority&nbsp;unspecified. |
| ACCURACY | 0x201 | Location&nbsp;accuracy. |
| LOW_POWER | 0x202 | Power&nbsp;efficiency. |
| FIRST_FIX | 0x203 | Fast&nbsp;location.&nbsp;Use&nbsp;this&nbsp;option&nbsp;if&nbsp;you&nbsp;want&nbsp;to&nbsp;obtain&nbsp;a&nbsp;location&nbsp;as&nbsp;fast&nbsp;as&nbsp;possible. |
## LocationRequestScenario
Sets the scenario of the location request.
| Name | Default&nbsp;Value | Description |
| -------- | -------- | -------- |
| UNSET | 0x300 | Scenario&nbsp;unspecified. |
| NAVIGATION | 0x301 | Navigation. |
| TRAJECTORY_TRACKING | 0x302 | Trajectory&nbsp;tracking. |
| CAR_HAILING | 0x303 | Ride&nbsp;hailing. |
| DAILY_LIFE_SERVICE | 0x304 | Daily&nbsp;life&nbsp;services. |
| NO_POWER | 0x305 | Power&nbsp;efficiency.&nbsp;Your&nbsp;application&nbsp;does&nbsp;not&nbsp;proactively&nbsp;start&nbsp;the&nbsp;location&nbsp;service.&nbsp;When&nbsp;responding&nbsp;to&nbsp;another&nbsp;application&nbsp;requesting&nbsp;the&nbsp;same&nbsp;location&nbsp;service,&nbsp;the&nbsp;system&nbsp;marks&nbsp;a&nbsp;copy&nbsp;of&nbsp;the&nbsp;location&nbsp;result&nbsp;to&nbsp;your&nbsp;application.&nbsp;In&nbsp;this&nbsp;way,&nbsp;your&nbsp;application&nbsp;will&nbsp;not&nbsp;consume&nbsp;extra&nbsp;power&nbsp;for&nbsp;obtaining&nbsp;the&nbsp;user&nbsp;location. |
## GeoLocationErrorCode
Enumerates error codes of the location service.
| Name | Default&nbsp;Value | Description |
| -------- | -------- | -------- |
| INPUT_PARAMS_ERROR | 101 | Incorrect&nbsp;input&nbsp;parameters. |
| REVERSE_GEOCODE_ERROR | 102 | Failed&nbsp;to&nbsp;call&nbsp;the&nbsp;reverse&nbsp;geocoding&nbsp;API. |
| GEOCODE_ERROR | 103 | Failed&nbsp;to&nbsp;call&nbsp;the&nbsp;geocoding&nbsp;API. |
| LOCATOR_ERROR | 104 | Failed&nbsp;to&nbsp;obtain&nbsp;the&nbsp;location. |
| LOCATION_SWITCH_ERROR | 105 | Failed&nbsp;to&nbsp;change&nbsp;the&nbsp;location&nbsp;service&nbsp;switch. |
| LAST_KNOWN_LOCATION_ERROR | 106 | Failed&nbsp;to&nbsp;obtain&nbsp;the&nbsp;previous&nbsp;location. |
| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | Failed&nbsp;to&nbsp;obtain&nbsp;the&nbsp;location&nbsp;within&nbsp;the&nbsp;specified&nbsp;time. |
## ReverseGeoCodeRequest
Defines a reverse geocoding request.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| locale | string | No | Language&nbsp;used&nbsp;for&nbsp;the&nbsp;location&nbsp;description.&nbsp;**zh**&nbsp;indicates&nbsp;Chinese,&nbsp;and&nbsp;**en**&nbsp;indicates&nbsp;English. |
| latitude | number | Yes | Latitude&nbsp;information.&nbsp;A&nbsp;positive&nbsp;value&nbsp;indicates&nbsp;north&nbsp;latitude,&nbsp;and&nbsp;a&nbsp;negative&nbsp;value&nbsp;indicates&nbsp;south&nbsp;latitude. |
| longitude | number | Yes | Longitude&nbsp;information.&nbsp;A&nbsp;positive&nbsp;value&nbsp;indicates&nbsp;east&nbsp;longitude&nbsp;,&nbsp;and&nbsp;a&nbsp;negative&nbsp;value&nbsp;indicates&nbsp;west&nbsp;longitude&nbsp;. |
| maxItems | number | No | Maximum&nbsp;number&nbsp;of&nbsp;location&nbsp;records&nbsp;to&nbsp;be&nbsp;returned. |
## GeoCodeRequest
Defines a geocoding request.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| locale | string | No | Language&nbsp;used&nbsp;for&nbsp;the&nbsp;location&nbsp;description.&nbsp;**zh**&nbsp;indicates&nbsp;Chinese,&nbsp;and&nbsp;**en**&nbsp;indicates&nbsp;English. |
| description | number | Yes | Location&nbsp;description,&nbsp;for&nbsp;example,&nbsp;**No.&nbsp;xx,&nbsp;xx&nbsp;Road,&nbsp;Pudong&nbsp;New&nbsp;District,&nbsp;Shanghai**. |
| maxItems | number | No | Maximum&nbsp;number&nbsp;of&nbsp;location&nbsp;records&nbsp;to&nbsp;be&nbsp;returned. |
| minLatitude | number | No | Minimum&nbsp;latitude.&nbsp;This&nbsp;parameter&nbsp;is&nbsp;used&nbsp;with&nbsp;**minLongitude**,&nbsp;**maxLatitude**,&nbsp;and&nbsp;**maxLongitude**&nbsp;to&nbsp;specify&nbsp;the&nbsp;latitude&nbsp;and&nbsp;longitude&nbsp;ranges. |
| minLongitude | number | No | Minimum&nbsp;longitude. |
| maxLatitude | number | No | Maximum&nbsp;latitude. |
| maxLongitude | number | No | Maximum&nbsp;longitude. |
## GeoAddress
Defines a geographic location.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| latitude | number | No | Latitude&nbsp;information.&nbsp;A&nbsp;positive&nbsp;value&nbsp;indicates&nbsp;north&nbsp;latitude,&nbsp;and&nbsp;a&nbsp;negative&nbsp;value&nbsp;indicates&nbsp;south&nbsp;latitude. |
| longitude | number | No | Longitude&nbsp;information.&nbsp;A&nbsp;positive&nbsp;value&nbsp;indicates&nbsp;east&nbsp;longitude&nbsp;,&nbsp;and&nbsp;a&nbsp;negative&nbsp;value&nbsp;indicates&nbsp;west&nbsp;longitude&nbsp;. |
| locale | string | No | Language&nbsp;used&nbsp;for&nbsp;the&nbsp;location&nbsp;description.&nbsp;**zh**&nbsp;indicates&nbsp;Chinese,&nbsp;and&nbsp;**en**&nbsp;indicates&nbsp;English. |
| placeName | string | No | Landmark&nbsp;of&nbsp;the&nbsp;location. |
| countryCode | string | No | Country&nbsp;code. |
| countryName | string | No | Country&nbsp;name. |
| administrativeArea | string | No | Administrative&nbsp;region&nbsp;name. |
| subAdministrativeArea | string | No | Sub-administrative&nbsp;region&nbsp;name. |
| locality | string | No | Locality&nbsp;information. |
| subLocality | string | No | Sub-locality&nbsp;information. |
| roadName | string | No | Road&nbsp;name. |
| subRoadName | string | No | Auxiliary&nbsp;road&nbsp;information. |
| premises | string | No | House&nbsp;information. |
| postalCode | string | No | Postal&nbsp;code. |
| phoneNumber | string | No | Phone&nbsp;number. |
| addressUrl | string | No | Website&nbsp;URL. |
| descriptions | Array&lt;string&gt; | No | Additional&nbsp;description. |
| descriptionsSize | number | No | Total&nbsp;number&nbsp;of&nbsp;additional&nbsp;descriptions. |
## LocationRequest
Defines a location request.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | No | Priority&nbsp;of&nbsp;the&nbsp;location&nbsp;request. |
| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes | Scenario&nbsp;of&nbsp;the&nbsp;location&nbsp;request. |
| timeInterval | number | No | Time&nbsp;interval&nbsp;at&nbsp;which&nbsp;location&nbsp;information&nbsp;is&nbsp;reported. |
| distanceInterval | number | No | Distance&nbsp;interval&nbsp;at&nbsp;which&nbsp;location&nbsp;information&nbsp;is&nbsp;reported. |
| maxAccuracy | number | No | Location&nbsp;accuracy. |
## CurrentLocationRequest
Defines the current location request.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | No | Priority&nbsp;of&nbsp;the&nbsp;location&nbsp;request. |
| scenario | [LocationRequestScenario](#locationrequestscenario) | No | Scenario&nbsp;of&nbsp;the&nbsp;location&nbsp;request. |
| maxAccuracy | number | No | Location&nbsp;accuracy,&nbsp;in&nbsp;meters. |
| timeoutMs | number | No | Timeout&nbsp;duration,&nbsp;in&nbsp;milliseconds.&nbsp;The&nbsp;minimum&nbsp;value&nbsp;is&nbsp;**1000**. |
## SatelliteStatusInfo
Defines the satellite status information.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| satellitesNumber | number | Yes | Number&nbsp;of&nbsp;satellites. |
| satelliteIds | Array&lt;number&gt; | Yes | Array&nbsp;of&nbsp;satellite&nbsp;IDs. |
| carrierToNoiseDensitys | Array&lt;number&gt; | Yes | Carrier-to-noise&nbsp;density&nbsp;ratio,&nbsp;that&nbsp;is,&nbsp;cn0. |
| altitudes | Array&lt;number&gt; | Yes | Altitude&nbsp;information. |
| azimuths | Array&lt;number&gt; | Yes | Azimuth&nbsp;information. |
| carrierFrequencies | Array&lt;number&gt; | Yes | Carrier&nbsp;frequency. |
## CachedGnssLocationsRequest
Represents a request for reporting cached GNSS locations.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| reportingPeriodSec | number | Yes | Interval&nbsp;for&nbsp;reporting&nbsp;the&nbsp;cached&nbsp;GNSS&nbsp;locations,&nbsp;in&nbsp;milliseconds. |
| wakeUpCacheQueueFull | boolean | Yes | **true**:&nbsp;reports&nbsp;the&nbsp;cached&nbsp;GNSS&nbsp;locations&nbsp;to&nbsp;the&nbsp;application&nbsp;when&nbsp;the&nbsp;cache&nbsp;queue&nbsp;is&nbsp;full.<br/>**false**:&nbsp;discards&nbsp;the&nbsp;cached&nbsp;GNSS&nbsp;locations&nbsp;when&nbsp;the&nbsp;cache&nbsp;queue&nbsp;is&nbsp;full. |
## Geofence
Defines a GNSS geofence. Currently, only circular geofences are supported.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| latitude | number | Yes | Latitude&nbsp;information. |
| longitude | number | Yes | Longitude&nbsp;information. |
| radius | number | Yes | Radius&nbsp;of&nbsp;a&nbsp;circular&nbsp;geofence. |
| expiration | number | Yes | Expiration&nbsp;period&nbsp;of&nbsp;a&nbsp;geofence,&nbsp;in&nbsp;milliseconds. |
## GeofenceRequest
Represents a GNSS geofencing request.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| priority | LocationRequestPriority | Yes | Priority&nbsp;of&nbsp;the&nbsp;location&nbsp;information. |
| scenario | LocationRequestScenario | Yes | Location&nbsp;scenario. |
| geofence | Geofence | Yes | Geofence&nbsp;information. |
## LocationPrivacyType
Defines the privacy statement type.
| Name | Default&nbsp;Value | Description |
| -------- | -------- | -------- |
| OTHERS | 0 | Other&nbsp;scenarios. |
| STARTUP | 1 | Privacy&nbsp;statement&nbsp;displayed&nbsp;in&nbsp;the&nbsp;startup&nbsp;wizard. |
| CORE_LOCATION | 2 | Privacy&nbsp;statement&nbsp;displayed&nbsp;when&nbsp;enabling&nbsp;the&nbsp;location&nbsp;service. |
## LocationCommand
Defines an extended command.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| scenario | LocationRequestScenario | Yes | Location&nbsp;scenario. |
| command | string | Yes | Extended&nbsp;command,&nbsp;in&nbsp;the&nbsp;string&nbsp;format. |
## Location
Defines a location.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| latitude | number | Yes | Latitude&nbsp;information.&nbsp;A&nbsp;positive&nbsp;value&nbsp;indicates&nbsp;north&nbsp;latitude,&nbsp;and&nbsp;a&nbsp;negative&nbsp;value&nbsp;indicates&nbsp;south&nbsp;latitude. |
| longitude | number | Yes | Longitude&nbsp;information.&nbsp;A&nbsp;positive&nbsp;value&nbsp;indicates&nbsp;east&nbsp;longitude&nbsp;,&nbsp;and&nbsp;a&nbsp;negative&nbsp;value&nbsp;indicates&nbsp;west&nbsp;longitude&nbsp;. |
| altitude | number | Yes | Location&nbsp;altitude,&nbsp;in&nbsp;meters. |
| accuracy | number | Yes | Location&nbsp;accuracy,&nbsp;in&nbsp;meters. |
| speed | number | Yes | Speed,&nbsp;in&nbsp;m/s. |
| timeStamp | number | Yes | Location&nbsp;timestamp&nbsp;in&nbsp;the&nbsp;UTC&nbsp;format. |
| direction | number | Yes | Direction&nbsp;information. |
| timeSinceBoot | number | Yes | Location&nbsp;timestamp&nbsp;since&nbsp;boot. |
| additions | Array&lt;string&gt; | No | Additional&nbsp;description. |
| additionSize | number | No | Number&nbsp;of&nbsp;additional&nbsp;descriptions. |
# RPC Communication
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import rpc from '@ohos.rpc';
```
## Required Permissions
None
## MessageParcel
Provides methods for reading and writing basic data types and arrays, inter-process communication (IPC) objects, interface tokens, and sequenceable objects.
### create
create(): MessageParcel
Creates a **MessageParcel** object. This method is a static method.
- Return values
| Type | Description |
| -------- | -------- |
| MessageParcel | **MessageParcel**&nbsp;object&nbsp;created. |
- Example
```
let data = rpc.MessageParcel.create();
console.log("RpcClient: data is " + data);
```
### reclaim
reclaim(): void
Reclaims the **MessageParcel** instance that is no longer used.
- Example
```
let reply = rpc.MessageParcel.create();
reply.reclaim();
```
### writeRemoteObject
writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean
Serializes a remote object and writes it to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| object | [IRemoteObject](#iremoteobject) | Yes | Remote&nbsp;object&nbsp;to&nbsp;serialize&nbsp;and&nbsp;write&nbsp;to&nbsp;the&nbsp;**MessageParcel**&nbsp;object. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let data = rpc.MessageParcel.create();
let testRemoteObject = new TestRemoteObject("testObject");
data.writeRemoteObject(testRemoteObject);
```
### readRemoteObject
readRemoteObject(): IRemoteObject
Reads the remote object from this **MessageParcel** object. You can use this method to deserialize the **MessageParcel** object to generate an **IRemoteObject**. The remote objects are read in the order in which they are written to this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| [IRemoteObject](#iremoteobject) | Remote&nbsp;object&nbsp;obtained. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let data = rpc.MessageParcel.create();
let testRemoteObject = new TestRemoteObject("testObject");
data.writeRemoteObject(testRemoteObject);
let proxy = data.readRemoteObject();
```
### writeInterfaceToken
writeInterfaceToken(token: string): boolean
Writes an interface token to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| token | string | Yes | Interface&nbsp;token&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeInterfaceToken("aaa");
console.log("RpcServer: writeInterfaceToken is " + result);
```
### readInterfaceToken
readInterfaceToken(): string
Reads the interface token from this **MessageParcel** object. The interface tokens are read in the order in which they are written into the **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| string | Interface&nbsp;token&nbsp;obtained. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let interfaceToken = data.readInterfaceToken();
console.log("RpcServer: interfaceToken is " + interfaceToken);
return true;
}
}
```
### getSize
getSize(): number
Obtains the data size of this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | Data&nbsp;size&nbsp;obtained,&nbsp;in&nbsp;bytes. |
- Example
```
let data = rpc.MessageParcel.create();
let size = data.getSize();
console.log("RpcClient: size is " + size);
```
### getCapacity
getCapacity(): number
Obtains the capacity of this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **MessageParcel**&nbsp;capacity&nbsp;obtained,&nbsp;in&nbsp;bytes. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.getCapacity();
console.log("RpcClient: capacity is " + result);
```
### setSize
setSize(size: number): boolean
Sets the size of data contained in this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| size | number | Yes | Data&nbsp;size&nbsp;to&nbsp;set,&nbsp;in&nbsp;bytes. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let setSize = data.setSize(16);
console.log("RpcClient: setSize is " + setSize);
```
### setCapacity
setCapacity(size: number): boolean
Sets the storage capacity of this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| size | number | Yes | Storage&nbsp;capacity&nbsp;to&nbsp;set,&nbsp;in&nbsp;bytes. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.setCapacity(100);
console.log("RpcClient: setCapacity is " + result);
```
### getWritableBytes
getWritableBytes(): number
Obtains the writable capacity of this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **MessageParcel**&nbsp;writable&nbsp;capacity&nbsp;obtained,&nbsp;in&nbsp;bytes. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let getWritableBytes = data.getWritableBytes();
console.log("RpcServer: getWritableBytes is " + getWritableBytes);
return true;
}
}
```
### getReadableBytes
getReadableBytes(): number
Obtains the readable capacity of this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **MessageParcel**&nbsp;readable&nbsp;capacity&nbsp;obtained,&nbsp;in&nbsp;bytes. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let result = data.getReadableBytes();
console.log("RpcServer: getReadableBytes is " + result);
return true;
}
}
```
### getReadPosition
getReadPosition(): number
Obtains the read position of this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | Current&nbsp;read&nbsp;position&nbsp;of&nbsp;the&nbsp;**MessageParcel**&nbsp;object. |
- Example
```
let data = rpc.MessageParcel.create();
let readPos = data.getReadPosition();
console.log("RpcClient: readPos is " + readPos);
```
### getWritePosition
getWritePosition(): number
Obtains the write position of this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | Current&nbsp;write&nbsp;position&nbsp;of&nbsp;the&nbsp;**MessageParcel**&nbsp;object. |
- Example
```
let data = rpc.MessageParcel.create();
data.writeInt(10);
let bwPos = data.getWritePosition();
console.log("RpcClient: bwPos is " + bwPos);
```
### rewindRead
rewindRead(pos: number): boolean
Moves the read pointer to the specified position.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| pos | number | Yes | Position&nbsp;from&nbsp;which&nbsp;data&nbsp;is&nbsp;to&nbsp;read. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;read&nbsp;position&nbsp;changes;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
data.writeInt(12);
data.writeString("parcel");
let number = data.readInt();
console.log("RpcClient: number is " + number);
data.rewindRead(0);
let number2 = data.readInt();
console.log("RpcClient: rewindRead is " + number2);
```
### rewindWrite
rewindWrite(pos: number): boolean
Moves the write pointer to the specified position.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| pos | number | Yes | Position&nbsp;from&nbsp;which&nbsp;data&nbsp;is&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;write&nbsp;position&nbsp;changes;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
data.writeInt(4);
data.rewindWrite(0);
data.writeInt(5);
let number = data.readInt();
console.log("RpcClient: rewindWrite is: " + number);
```
### writeByte
writeByte(val: number): boolean
Writes a **Byte** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | number | Yes | **Byte**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result);
```
### readByte
readByte(): number
Reads the **Byte** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **Byte**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result);
let ret = data.readByte();
console.log("RpcClient: readByte is: " + ret);
```
### writeShort
writeShort(val: number): boolean
Writes a **Short int** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | number | Yes | **Short&nbsp;int**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result);
```
### readShort
readShort(): number
Reads the **Short int** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **Short&nbsp;int**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result);
let ret = data.readShort();
console.log("RpcClient: readShort is: " + ret);
```
### writeInt
writeInt(val: number): boolean
Writes an **Int** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | number | Yes | **Int**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result);
```
### readInt
readInt(): number
Reads the **Int** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **Int**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result);
let ret = data.readInt();
console.log("RpcClient: readInt is " + ret);
```
### writeLong
writeLong(val: number): boolean
Writes a **Long int** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | number | Yes | **Long&nbsp;int**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result);
```
### readLong
readLong(): number
Reads the **Long int** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **Long&nbsp;int**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result);
let ret = data.readlong();
console.log("RpcClient: readLong is " + ret);
```
### writeFloat
writeFloat(val: number): boolean
Writes a **Float** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | number | Yes | **Float**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result);
```
### readFloat
readFloat(): number
Reads the **Float** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **Float**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result);
let ret = data.readFloat();
console.log("RpcClient: readFloat is " + ret);
```
### writeDouble
writeDouble(val: number): boolean
Writes a **Double** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | number | Yes | **Double**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result);
```
### readDouble
readDouble(): number
Reads the **Double** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **Double**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result);
let ret = data.readDouble();
console.log("RpcClient: readDouble is " + ret);
```
### writeBoolean
writeBoolean(val: boolean): boolean
Writes a **Boolean** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | boolean | Yes | **Boolean**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result);
```
### readBoolean
readBoolean(): boolean
Reads the **Boolean** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| boolean | **Boolean**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result);
let ret = data.readBoolean();
console.log("RpcClient: readBoolean is " + ret);
```
### writeChar
writeChar(val: number): boolean
Writes a **Char** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | number | Yes | **Char**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeChar('a');
console.log("RpcClient: writeChar is " + result);
```
### readChar
readChar(): number
Reads the **Char** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | **Char**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeChar('a');
console.log("RpcClient: writeChar is " + result);
let ret = data.readChar();
console.log("RpcClient: readChar is " + ret);
```
### writeString
writeString(val: string): boolean
Writes a **String** value to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | string | Yes | **String**&nbsp;value&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result);
```
### readString
readString(): string
Reads the **String** value from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| string | **String**&nbsp;value&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result);
let ret = data.readString();
console.log("RpcClient: readString is " + ret);
```
### writeSequenceable
writeSequenceable(val: Sequenceable): boolean
Writes a sequenceable object to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| val | [Sequenceable](#sequenceable) | Yes | Sequenceable&nbsp;object&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
```
### readSequenceable
readSequenceable(dataIn: Sequenceable) : boolean
Reads member variables from the **MessageParcel** instance.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | [Sequenceable](#sequenceable) | Yes | Object&nbsp;that&nbsp;reads&nbsp;member&nbsp;variables&nbsp;from&nbsp;the&nbsp;**MessageParcel**&nbsp;instance. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
let ret = new MySequenceable(0, "");
let result2 = data.readSequenceable(ret);
console.log("RpcClient: writeSequenceable is " + result2);
```
### writeByteArray
writeByteArray(byteArray: number[]): boolean
Writes a **ByteArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| byteArray | number[] | Yes | **ByteArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result);
```
### readByteArray
readByteArray(dataIn: number[]) : void
Reads the **ByteArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | Yes | **ByteArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result);
let array = new Array(5);
data.readByteArray(array);
```
### readByteArray
readByteArray(): number[]
Reads the **ByteArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number[] | **ByteArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result);
let array = data.readByteArray();
console.log("RpcClient: readByteArray is " + array);
```
### writeShortArray
writeShortArray(shortArray: number[]): boolean
Writes a **ShortArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| shortArray | number[] | Yes | **ShortArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
```
### readShortArray
readShortArray(dataIn: number[]) : void
Reads the **ShortArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | Yes | **ShortArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
let array = new Array(3);
data.readShortArray(array);
```
### readShortArray
readShortArray(): number[]
Reads the **ShortArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number[] | **ShortArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
let array = data.readShortArray();
console.log("RpcClient: readShortArray is " + array);
```
### writeIntArray
writeIntArray(intArray: number[]): boolean
Writes an **IntArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| intArray | number[] | Yes | **IntArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
```
### readIntArray
readIntArray(dataIn: number[]) : void
Reads the **IntArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | Yes | **IntArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
let array = new Array(3);
data.readIntArray(array);
```
### readIntArray
readIntArray(): number[]
Reads the **IntArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number[] | **IntArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
let array = data.readIntArray();
console.log("RpcClient: readIntArray is " + array);
```
### writeLongArray
writeLongArray(longArray: number[]): boolean
Writes a **LongArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| longArray | number[] | Yes | **LongArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
```
### readLongArray
readLongArray(dataIn: number[]) : void
Reads the **LongArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | Yes | **LongArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
let array = new Array(3);
data.readLongArray(array);
```
### readLongArray
readLongArray(): number[]
Reads the **LongArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number[] | **LongArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
let array = data.readLongArray();
console.log("RpcClient: readLongArray is " + array);
```
### writeFloatArray
writeFloatArray(floatArray: number[]): boolean
Writes a **FloatArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| floatArray | number[] | Yes | **FloatArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
```
### readFloatArray
readFloatArray(dataIn: number[]) : void
Reads the **FloatArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | Yes | **FloatArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
let array = new Array(3);
data.readFloatArray(array);
```
### readFloatArray
readFloatArray(): number[]
Reads the **FloatArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number[] | **FloatArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
let array = data.readFloatArray();
console.log("RpcClient: readFloatArray is " + array);
```
### writeDoubleArray
writeDoubleArray(doubleArray: number[]): boolean
Writes a **DoubleArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| doubleArray | number[] | Yes | **DoubleArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
```
### readDoubleArray
readDoubleArray(dataIn: number[]) : void
Reads the **DoubleArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | Yes | **DoubleArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
let array = new Array(3);
data.readDoubleArray(array);
```
### readDoubleArray
readDoubleArray(): number[]
Reads the **DoubleArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number[] | **DoubleArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
let array = data.readDoubleArray();
console.log("RpcClient: readDoubleArray is " + array);
```
### writeBooleanArray
writeBooleanArray(booleanArray: boolean[]): boolean
Writes a **BooleanArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| booleanArray | boolean[] | Yes | **BooleanArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
```
### readBooleanArray
readBooleanArray(dataIn: boolean[]) : void
Reads the **BooleanArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | boolean[] | Yes | **BooleanArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
let array = new Array(3);
data.readBooleanArray(array);
```
### readBooleanArray
readBooleanArray(): boolean[]
Reads the **BooleanArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| boolean[] | **BooleanArray**&nbsp;read. |
```
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
let array = data.readBooleanArray();
console.log("RpcClient: readBooleanArray is " + array);
```
### writeCharArray
writeCharArray(charArray: number[]): boolean
Writes a **CharArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| charArray | number[] | Yes | **CharArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeCharArray(['a', 'b', 'c']);
console.log("RpcClient: writeCharArray is " + result);
```
### readCharArray
readCharArray(dataIn: boolean[]) : void
Reads the **CharArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | boolean[] | Yes | **CharArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeCharArray(['a', 'b', 'c']);
console.log("RpcClient: writeCharArray is " + result);
let array = new Array(3);
data.readCharArray(array);
```
### readCharArray
readCharArray(): boolean[]
Reads the **CharArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| boolean[] | **CharArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeCharArray(['a', 'b', 'c']);
console.log("RpcClient: writeCharArray is " + result);
let array = data.readCharArray();
console.log("RpcClient: readCharArray is " + array);
```
### writeStringArray
writeStringArray(stringArray: string[]): boolean
Writes a **StringArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| stringArray | string[] | Yes | **StringArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
```
### readStringArray
readStringArray(dataIn: string[]) : void
Reads the **StringArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | string[] | Yes | **StringArray**&nbsp;to&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
let array = new Array(2);
data.readStringArray(array);
```
### readStringArray
readStringArray(): string[]
Reads the **StringArray** from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| string[] | **StringArray**&nbsp;read. |
- Example
```
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
let array = data.readStringArray();
console.log("RpcClient: readStringArray is " + array);
```
### writeNoException<sup>8+</sup>
writeNoException(): void
Writes information to this **MessageParcel** object indicating that no exception occurred.
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
onRemoteRequest(code, data, reply, option) {
if (code === 1) {
console.log("RpcServer: onRemoteRequest called");
reply.writeNoException();
return true;
} else {
console.log("RpcServer: unknown code: " + code);
return false;
}
}
}
```
### readException<sup>8+</sup>
readException(): void
Reads the exception information from this **MessageParcel** object.
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option)
.then(function(errCode) {
if (errCode === 0) {
console.log("sendRequest got result");
reply.readException();
let msg = reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
### writeSequenceableArray
writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean
Writes a **SequenceableArray** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| sequenceableArray | Sequenceable[] | Yes | **SequenceableArray**&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let sequenceable2 = new MySequenceable(2, "bbb");
let sequenceable3 = new MySequenceable(3, "ccc");
let a = [sequenceable, sequenceable2, sequenceable3];
let data = rpc.MessageParcel.create();
let result = data.writeSequenceableArray(a);
console.log("RpcClient: writeSequenceableArray is " + result);
```
### readSequenceableArray<sup>8+</sup>
readSequenceableArray(sequenceableArray: Sequenceable[]): void
Reads the specified **SequenceableArray** from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| sequenceableArray | Sequenceable[] | Yes | **SequenceableArray**&nbsp;to&nbsp;read. |
- Example
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let sequenceable2 = new MySequenceable(2, "bbb");
let sequenceable3 = new MySequenceable(3, "ccc");
let a = [sequenceable, sequenceable2, sequenceable3];
let data = rpc.MessageParcel.create();
let result = data.writeSequenceableArray(a);
console.log("RpcClient: writeSequenceableArray is " + result);
let b = [new MySequenceable(0, ""), new MySequenceable(0, ""), new MySequenceable(0, "")];
data.readSequenceableArray(b);
```
### writeRemoteObjectArray<sup>8+</sup>
writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean
Writes an array of **IRemoteObject** objects to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| objectArray | IRemoteObject[] | Yes | Array&nbsp;of&nbsp;**IRemoteObject**&nbsp;objects&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;**IRemoteObject**&nbsp;array&nbsp;is&nbsp;successfully&nbsp;written&nbsp;to&nbsp;the&nbsp;**MessageParcel**;&nbsp;returns&nbsp;**false**&nbsp;if&nbsp;the&nbsp;**IRemoteObject**&nbsp;array&nbsp;is&nbsp;null&nbsp;or&nbsp;fails&nbsp;to&nbsp;be&nbsp;written&nbsp;to&nbsp;the&nbsp;**MessageParcel**. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")];
let data = rpc.MessageParcel.create();
let result = data.writeRemoteObjectArray(a);
console.log("RpcClient: writeRemoteObjectArray is " + result);
```
### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(objects: IRemoteObject[]): void
Reads the specified **IRemoteObject** array from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| objects | IRemoteObject[] | Yes | **IRemoteObject**&nbsp;array&nbsp;to&nbsp;read. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")];
let data = rpc.MessageParcel.create();
let result = data.writeRemoteObjectArray(a);
let b = new Array(3);
data.readRemoteObjectArray(b);
```
### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(): IRemoteObject[]
Reads **IRemoteObject** objects from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| IRemoteObject[] | An&nbsp;array&nbsp;of&nbsp;**IRemoteObject**&nbsp;objects&nbsp;obtained. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")];
let data = rpc.MessageParcel.create();
let result = data.writeRemoteObjectArray(a);
console.log("RpcClient: readRemoteObjectArray is " + result);
let b = data.readRemoteObjectArray();
console.log("RpcClient: readRemoteObjectArray is " + b);
```
### closeFileDescriptor<sup>8+</sup>
static closeFileDescriptor(fd: number): void
Closes the specified file descriptor.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| fd | number | Yes | File&nbsp;descriptor&nbsp;to&nbsp;close. |
- Example
```
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
rpc.MessageParcel.closeFileDescriptor(fd);
```
### dupFileDescriptor<sup>8+</sup>
static dupFileDescriptor(fd: number) :number
Duplicates the specified file descriptor.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| fd | number | Yes | File&nbsp;descriptor&nbsp;to&nbsp;duplicate. |
- Return values
| Type | Description |
| -------- | -------- |
| number | New&nbsp;file&nbsp;descriptor. |
- Example
```
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let newFd = rpc.MessageParcel.dupFileDescriptor(fd);
```
### containFileDescriptors<sup>8+</sup>
containFileDescriptors(): boolean
Checks whether this **MessageParcel** object contains a file descriptor.
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;**MessageParcel**&nbsp;object&nbsp;contains&nbsp;a&nbsp;file&nbsp;descriptor;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let r1 = parcel.containFileDescriptors();
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
console.log("RpcTest: parcel writeFd result is : " + writeResult);
let containFD = parcel.containFileDescriptors();
console.log("RpcTest: parcel after write fd containFd result is : " + containFD);
```
### writeFileDescriptor<sup>8+</sup>
writeFileDescriptor(fd: number): boolean
Writes a file descriptor to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| fd | number | Yes | File&nbsp;descriptor&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
console.log("RpcTest: parcel writeFd result is : " + writeResult);
```
### readFileDescriptor<sup>8+</sup>
readFileDescriptor(): number
Reads a file descriptor from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | File&nbsp;descriptor&nbsp;obtained. |
- Example
```
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
let readFD = parcel.readFileDescriptor();
console.log("RpcTest: parcel read fd is : " + readFD);
```
### writeAshmem<sup>8+</sup>
writeAshmem(ashmem: Ashmem): boolean
Writes an anonymous shared object to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| ashmem | Ashmem | Yes | Anonymous&nbsp;shared&nbsp;object&nbsp;to&nbsp;write. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem);
console.log("RpcTest: write ashmem to result is : " + isWriteSuccess);
```
### readAshmem<sup>8+</sup>
readAshmem(): Ashmem
Reads the anonymous shared object from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| Ashmem | Anonymous&nbsp;share&nbsp;object&nbsp;obtained. |
- Example
```
let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem);
console.log("RpcTest: write ashmem to result is : " + isWriteSuccess);
let readAshmem = parcel.readAshmem();
console.log("RpcTest: read ashmem to result is : " + readAshmem);
```
### getRawDataCapacity<sup>8+</sup>
getRawDataCapacity(): number
Obtains the maximum amount of raw data that can be held by this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | 128&nbsp;MB,&nbsp;which&nbsp;is&nbsp;the&nbsp;maximum&nbsp;amount&nbsp;of&nbsp;raw&nbsp;data&nbsp;that&nbsp;can&nbsp;be&nbsp;held&nbsp;by&nbsp;this&nbsp;**MessageParcel**&nbsp;object. |
- Example
```
let parcel = new rpc.MessageParcel();
let result = parcel.getRawDataCapacity();
console.log("RpcTest: parcel get RawDataCapacity result is : " + result);
```
### writeRawData<sup>8+</sup>
writeRawData(rawData: number[], size: number): boolean
Writes raw data to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| rawData | number[] | Yes | Raw&nbsp;data&nbsp;to&nbsp;write. |
| size | number | Yes | Size&nbsp;of&nbsp;the&nbsp;raw&nbsp;data,&nbsp;in&nbsp;bytes. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let parcel = new rpc.MessageParcel();
let arr = new Int8Array([1, 2, 3, 4, 5]);
let isWriteSuccess = parcel.writeRawData(arr, arr.length);
console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess);
```
### readRawData<sup>8+</sup>
readRawData(size: number): number[]
Reads raw data from this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| size | number | Yes | Size&nbsp;of&nbsp;the&nbsp;raw&nbsp;data&nbsp;to&nbsp;read. |
- Return values
| Type | Description |
| -------- | -------- |
| number[] | Raw&nbsp;data&nbsp;obtained,&nbsp;in&nbsp;bytes. |
- Example
```
let parcel = new rpc.MessageParcel();
let arr = new Int8Array([1, 2, 3, 4, 5]);
let isWriteSuccess = parcel.writeRawData(arr, arr.length);
console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess);
let result = parcel.readRawData(5);
console.log("RpcTest: parcel read raw data result is : " + result);
```
### getDataVersion<sup>8+</sup>
getDataVersion(): number
Obtains the data format version from this **MessageParcel** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | Data&nbsp;format&nbsp;version&nbsp;obtained. |
- Example
```
let parcel = new rpc.MessageParcel();
let version = parcel.getDataVersion();
console.log("RpcTest: parcel get data version is : " + version);
```
### updateDataVersion<sup>8+</sup>
updateDataVersion(proxy: IRemoteObject): void
Updates the data format version of the **IRemoteObject** to this **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| proxy | IRemoteObject | Yes | Remote&nbsp;object&nbsp;that&nbsp;uses&nbsp;this&nbsp;**MessageParcel**&nbsp;object&nbsp;to&nbsp;send&nbsp;the&nbsp;request. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let parcel = new rpc.MessageParcel();
parcel.updateDataVersion(proxy);
```
## Sequenceable
Writes objects of classes to a **MessageParcel** and reads them from the **MessageParcel** during inter-process communication (IPC).
### marshalling
marshalling(dataOut: MessageParcel): boolean
Marshals this sequenceable object into a **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataOut | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;to&nbsp;which&nbsp;the&nbsp;sequenceable&nbsp;object&nbsp;is&nbsp;to&nbsp;be&nbsp;marshaled. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
let ret = new MySequenceable(0, "");
let result2 = data.readSequenceable(ret);
console.log("RpcClient: readSequenceable is " + result2);
```
### unmarshalling
unmarshalling(dataIn: MessageParcel) : boolean
Unmarshals this sequenceable object from a **MessageParcel** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataIn | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;in&nbsp;which&nbsp;the&nbsp;sequenceable&nbsp;object&nbsp;has&nbsp;been&nbsp;marshaled. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
let ret = new MySequenceable(0, "");
let result2 = data.readSequenceable(ret);
console.log("RpcClient: readSequenceable is " + result2);
```
## IRemoteBroker
Obtains a remote proxy object.
### asObject
asObject(): IRemoteObject
Obtains a proxy or remote object. This method must be implemented by its derived classes.
- Return values
| Type | Description |
| -------- | -------- |
| [IRemoteObject](#iremoteobject) | Returns&nbsp;the&nbsp;[RemoteObject](#ashmem8)&nbsp;if&nbsp;the&nbsp;caller&nbsp;is&nbsp;a&nbsp;[RemoteObject](#ashmem8);&nbsp;returns&nbsp;the&nbsp;[IRemoteObject](#iremoteobject),&nbsp;that&nbsp;is,&nbsp;the&nbsp;holder&nbsp;of&nbsp;this&nbsp;**RemoteProxy**&nbsp;object,&nbsp;if&nbsp;the&nbsp;caller&nbsp;is&nbsp;a&nbsp;[RemoteProxy](#remoteproxy)&nbsp;object. |
- Example
```
class TestAbility extends rpc.RemoteObject {
asObject() {
return this;
}
}
```
- Example
```
class TestProxy {
constructor(remote) {
this.remote = remote;
}
asObject() {
return this.remote;
}
}
```
## DeathRecipient
Subscribes to death notifications of a remote object. When the remote object is dead, the local end will receive a notification and [onRemoteDied](#onremotedied) will be called. A remote object is dead when the process holding the object is terminated or the device of the remote object is shut down or restarted. If the local and remote objects belong to different devices, the remote object is dead when the device holding the remote object is detached from the network.
### onRemoteDied
onRemoteDied(): void
Called to perform subsequent operations when a death notification of the remote object is received.
- Example
```
class MyDeathRecipient {
onRemoteDied() {
console.log("server is died");
}
}
```
## SendRequestResult<sup>8+</sup>
Defines the response to the request.
| Parameters | Value | Description |
| -------- | -------- | -------- |
| errCode | number | Error&nbsp;code. |
| code | number | Message&nbsp;code. |
| data | MessageParcel | **MessageParcel**&nbsp;object&nbsp;sent&nbsp;to&nbsp;the&nbsp;peer&nbsp;process. |
| reply | MessageParcel | **MessageParcel**&nbsp;object&nbsp;returned&nbsp;by&nbsp;the&nbsp;peer&nbsp;process. |
## IRemoteObject
Provides methods to query or obtain interface descriptors, add or delete death notifications, dump object status to specific files, and send messages.
### queryLocalInterface
queryLocalInterface(descriptor: string): IRemoteBroker
Obtains the interface.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| descriptor | string | Yes | Interface&nbsp;descriptor. |
- Return values
| Type | Description |
| -------- | -------- |
| IRemoteBroker | **IRemoteBroker**&nbsp;object&nbsp;bound&nbsp;to&nbsp;the&nbsp;specified&nbsp;interface&nbsp;descriptor. |
### sendRequest
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;number&gt;<sup>7</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;<sup>8+</sup>
Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a promise will be fulfilled immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| code | number | Yes | Message&nbsp;code&nbsp;called&nbsp;by&nbsp;the&nbsp;request,&nbsp;which&nbsp;is&nbsp;determined&nbsp;by&nbsp;the&nbsp;client&nbsp;and&nbsp;server.&nbsp;If&nbsp;the&nbsp;method&nbsp;is&nbsp;generated&nbsp;by&nbsp;an&nbsp;IDL&nbsp;tool,&nbsp;the&nbsp;message&nbsp;code&nbsp;is&nbsp;automatically&nbsp;generated&nbsp;by&nbsp;the&nbsp;IDL&nbsp;tool. |
| data | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;holding&nbsp;the&nbsp;data&nbsp;to&nbsp;send. |
| reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;that&nbsp;receives&nbsp;the&nbsp;response. |
| options | [MessageOption](#messageoption) | Yes | Request&nbsp;sending&nbsp;mode,&nbsp;which&nbsp;can&nbsp;be&nbsp;synchronous&nbsp;(default)&nbsp;or&nbsp;asynchronous. |
- Return values
| Type | Description |
| -------- | -------- |
| Promise&lt;number&gt;<sup>7</sup><br/>Promise&lt;SendRequestResult&gt;<sup>8+</sup> | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result.&nbsp;The&nbsp;value&nbsp;**0**&nbsp;will&nbsp;be&nbsp;returned&nbsp;if&nbsp;the&nbsp;request&nbsp;is&nbsp;sent&nbsp;successfully.&nbsp;Otherwise,&nbsp;an&nbsp;error&nbsp;code&nbsp;will&nbsp;be&nbsp;returned.&nbsp;<sup>7</sup><br/>Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;**sendRequestResult**&nbsp;instance.&nbsp;<sup>8+</sup> |
### sendRequest<sup>8+</sup>
sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback&lt;SendRequestResult&gt;): void
Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a callback will be invoked immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a callback will be invoked when the response to **sendRequest** is returned, and the **reply** message contains the returned information.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| code | number | Yes | Message&nbsp;code&nbsp;called&nbsp;by&nbsp;the&nbsp;request,&nbsp;which&nbsp;is&nbsp;determined&nbsp;by&nbsp;the&nbsp;client&nbsp;and&nbsp;server.&nbsp;If&nbsp;the&nbsp;method&nbsp;is&nbsp;generated&nbsp;by&nbsp;an&nbsp;IDL&nbsp;tool,&nbsp;the&nbsp;message&nbsp;code&nbsp;is&nbsp;automatically&nbsp;generated&nbsp;by&nbsp;the&nbsp;IDL&nbsp;tool. |
| data | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;holding&nbsp;the&nbsp;data&nbsp;to&nbsp;send. |
| reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;that&nbsp;receives&nbsp;the&nbsp;response. |
| options | [MessageOption](#messageoption) | Yes | Request&nbsp;sending&nbsp;mode,&nbsp;which&nbsp;can&nbsp;be&nbsp;synchronous&nbsp;(default)&nbsp;or&nbsp;asynchronous. |
| callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback&nbsp;for&nbsp;receiving&nbsp;the&nbsp;sending&nbsp;result. |
### addDeathrecipient
addDeathRecipient(recipient: DeathRecipient, flags: number): boolean
Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback&nbsp;to&nbsp;add. |
| flags | number | Yes | Flag&nbsp;of&nbsp;the&nbsp;death&nbsp;notification. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;callback&nbsp;is&nbsp;added&nbsp;successfully;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
### removeDeathRecipient
removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean
Removes the callback used to receive death notifications of the remote object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback&nbsp;to&nbsp;remove. |
| flags | number | Yes | Flag&nbsp;of&nbsp;the&nbsp;death&nbsp;notification. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;callback&nbsp;is&nbsp;removed&nbsp;successfully;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
### getInterfaceDescriptor
getInterfaceDescriptor(): string
Obtains the interface descriptor of the object. The interface descriptor is a string.
- Return values
| Type | Description |
| -------- | -------- |
| string | Interface&nbsp;descriptor&nbsp;obtained. |
### isObjectDead
isObjectDead(): boolean
Checks whether the current object is dead.
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;object&nbsp;is&nbsp;dead;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
## RemoteProxy
Provides methods to implement **IRemoteObject**.
### sendRequest
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;number&gt;<sup>7</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;<sup>8+</sup>
Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a promise will be fulfilled immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| code | number | Yes | Message&nbsp;code&nbsp;called&nbsp;by&nbsp;the&nbsp;request,&nbsp;which&nbsp;is&nbsp;determined&nbsp;by&nbsp;the&nbsp;client&nbsp;and&nbsp;server.&nbsp;If&nbsp;the&nbsp;method&nbsp;is&nbsp;generated&nbsp;by&nbsp;an&nbsp;IDL&nbsp;tool,&nbsp;the&nbsp;message&nbsp;code&nbsp;is&nbsp;automatically&nbsp;generated&nbsp;by&nbsp;the&nbsp;IDL&nbsp;tool. |
| data | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;holding&nbsp;the&nbsp;data&nbsp;to&nbsp;send. |
| reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;that&nbsp;receives&nbsp;the&nbsp;response. |
| options | [MessageOption](#messageoption) | Yes | Request&nbsp;sending&nbsp;mode,&nbsp;which&nbsp;can&nbsp;be&nbsp;synchronous&nbsp;(default)&nbsp;or&nbsp;asynchronous. |
- Return values
| Type | Description |
| -------- | -------- |
| Promise&lt;number&gt;<sup>7</sup><br/>Promise&lt;SendRequestResult&gt;<sup>8+</sup> | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result.&nbsp;The&nbsp;value&nbsp;**0**&nbsp;will&nbsp;be&nbsp;returned&nbsp;if&nbsp;the&nbsp;request&nbsp;is&nbsp;sent&nbsp;successfully.&nbsp;Otherwise,&nbsp;an&nbsp;error&nbsp;code&nbsp;will&nbsp;be&nbsp;returned.&nbsp;<sup>7</sup><br/>Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;**sendRequestResult**&nbsp;instance.&nbsp;<sup>8+</sup> |
- Example<sup>7</sup>
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option)
.then(function(errCode) {
if (errCode === 0) {
console.log("sendRequest got result");
let msg = reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
- Example<sup>8+</sup>
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option)
.then(function(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
### sendRequest<sup>8+</sup>
sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback&lt;SendRequestResult&gt;): void
Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a callback will be invoked immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a callback will be invoked when the response to **sendRequest** is returned, and the **reply** message contains the returned information.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| code | number | Yes | Message&nbsp;code&nbsp;called&nbsp;by&nbsp;the&nbsp;request,&nbsp;which&nbsp;is&nbsp;determined&nbsp;by&nbsp;the&nbsp;client&nbsp;and&nbsp;server.&nbsp;If&nbsp;the&nbsp;method&nbsp;is&nbsp;generated&nbsp;by&nbsp;an&nbsp;IDL&nbsp;tool,&nbsp;the&nbsp;message&nbsp;code&nbsp;is&nbsp;automatically&nbsp;generated&nbsp;by&nbsp;the&nbsp;IDL&nbsp;tool. |
| data | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;holding&nbsp;the&nbsp;data&nbsp;to&nbsp;send. |
| reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;that&nbsp;receives&nbsp;the&nbsp;response. |
| options | [MessageOption](#messageoption) | Yes | Request&nbsp;sending&nbsp;mode,&nbsp;which&nbsp;can&nbsp;be&nbsp;synchronous&nbsp;(default)&nbsp;or&nbsp;asynchronous. |
| callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback&nbsp;for&nbsp;receiving&nbsp;the&nbsp;sending&nbsp;result. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
function sendRequestCallback(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
console.log("RPCTest: sendRequest ends, reclaim parcel");
result.data.reclaim();
result.reply.reclaim();
}
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option, sendRequestCallback);
```
### queryLocalInterface
queryLocalInterface(interface: string): IRemoteBroker
Obtains the **LocalInterface** object of an interface descriptor.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| interface | string | Yes | Interface&nbsp;descriptor. |
- Return values
| Type | Description |
| -------- | -------- |
| IRemoteBroker | Returns&nbsp;**Null**&nbsp;by&nbsp;default,&nbsp;which&nbsp;indicates&nbsp;a&nbsp;proxy&nbsp;interface. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function (elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName":"com.huawei.server",
"abilityName":"com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let broker = proxy.queryLocalInterface("testObject");
console.log("RpcClient: queryLocalInterface is " + broker);
```
### addDeathRecippient
addDeathRecipient(recipient : DeathRecipient, flags : number): boolean
Adds a callback for receiving the death notifications of the remote object, including the death notifications of the remote proxy.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback&nbsp;to&nbsp;add. |
| flags | number | Yes | Flag&nbsp;of&nbsp;the&nbsp;death&nbsp;notification.&nbsp;This&nbsp;parameter&nbsp;is&nbsp;reserved.&nbsp;It&nbsp;is&nbsp;set&nbsp;to&nbsp;**0**. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;callback&nbsp;is&nbsp;added&nbsp;successfully;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
class MyDeathRecipient {
onRemoteDied() {
console.log("server is died");
}
}
let deathRecipient = new MyDeathRecipient();
proxy.addDeathRecippient(deathRecipient, 0);
```
### removeDeathRecipient
removeDeathRecipient(recipient : DeathRecipient, flags : number): boolean
Removes the callback used to receive death notifications of the remote object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback&nbsp;to&nbsp;remove. |
| flags | number | Yes | Flag&nbsp;of&nbsp;the&nbsp;death&nbsp;notification.&nbsp;This&nbsp;parameter&nbsp;is&nbsp;reserved.&nbsp;It&nbsp;is&nbsp;set&nbsp;to&nbsp;**0**. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;callback&nbsp;is&nbsp;removed&nbsp;successfully;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
class MyDeathRecipient {
onRemoteDied() {
console.log("server is died");
}
}
let deathRecipient = new MyDeathRecipient();
proxy.addDeathRecippient(deathRecipient, 0);
proxy.removeDeathRecipient(deathRecipient, 0);
```
### getInterfaceDescriptor
getInterfaceDescriptor(): string
Obtains the interface descriptor of this proxy object.
- Return values
| Type | Description |
| -------- | -------- |
| string | Interface&nbsp;descriptor&nbsp;obtained. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let descriptor = proxy.getInterfaceDescriptor();
console.log("RpcClient: descriptor is " + descriptor);
```
### isObjectDead
isObjectDead(): boolean
Checks whether the **RemoteObject** is dead.
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;**RemoteObject**&nbsp;is&nbsp;dead;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let isDead = proxy.isObjectDead();
console.log("RpcClient: isObjectDead is " + isDead);
```
### setDataVersion<sup>8+</sup>
setDataVersion(dataVersion: number): boolean
Sets the data format version to this **RemoteProxy** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| dataVersion | number | Yes | Data&nbsp;format&nbsp;version&nbsp;to&nbsp;set. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let result = proxy.setDataVersion(1);
console.log("RpcClient: set Data Version is " + result);
```
## MessageOption
Provides common message options (flag and wait time). The flag is used to construct the specified **MessageOption** object.
| Parameters | Value | Description |
| -------- | -------- | -------- |
| TF_SYNC | 0 | Synchronous&nbsp;call. |
| TF_ASYNC | 1 | Asynchronous&nbsp;call. |
| TF_ACCEPT_FDS | 0x10 | Indication&nbsp;to&nbsp;the&nbsp;[sendRequest](#sendrequest8)&nbsp;API&nbsp;for&nbsp;returning&nbsp;the&nbsp;file&nbsp;descriptor. |
| TF_WAIT_TIME | 8 | Wait&nbsp;time,&nbsp;in&nbsp;seconds. |
### constructor
constructor(syncFlags?: number, waitTime = TF_WAIT_TIME)
A constructor used to create a **MessageOption** instance.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| syncFlags | number | No | Specifies&nbsp;whether&nbsp;the&nbsp;**SendRequest**&nbsp;is&nbsp;called&nbsp;synchronously&nbsp;(default)&nbsp;or&nbsp;asynchronously. |
| waitTime | number | No | Maximum&nbsp;wait&nbsp;time&nbsp;for&nbsp;an&nbsp;RPC&nbsp;call.&nbsp;The&nbsp;default&nbsp;value&nbsp;is&nbsp;**TF_WAIT_TIME**. |
### getFlags
getFlags(): number
Obtains the **SendRequest** call flag, which can be synchronous or asynchronous.
- Return values
| Type | Description |
| -------- | -------- |
| number | Whether&nbsp;the&nbsp;**SendRequest**&nbsp;is&nbsp;called&nbsp;synchronously&nbsp;or&nbsp;asynchronously. |
### setFlags
setFlags(flags: number): void
Sets the **SendRequest** call flag, which can be synchronous or asynchronous.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| flags | number | Yes | Call&nbsp;flag,&nbsp;which&nbsp;can&nbsp;be&nbsp;synchronous&nbsp;or&nbsp;asynchronous. |
### getWaitTime
getWaitTime(): number
Obtains the maximum wait time for this RPC call.
- Return values
| Type | Description |
| -------- | -------- |
| number | Maximum&nbsp;wait&nbsp;time&nbsp;obtained. |
### setWaitTime
setWaitTime(waitTime: number): void
Sets the maximum wait time for this RPC call.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| waitTime | number | Yes | Maximum&nbsp;wait&nbsp;time&nbsp;to&nbsp;set. |
## IPCSkeleton
Obtains IPC context information, including the UID and PID, local and peer device IDs, and whether the method is invoked on the same device.
### getContextObject
static getContextObject(): IRemoteObject
Obtains the system capability manager.
- Return values
| Type | Description |
| -------- | -------- |
| [IRemoteObject](#iremoteobject) | System&nbsp;capability&nbsp;manager. |
- Example
```
let samgr = rpc.IPCSkeleton.getContextObject();
console.log("RpcServer: getContextObject result: " + samgr);
```
### getCallingPid
static getCallingPid(): number
Obtains the PID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the PID of the process will be returned.
- Return values
| Type | Description |
| -------- | -------- |
| number | PID&nbsp;of&nbsp;the&nbsp;caller. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callerPid = rpc.IPCSkeleton.getCallingPid();
console.log("RpcServer: getCallingPid result: " + callerPid);
return true;
}
}
```
### getCallingUid
static getCallingUid(): number
Obtains the UID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the UID of the process will be returned.
- Return values
| Type | Description |
| -------- | -------- |
| number | UID&nbsp;of&nbsp;the&nbsp;caller. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callerUid = rpc.IPCSkeleton.getCallingUid();
console.log("RpcServer: getCallingUid result: " + callerUid);
return true;
}
}
```
### getCalligDeviceID
static getCallingDeviceID(): string
Obtains the ID of the device hosting the caller's process.
- Return values
| Type | Description |
| -------- | -------- |
| string | Device&nbsp;ID&nbsp;obtained. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callerDeviceID = rpc.IPCSkeleton.getCalligDeviceID();
console.log("RpcServer: callerDeviceID is: " + callerDeviceID);
return true;
}
}
```
### getLocalDeviceID
static getLocalDeviceID(): string
Obtains the local device ID.
- Return values
| Type | Description |
| -------- | -------- |
| string | Local&nbsp;device&nbsp;ID&nbsp;obtained. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID();
console.log("RpcServer: localDeviceID is: " + localDeviceID);
return true;
}
}
```
### isLocalCalling
static isLocalCalling(): boolean
Checks whether the peer process is a process of the local device.
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;local&nbsp;and&nbsp;peer&nbsp;processes&nbsp;are&nbsp;on&nbsp;the&nbsp;same&nbsp;device;&nbsp;returns&nbsp;false&nbsp;otherwise. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let isLocalCalling = rpc.IPCSkeleton.isLocalCalling();
console.log("RpcServer: isLocalCalling is: " + isLocalCalling);
return true;
}
}
```
### flushCommands
static flushCommands(object : IRemoteObject): number
Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy**. |
- Return values
| Type | Description |
| -------- | -------- |
| number | Returns&nbsp;**0**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;an&nbsp;error&nbsp;code&nbsp;if&nbsp;the&nbsp;input&nbsp;object&nbsp;is&nbsp;null&nbsp;or&nbsp;a&nbsp;**RemoteObject**,&nbsp;or&nbsp;the&nbsp;operation&nbsp;fails. |
- Example
```
let remoteObject = new rpc.RemoteObject("aaa", 3);
let ret = rpc.IPCSkeleton.flushCommands(remoteObject);
console.log("RpcServer: flushCommands result: " + ret);
```
### resetCallingIdentity
static resetCallingIdentity(): string
Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication.
- Return values
| Type | Description |
| -------- | -------- |
| string | String&nbsp;containing&nbsp;the&nbsp;UID&nbsp;and&nbsp;PID&nbsp;of&nbsp;the&nbsp;remote&nbsp;user. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity();
console.log("RpcServer: callingIdentity is: " + callingIdentity);
return true;
}
}
```
### setCallingIdentity
static setCallingIdentity(identity : string): boolean
Restores the UID and PID of the remote user. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| identity | string | Yes | String&nbsp;containing&nbsp;the&nbsp;remote&nbsp;user&nbsp;UID&nbsp;and&nbsp;PID,&nbsp;which&nbsp;are&nbsp;returned&nbsp;by&nbsp;**resetCallingIdentity**. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callingIdentity = null;
try {
callingIdentity = rpc.IPCSkeleton.resetCallingIdentity();
console.log("RpcServer: callingIdentity is: " + callingIdentity);
} finally {
let ret = rpc.IPCSkeleton.setCallingIdentity("callingIdentity ");
console.log("RpcServer: setCallingIdentity is: " + ret);
}
return true;
}
}
```
## RemoteObject
Provides methods to implement **RemoteObject**. The service provider must inherit from this class.
### constructor
constructor(descriptor: string)
A constructor used to create a **RemoteObject** instance.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| descriptor | string | Yes | Interface&nbsp;descriptor. |
### sendRequest
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;number&gt;<sup>7</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;<sup>8+</sup>
Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a promise will be fulfilled immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| code | number | Yes | Message&nbsp;code&nbsp;called&nbsp;by&nbsp;the&nbsp;request,&nbsp;which&nbsp;is&nbsp;determined&nbsp;by&nbsp;the&nbsp;client&nbsp;and&nbsp;server.&nbsp;If&nbsp;the&nbsp;method&nbsp;is&nbsp;generated&nbsp;by&nbsp;an&nbsp;IDL&nbsp;tool,&nbsp;the&nbsp;message&nbsp;code&nbsp;is&nbsp;automatically&nbsp;generated&nbsp;by&nbsp;the&nbsp;IDL&nbsp;tool. |
| data | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;holding&nbsp;the&nbsp;data&nbsp;to&nbsp;send. |
| reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;that&nbsp;receives&nbsp;the&nbsp;response. |
| options | [MessageOption](#messageoption) | Yes | Request&nbsp;sending&nbsp;mode,&nbsp;which&nbsp;can&nbsp;be&nbsp;synchronous&nbsp;(default)&nbsp;or&nbsp;asynchronous. |
- Return values
| Type | Description |
| -------- | -------- |
| Promise&lt;number&gt;<sup>7</sup><br/>Promise&lt;SendRequestResult&gt;<sup>8+</sup> | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result.&nbsp;The&nbsp;value&nbsp;**0**&nbsp;will&nbsp;be&nbsp;returned&nbsp;if&nbsp;the&nbsp;request&nbsp;is&nbsp;sent&nbsp;successfully.&nbsp;Otherwise,&nbsp;an&nbsp;error&nbsp;code&nbsp;will&nbsp;be&nbsp;returned.&nbsp;<sup>7</sup><br/>Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;**sendRequestResult**&nbsp;instance.&nbsp;<sup>8+</sup> |
- Example<sup>7</sup>
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
testRemoteObject.sendRequest(1, data, reply, option)
.then(function(errCode) {
if (errCode === 0) {
console.log("sendRequest got result");
let msg = reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
- Example<sup>8+</sup>
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
testRemoteObject.sendRequest(1, data, reply, option)
.then(function(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
### sendRequest<sup>8+</sup>
sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback&lt;SendRequestResult&gt;): void
Sends a **MessageParcel** message to the peer process in synchronous or asynchronous mode. If **options** indicates the asynchronous mode, a callback will be invoked immediately and the **reply** message does not contain any content. If **options** indicates the synchronous mode, a callback will be invoked when the response to **sendRequest** is returned, and the **reply** message contains the returned information.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| code | number | Yes | Message&nbsp;code&nbsp;called&nbsp;by&nbsp;the&nbsp;request,&nbsp;which&nbsp;is&nbsp;determined&nbsp;by&nbsp;the&nbsp;client&nbsp;and&nbsp;server.&nbsp;If&nbsp;the&nbsp;method&nbsp;is&nbsp;generated&nbsp;by&nbsp;an&nbsp;IDL&nbsp;tool,&nbsp;the&nbsp;message&nbsp;code&nbsp;is&nbsp;automatically&nbsp;generated&nbsp;by&nbsp;the&nbsp;IDL&nbsp;tool. |
| data | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;holding&nbsp;the&nbsp;data&nbsp;to&nbsp;send. |
| reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;that&nbsp;receives&nbsp;the&nbsp;response. |
| options | [MessageOption](#messageoption) | Yes | Request&nbsp;sending&nbsp;mode,&nbsp;which&nbsp;can&nbsp;be&nbsp;synchronous&nbsp;(default)&nbsp;or&nbsp;asynchronous. |
| AsyncCallback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback&nbsp;for&nbsp;receiving&nbsp;the&nbsp;sending&nbsp;result. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
function sendRequestCallback(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
console.log("RPCTest: sendRequest ends, reclaim parcel");
result.data.reclaim();
result.reply.reclaim();
}
let testRemoteObject = new TestRemoteObject("testObject");
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
testRemoteObject.sendRequest(1, data, reply, option, sendRequestCallback);
```
### onRemoteRequest
onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean
Provides a response to **sendRequest()**. The server processes the request and returns a response in this function.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| code | number | Yes | Service&nbsp;request&nbsp;code&nbsp;sent&nbsp;by&nbsp;the&nbsp;peer&nbsp;end. |
| data | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;that&nbsp;holds&nbsp;the&nbsp;parameters&nbsp;called&nbsp;by&nbsp;the&nbsp;client. |
| reply | [MessageParcel](#messageparcel) | Yes | **MessageParcel**&nbsp;object&nbsp;carrying&nbsp;the&nbsp;result. |
| option | [MessageOption](#messageoption) | Yes | Whether&nbsp;the&nbsp;operation&nbsp;is&nbsp;synchronous&nbsp;or&nbsp;asynchronous. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
onRemoteRequest(code, data, reply, option) {
if (code === 1) {
console.log("RpcServer: onRemoteRequest called");
return true;
} else {
console.log("RpcServer: unknown code: " + code);
return false;
}
}
}
```
### getCallingUid
getCallingUid(): number
Obtains the UID of the peer process.
- Return values
| Type | Description |
| -------- | -------- |
| number | UID&nbsp;of&nbsp;the&nbsp;peer&nbsp;process&nbsp;obtained. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
console.log("RpcServer: getCallingUid: " + testRemoteObject.getCallingUid());
```
### getCallingPid
getCallingPid(): number
Obtains the PID of the peer process.
- Return values
| Type | Description |
| -------- | -------- |
| number | PID&nbsp;of&nbsp;the&nbsp;peer&nbsp;process&nbsp;obtained. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
console.log("RpcServer: getCallingPid: " + testRemoteObject.getCallingPid());
```
### queryLocalInterface
queryLocalInterface(descriptor: descriptor): IRemoteBroker
Checks whether the remote object corresponding to the specified interface descriptor exists.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| descriptor | descriptor | Yes | Interface&nbsp;descriptor. |
- Return values
| Type | Description |
| -------- | -------- |
| IRemoteBroker | Returns&nbsp;the&nbsp;remote&nbsp;object&nbsp;if&nbsp;a&nbsp;match&nbsp;is&nbsp;found;&nbsp;returns&nbsp;**Null**&nbsp;otherwise. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let broker = testRemoteObject.queryLocalInterface("testObject");
```
### getInterfaceDescriptor
getInterfaceDescriptor(): string
Obtains the interface descriptor.
- Return values
| Type | Description |
| -------- | -------- |
| string | Interface&nbsp;descriptor&nbsp;obtained. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let descriptor = testRemoteObject.getInterfaceDescriptor();
console.log("RpcServer: descriptor is: " + descriptor);
```
### attachLocalInterface
attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
Binds an interface descriptor to an **IRemoteBroker** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| localInterface | IRemoteBroker | Yes | **IRemoteBroker**&nbsp;object. |
| descriptor | string | Yes | Interface&nbsp;descriptor. |
- Example
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
```
## Ashmem<sup>8+</sup>
Provides methods related to anonymous shared memory objects, including creating, closing, mapping, and unmapping an **Ashmem** object, reading data from and writing data to an **Ashmem** object, obtaining the **Ashmem** size, and setting **Ashmem** protection.
The following table describes the protection types of the mapped memory.
| Name | Value | Description |
| -------- | -------- | -------- |
| PROT_EXEC | 4 | The&nbsp;mapped&nbsp;memory&nbsp;is&nbsp;executable. |
| PROT_NONE | 0 | The&nbsp;mapped&nbsp;memory&nbsp;is&nbsp;inaccessible. |
| PROT_READ | 1 | The&nbsp;mapped&nbsp;memory&nbsp;is&nbsp;readable. |
| PROT_WRITE | 2 | The&nbsp;mapped&nbsp;memory&nbsp;is&nbsp;writeable. |
### createAshmem
static createAshmem(name: string, size: number): Ashmem
Creates an **Ashmem** object with the specified name and size.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| name | string | Yes | Name&nbsp;of&nbsp;the&nbsp;**Ashmem**&nbsp;object&nbsp;to&nbsp;create. |
| size | number | Yes | Size&nbsp;(in&nbsp;bytes)&nbsp;of&nbsp;the&nbsp;**Ashmem**&nbsp;object&nbsp;to&nbsp;create. |
- Return values
| Type | Description |
| -------- | -------- |
| Ashmem | Returns&nbsp;the&nbsp;**Ashmem**&nbsp;object&nbsp;if&nbsp;it&nbsp;is&nbsp;created&nbsp;successfully;&nbsp;returns&nbsp;**null**&nbsp;otherwise. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmem : " + ashmem + " size is : " + size);
```
### createAshmemFromExisting
static createAshmemFromExisting(ashmem: Ashmem): Ashmem
Creates an **Ashmem** object by copying the file descriptor (FD) of an existing **Ashmem** object. The two **Ashmem** objects point to the same shared memory region.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| ashmem | Ashmem | Yes | Existing&nbsp;**Ashmem**&nbsp;object. |
- Return values
| Type | Description |
| -------- | -------- |
| Ashmem | **Ashmem**&nbsp;object&nbsp;created. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let ashmem2 = rpc.Ashmem.createAshmemFromExisting(ashmem);
let size = ashmem2.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmemFromExisting : " + ashmem2 + " size is : " + size);
```
### closeAshmem
closeAshmem(): void
Closes this **Ashmem** object.
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
ashmem.closeAshmem();
```
### unmapAshmem
unmapAshmem(): void
Deletes the mappings for the specified address range of this **Ashmem** object.
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
ashmem.unmapAshmem();
```
### getAshmemSize
getAshmemSize(): number
Obtains the memory size of this **Ashmem** object.
- Return values
| Type | Description |
| -------- | -------- |
| number | Memory&nbsp;size&nbsp;obtained. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashmem is " + ashmem + " size is : " + size);
```
### mapAshmem
mapAshmem(mapType: number): boolean
Creates the shared file mapping on the virtual address space of this process. The size of the mapping region is specified by this **Ashmem** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| mapType | number | Yes | Protection&nbsp;level&nbsp;of&nbsp;the&nbsp;memory&nbsp;region&nbsp;to&nbsp;which&nbsp;the&nbsp;shared&nbsp;file&nbsp;is&nbsp;mapped. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapReadAndWrite = ashmem.mapAshmem(rpc.Ashmem.PROT_READ | rpc.Ashmem.PROT_WRITE);
console.log("RpcTest: map ashmem result is : " + mapReadAndWrite);
```
### mapReadAndWriteAshmem
mapReadAndWriteAshmem(): boolean
Maps the shared file to the readable and writable virtual address space of the process.
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem();
console.log("RpcTest: map ashmem result is : " + mapResult);
```
### mapReadOnlyAshmem
mapReadOnlyAshmem(): boolean
Maps the shared file to the read-only virtual address space of the process.
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadOnlyAshmem();
console.log("RpcTest: Ashmem mapReadOnlyAshmem result is : " + mapResult);
```
### setProtection
setProtection(protectionType: number): boolean
Sets the protection level of the memory region to which the shared file is mapped.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| protectionType | number | Yes | Protection&nbsp;type&nbsp;to&nbsp;set. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;if&nbsp;the&nbsp;operation&nbsp;is&nbsp;successful;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let result = ashmem.setProtection(rpc.Ashmem.PROT_READ);
console.log("RpcTest: Ashmem setProtection result is : " + result);
```
### writeToAshmem
writeToAshmem(buf: number[], size: number, offset: number): boolean
Writes data to the shared file associated with this **Ashmem** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| buf | number[] | Yes | Data&nbsp;to&nbsp;write. |
| size | number | Yes | Size&nbsp;of&nbsp;the&nbsp;data&nbsp;to&nbsp;write. |
| offset | number | Yes | Start&nbsp;position&nbsp;of&nbsp;the&nbsp;data&nbsp;to&nbsp;write&nbsp;in&nbsp;the&nbsp;memory&nbsp;region&nbsp;associated&nbsp;with&nbsp;this&nbsp;**Ashmem**&nbsp;object. |
- Return values
| Type | Description |
| -------- | -------- |
| boolean | Returns&nbsp;**true**&nbsp;is&nbsp;the&nbsp;data&nbsp;is&nbsp;written&nbsp;successfully;&nbsp;returns&nbsp;**false**&nbsp;otherwise. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0);
console.log("RpcTest: write to Ashmem result is : " + writeResult);
```
### readFromAshmem
readFromAshmem(size: number, offset: number): number[]
Reads data from the shared file associated with this **Ashmem** object.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| size | number | Yes | Size&nbsp;of&nbsp;the&nbsp;data&nbsp;to&nbsp;read. |
| offset | number | Yes | Start&nbsp;position&nbsp;of&nbsp;the&nbsp;data&nbsp;to&nbsp;read&nbsp;in&nbsp;the&nbsp;memory&nbsp;region&nbsp;associated&nbsp;with&nbsp;this&nbsp;**Ashmem**&nbsp;object. |
- Return values
| Type | Description |
| -------- | -------- |
| number[] | Data&nbsp;read. |
- Example
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0);
console.log("RpcTest: write to Ashmem result is : " + writeResult);
let readResult = ashmem.readFromAshmem(5, 0);
console.log("RpcTest: read to Ashmem result is : " + readResult);
```
......@@ -7,7 +7,7 @@
- [Universal Events](js-components-common-events.md)
- [Universal Methods](js-components-common-methods.md)
- [Animation Styles](js-components-common-animation.md)
- [Gradient Styles](reference/arkui-js/js-components-common-gradient.md)
- [Gradient Styles](js-components-common-gradient.md)
- [Transition Styles](js-components-common-transition.md)
- [Media Query](js-components-common-mediaquery.md)
- [Custom Font Styles](js-components-common-customizing-font.md)
......
......@@ -81,14 +81,14 @@ You can use **$r** or **$rawfile** to create a **Resource** object. For details,
| Name| Type| Description|
| -------- | -------- | -------- |
| ResourceStr | string&nbsp;\|&nbsp;[Resource](#ResourceType) | Resource string.|
| ResourceStr | string&nbsp;\|&nbsp;[Resource](#resourcetype) | Resource string.|
## Resource Color<sup>8+</sup>
| Name| Type| Description|
| -------- | -------- | -------- |
| ResourceColor | Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](#ResourceType) | Resource color.|
| ResourceColor | Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](#resourcetype) | Resource color.|
## Custom Builder<sup>8+</sup>
......
# USB Service
- [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md)
......@@ -13,15 +13,17 @@
- [Ability开发](ability/Readme-CN.md)
- [UI开发](ui/Readme-CN.md)
- 基础功能开发
- [后台代理提醒](background-agent-scheduled-reminder/Readme-CN.md)
- [后台任务管理](background-task-management/Readme-CN.md)
- [窗口管理](windowmanager/Readme-CN.md)
- [WebGL](webgl/Readme-CN.md)
- [媒体](media/Readme-CN.md)
- [安全](security/Readme-CN.md)
- [网络与连接](connectivity/Readme-CN.md)
- [数据管理](database/Readme-CN.md)
- [USB服务](usb/Readme-CN.md)
- [后台代理提醒](background-agent-scheduled-reminder/Readme-CN.md)
- [后台任务管理](background-task-management/Readme-CN.md)
- [设备管理](device/Readme-CN.md)
- [设备使用信息统计](device-usage-statistics/Readme-CN.md)
- [DFX](dfx/Readme-CN.md)
- [窗口管理](windowmanager/Readme-CN.md)
- 工具
- [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md)
- 示例教程
......
......@@ -36,12 +36,12 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager';
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspension delay will time out.");
});
var id = delayInfo.requestId;console.info("requestId is: " + id);
```
......@@ -106,10 +106,10 @@ ohos.permission.KEEP_BACKGROUND_RUNNING
| function stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void;<br/>function stopBackgroundRunning(context: Context): Promise&lt;void&gt;; | 停止后台长时任务的运行 |
其中,wantAgent的信息详见([WantAgent](../reference/apis/js-apis-notification.md#WantAgent接口)
其中,wantAgent的信息详见([WantAgent](../reference/apis/js-apis-notification.md#WantAgent接口)
**表4** 后台模式类型
| 参数名 | id值 | 描述 |
| -------- | -------- | -------- |
| DATA_TRANSFER | 1 | 数据传输 |
......@@ -174,13 +174,13 @@ ohos.permission.KEEP_BACKGROUND_RUNNING
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation succeeded");
}).catch((err) => {
console.error("Operation failed Cause: " + err);
});
```
## 开发实例
......
# 设备使用信息统计
- 后台任务
- [设备使用信息统计概述](device-usage-statistics-overview.md)
- [设备使用信息统计开发指导](device-usage-statistics-dev-guide.md)
\ No newline at end of file
- [设备使用信息统计概述](device-usage-statistics-overview.md)
- [设备使用信息统计开发指导](device-usage-statistics-dev-guide.md)
\ No newline at end of file
# 设备管理
- USB服务
- [USB服务开发概述](usb-overview.md)
- [USB服务开发指导](usb-guidelines.md)
- 位置
- [位置开发概述](device-location-overview.md)
- [获取设备的位置信息](device-location-info.md)
- [(逆)地理编码转化](device-location-geocoding.md)
# (逆)地理编码转化
## 场景介绍
使用坐标描述一个位置,非常准确,但是并不直观,面向用户表达并不友好。
系统向开发者提供了地理编码转化能力(将地理描述转化为具体坐标),以及逆地理编码转化能力(将坐标转化为地理描述)。其中地理编码包含多个属性来描述位置,包括国家、行政区划、街道、门牌号、地址描述等等,这样的信息更便于用户理解。
## 接口说明
进行坐标和地理编码信息的相互转化,所使用的接口说明如下。
**表1** 地理编码转化能力和逆地理编码转化能力的API功能介绍
| 接口名 | 功能描述 |
| -------- | -------- |
| isGeoServiceAvailable(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 判断(逆)地理编码服务状态,使用callback回调异步返回结果。 |
| isGeoServiceAvailable()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 判断(逆)地理编码服务状态,使用Promise方式异步返回结果。 |
| getAddressesFromLocation(request:&nbsp;ReverseGeoCodeRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;)&nbsp;:&nbsp;void | 调用逆地理编码服务,将坐标转换为地理描述,使用callback回调异步返回结果。 |
| getAddressesFromLocation(request:&nbsp;ReverseGeoCodeRequest)&nbsp;:&nbsp;Promise&lt;Array&lt;GeoAddress&gt;&gt;; | 调用逆地理编码服务,将坐标转换为地理描述,使用Promise方式异步返回结果。 |
| getAddressesFromLocationName(request:&nbsp;GeoCodeRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;)&nbsp;:&nbsp;void | 调用地理编码服务,将地理描述转换为具体坐标,使用callback回调异步返回结果。 |
| getAddressesFromLocationName(request:&nbsp;GeoCodeRequest)&nbsp;:&nbsp;Promise&lt;Array&lt;GeoAddress&gt;&gt; | 调用地理编码服务,将地理描述转换为具体坐标,使用Promise方式异步返回结果。 |
## 开发步骤
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> GeoConvert需要访问后端服务,请确保设备联网,以进行信息获取。
1. 导入geolocation模块,所有与(逆)地理编码转化能力相关的功能API,都是通过该模块提供的。
```
import geolocation from '@ohos.geolocation';
```
2. 获取转化结果。
- 调用getAddressesFromLocation,坐标转化地理位置信息。
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data));
});
```
参考接口API说明,应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。
- 调用getAddressesFromLocationName位置描述转化坐标。
```
var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (data) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(data));
});
```
参考接口API说明,应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。
如果需要查询的位置描述可能出现多地重名的请求,可以设置GeoCodeRequest,通过设置一个经纬度范围,以高效地获取期望的准确结果。
# 获取设备的位置信息
## 场景介绍
开发者可以调用OpenHarmony位置相关接口,获取设备实时位置,或者最近的历史位置。
对于位置敏感的应用业务,建议获取设备实时位置信息。如果不需要设备实时位置信息,并且希望尽可能的节省耗电,开发者可以考虑获取最近的历史位置。
## 接口说明
获取设备的位置信息,所使用的接口说明如下。
**表1** 获取位置信息API功能介绍
| 接口名 | 功能描述 |
| -------- | -------- |
| on(type:&nbsp;'locationChange',&nbsp;request:&nbsp;LocationRequest,&nbsp;callback:&nbsp;Callback&lt;Location&gt;)&nbsp;:&nbsp;void | 开启位置变化订阅,并发起定位请求。 |
| off(type:&nbsp;'locationChange',&nbsp;callback?:&nbsp;Callback&lt;Location&gt;)&nbsp;:&nbsp;void | 关闭位置变化订阅,并删除对应的定位请求。 |
| on(type:&nbsp;'locationServiceState',&nbsp;callback:&nbsp;Callback&lt;boolean&gt;)&nbsp;:&nbsp;void | 订阅位置服务状态变化。 |
| off(type:&nbsp;'locationServiceState',&nbsp;callback:&nbsp;Callback&lt;boolean&gt;)&nbsp;:&nbsp;void | 取消订阅位置服务状态变化。 |
| on(type:&nbsp;'cachedGnssLocationsReporting',&nbsp;request:&nbsp;CachedGnssLoactionsRequest,&nbsp;callback:&nbsp;Callback&lt;Array&lt;Location&gt;&gt;)&nbsp;:&nbsp;void; | 订阅缓存GNSS位置上报。 |
| off(type:&nbsp;'cachedGnssLocationsReporting',&nbsp;callback?:&nbsp;Callback&lt;Array&lt;Location&gt;&gt;)&nbsp;:&nbsp;void; | 取消订阅缓存GNSS位置上报。 |
| on(type:&nbsp;'gnssStatusChange',&nbsp;callback:&nbsp;Callback&lt;SatelliteStatusInfo&gt;)&nbsp;:&nbsp;void; | 订阅卫星状态信息更新事件。 |
| off(type:&nbsp;'gnssStatusChange',&nbsp;callback?:&nbsp;Callback&lt;SatelliteStatusInfo&gt;)&nbsp;:&nbsp;void; | 取消订阅卫星状态信息更新事件。 |
| on(type:&nbsp;'nmeaMessageChange',&nbsp;callback:&nbsp;Callback&lt;string&gt;)&nbsp;:&nbsp;void; | 订阅GNSS&nbsp;NMEA信息上报。 |
| off(type:&nbsp;'nmeaMessageChange',&nbsp;callback?:&nbsp;Callback&lt;string&gt;)&nbsp;:&nbsp;void; | 取消订阅GNSS&nbsp;NMEA信息上报。 |
| on(type:&nbsp;'fenceStatusChange',&nbsp;request:&nbsp;GeofenceRequest,&nbsp;want:&nbsp;WantAgent)&nbsp;:&nbsp;void; | 添加围栏,并订阅该围栏事件上报。 |
| off(type:&nbsp;'fenceStatusChange',&nbsp;request:&nbsp;GeofenceRequest,&nbsp;want:&nbsp;WantAgent)&nbsp;:&nbsp;void; | 删除围栏,并取消订阅该围栏事件。 |
| getCurrentLocation(request:&nbsp;CurrentLocationRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Location&gt;)&nbsp;:&nbsp;void | 获取当前位置,使用callback回调异步返回结果。 |
| getCurrentLocation(request?:&nbsp;CurrentLocationRequest)&nbsp;:&nbsp;Promise&lt;Location&gt; | 获取当前位置,使用Promise方式异步返回结果。 |
| getLastLocation(callback:&nbsp;AsyncCallback&lt;Location&gt;)&nbsp;:&nbsp;void | 获取上一次位置,使用callback回调异步返回结果。 |
| getLastLocation()&nbsp;:&nbsp;Promise&lt;Location&gt; | 获取上一次位置,使用Promise方式异步返回结果。 |
| isLocationEnabled(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 判断位置服务是否已经打开,使用callback回调异步返回结果。 |
| isLocationEnabled()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 判断位置服务是否已经开启,使用Promise方式异步返回结果。 |
| requestEnableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 请求打开位置服务,使用callback回调异步返回结果。 |
| requestEnableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 请求打开位置服务,使用Promise方式异步返回结果。 |
| enableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 打开位置服务,使用callback回调异步返回结果。 |
| enableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 打开位置服务,使用Promise方式异步返回结果。 |
| disableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 关闭位置服务,使用callback回调异步返回结果。 |
| disableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 关闭位置服务,使用Promise方式异步返回结果。 |
| getCachedGnssLocationsSize(callback:&nbsp;AsyncCallback&lt;number&gt;)&nbsp;:&nbsp;void; | 获取缓存GNSS位置的个数,使用callback回调异步返回结果。 |
| getCachedGnssLocationsSize()&nbsp;:&nbsp;Promise&lt;number&gt;; | 获取缓存GNSS位置的个数,使用Promise方式异步返回结果。 |
| flushCachedGnssLocations(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用callback回调异步返回结果。 |
| flushCachedGnssLocations()&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用Promise方式异步返回结果。 |
| sendCommand(command:&nbsp;LocationCommand,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 给位置服务子系统发送扩展命令,使用callback回调异步返回结果。 |
| sendCommand(command:&nbsp;LocationCommand)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 给位置服务子系统发送扩展命令,使用Promise方式异步返回结果。 |
| isLocationPrivacyConfirmed(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 查询用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。 |
| isLocationPrivacyConfirmed(type&nbsp;:&nbsp;LocationPrivacyType,)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 查询用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。 |
| setLocationPrivacyConfirmStatus(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;isConfirmed&nbsp;:&nbsp;boolean,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 设置并记录用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。 |
| setLocationPrivacyConfirmStatus(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;isConfirmed&nbsp;:&nbsp;boolean)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 设置并记录用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。 |
## 开发步骤
1. 应用在使用系统能力前,需要检查是否已经获取用户授权访问设备位置信息。如未获得授权,可以向用户申请需要的位置权限,申请方式请参考。
系统提供的定位权限有:
- ohos.permission.LOCATION
- ohos.permission.LOCATION_IN_BACKGROUND
访问设备的位置信息,必须申请ohos.permission.LOCATION权限,并且获得用户授权。
如果应用在后台运行时也需要访问设备位置,除需要将应用声明为允许后台运行外,还必须申请ohos.permission.LOCATION_IN_BACKGROUND权限,这样应用在切入后台之后,系统可以继续上报位置信息。
开发者可以在应用config.json文件中声明所需要的权限,示例代码如下:
```
{
"module": {
"reqPermissions": [{
"name": "ohos.permission.LOCATION",
"reason": "$string:reason_description",
"usedScene": {
"ability": ["com.myapplication.LocationAbility"],
"when": "inuse"
}, {
...
}
]
}
}
```
配置字段详细说明见。
2. 导入geolocation模块,所有与基础定位能力相关的功能API,都是通过该模块提供的。
```
import geolocation from '@ohos.geolocation';
```
3. 实例化LocationRequest对象,用于告知系统该向应用提供何种类型的位置服务,以及位置结果上报的频率。
**方式一:**
为了面向开发者提供贴近其使用场景的API使用方式,系统定义了几种常见的位置能力使用场景,并针对使用场景做了适当的优化处理,应用可以直接匹配使用,简化开发复杂度。系统当前支持场景如下表所示。
```
export enum LocationRequestScenario {
UNSET = 0x300,
NAVIGATION,
TRAJECTORY_TRACKING,
CAR_HAILING,
DAILY_LIFE_SERVICE,
NO_POWER,
}
```
**表2** 定位场景类型说明
| 场景名称 | 常量定义 | 说明 |
| -------- | -------- | -------- |
| 导航场景 | NAVIGATION | 适用于在户外定位设备实时位置的场景,如车载、步行导航。在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务,结合场景特点,在导航启动之初,用户很可能在室内、车库等遮蔽环境,GNSS技术很难提供位置服务。为解决此问题,我们会在GNSS提供稳定位置结果之前,使用系统网络定位技术,向应用提供位置服务,以在导航初始阶段提升用户体验。<br/>此场景默认以最小1秒间隔上报定位结果,使用此场景的应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 轨迹跟踪场景 | TRAJECTORY_TRACKING | 适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 出行约车场景 | CAR_HAILING | 适用于用户出行打车时定位当前位置的场景,如网约车类应用。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 生活服务场景 | DAILY_LIFE_SERVICE | 生活服务场景,适用于不需要定位用户精确位置的使用场景,如新闻资讯、网购、点餐类应用,做推荐、推送时定位用户大致位置即可。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 无功耗场景 | NO_POWER | 无功耗场景,适用于不需要主动启动定位业务。系统在响应其他应用启动定位业务并上报位置结果时,会同时向请求此场景的应用程序上报定位结果,当前的应用程序不产生定位功耗。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用需要申请ohos.permission.LOCATION权限,同时获得用户授权。 |
以导航场景为例,实例化方式如下:
```
var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
**方式二:**
如果定义的现有场景类型不能满足所需的开发场景,系统提供了基本的定位优先级策略类型。
```
export enum LocationRequestPriority {
UNSET = 0x200,
ACCURACY,
LOW_POWER,
FIRST_FIX,
}
```
**表3** 定位优先级策略类型说明:
| 策略类型 | 常量定义 | 说明 |
| -------- | -------- | -------- |
| 定位精度优先策略 | ACCURACY | 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。<br/>应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 快速定位优先策略 | FAST_FIRST_FIX | 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。<br/>应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 低功耗定位优先策略 | LOW_POWER | 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。<br/>应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。 |
以定位精度优先策略为例,实例化方式如下:
```
var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
4. 实例化Callback对象,用于向系统提供位置上报的途径。
应用需要自行实现系统定义好的回调接口,并将其实例化。系统在定位成功确定设备的实时位置结果时,会通过该接口上报给应用。应用程序可以在接口的实现中完成自己的业务逻辑。
```
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
```
5. 启动定位。
```
geolocation.on('locationChange', requestInfo, locationChange);
```
6. (可选)结束定位。
```
geolocation.off('locationChange', locationChange);
```
如果应用使用场景不需要实时的设备位置,可以获取系统缓存的最近一次历史定位结果。
```
geolocation.getLastLocation((data) => {
console.log('getLastLocation: data: ' + JSON.stringify(data));
});
```
此接口的使用需要应用向用户申请ohos.permission.LOCATION权限。
# 位置开发概述
移动终端设备已经深入人们日常生活的方方面面,如查看所在城市的天气、新闻轶事、出行打车、旅行导航、运动记录。这些习以为常的活动,都离不开定位用户终端设备的位置。
当用户处于这些丰富的使用场景中时,系统的位置能力可以提供实时准确的位置数据。对于开发者,设计基于位置体验的服务,也可以使应用的使用体验更贴近每个用户。
当应用在实现基于设备位置的功能时,如:驾车导航,记录运动轨迹等,可以调用该模块的API接口,完成位置信息的获取。
## 基本概念
位置能力用于确定用户设备在哪里,系统使用位置坐标标示设备的位置,并用多种定位技术提供服务,如GNSS定位、基站定位、WLAN/蓝牙定位(基站定位、WLAN/蓝牙定位后续统称“网络定位技术”)。通过这些定位技术,无论用户设备在室内或是户外,都可以准确地确定设备位置。
- **坐标**
系统以1984年世界大地坐标系统为参考,使用经度、纬度数据描述地球上的一个位置。
- **GNSS定位**
基于全球导航卫星系统,包含:GPS、GLONASS、北斗、Galileo等,通过导航卫星、设备芯片提供的定位算法,来确定设备准确位置。定位过程具体使用哪些定位系统,取决于用户设备的硬件能力。
- **基站定位**
根据设备当前驻网基站和相邻基站的位置,估算设备当前位置。此定位方式的定位结果精度相对较低,并且需要设备可以访问蜂窝网络。
- **WLAN、蓝牙定位**
根据设备可搜索到的周围WLAN、蓝牙设备位置,估算设备当前位置。此定位方式的定位结果精度依赖设备周围可见的固定WLAN、蓝牙设备的分布,密度较高时,精度也相较于基站定位方式更高,同时也需要设备可以访问网络。
## 运作机制
位置能力作为系统为应用提供的一种基础服务,需要应用在所使用的业务场景,向系统主动发起请求,并在业务场景结束时,主动结束此请求,在此过程中系统会将实时的定位结果上报给应用。
## 约束与限制
使用设备的位置能力,需要用户进行确认并主动开启位置开关。如果位置开关没有开启,系统不会向任何应用提供位置服务。
设备位置信息属于用户敏感数据,所以即使用户已经开启位置开关,应用在获取设备位置前仍需向用户申请位置访问权限。在用户确认允许后,系统才会向应用提供位置服务。
......@@ -57,6 +57,7 @@
- 通信与连接
- [WLAN](js-apis-wifi.md)
- [Bluetooth](js-apis-bluetooth.md)
- [RPC通信](js-apis-rpc.md)
- 设备管理
- [传感器](js-apis-sensor.md)
- [振动](js-apis-vibrator.md)
......@@ -72,6 +73,7 @@
- [显示设备属性](js-apis-display.md)
- [升级](js-apis-update.md)
- [USB管理](js-apis-usb.md)
- [位置服务](js-apis-geolocation.md)
- 基本功能
- [应用上下文](js-apis-basic-features-app-context.md)
- [日志打印](js-apis-basic-features-logs.md)
......
......@@ -13,7 +13,7 @@ Ability运行相关信息。
通过abilityManager中getAbilityRunningInfos方法获取。
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => {
......@@ -23,14 +23,14 @@ abilitymanager.getAbilityRunningInfos((err,data) => {
## 属性
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| ability | ElementName | 是 | 否 | Ability匹配信息。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| pid | number | 是 | 否 | 进程ID。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| uid | number | 是 | 否 | 用户ID。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| processName | string | 是 | 否 | 进程名称。 <br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| startTime | number | 是 | 否 | Ability启动时间。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| abilityState | [abilityManager.AbilityState](#abilitymanager-abilitystate) | 是 | 否 | Ability状态。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| ability | ElementName | 是 | 否 | Ability匹配信息。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| pid | number | 是 | 否 | 进程ID。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| uid | number | 是 | 否 | 用户ID。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| processName | string | 是 | 否 | 进程名称。 <br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| startTime | number | 是 | 否 | Ability启动时间。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
| abilityState | [abilityManager.AbilityState](#abilitymanagerabilitystate) | 是 | 否 | Ability状态。<br/>**系统能力**:SystemCapability.Ability.AbilityRuntime.Core |
## abilityManager.AbilityState
......
......@@ -2531,7 +2531,7 @@ createVideoOutput(surfaceId: string, callback: AsyncCallback<VideoOutput\>): voi
| 名称 | 类型 | 必填 | 说明 |
|------------|-------------------------------|-----------|----------------------------------------------------|
| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 |
| callback | AsyncCallback<[VideoOutput](#videootput)\> | 是 | 回调函数,用于获取VideoOutput实例。 |
| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 |
**示例:**
......
......@@ -61,17 +61,17 @@ createKVManager(config: KVManagerConfig): Promise&lt;KVManager&gt;
创建一个KVManager对象实例,用于管理数据库对象,并通过Promise方式返回,此方法为异步方法。
- 参数:
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ------ | ------ |
| config |[KVManagerConfig](#kvmanager) | 是 | 提供KVManager实例的配置信息,包括调用方的包名和用户信息。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;[KVManager](#kvmanager)&gt; | 指定的Promise回调方法,返回创建的KVManager对象实例。 |
- 示例:
```
......@@ -363,7 +363,7 @@ deleteKVStore(appId: string, storeId: string): Promise&lt;void&gt;;
通过storeId的值删除指定的kvStore数据库,并通过Promise方式返回,此方法为异步方法。
- 参数:
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| appId | string | 是 | 所调用数据库方的包名。 |
......@@ -450,7 +450,7 @@ getAllKVStoreId(appId: string): Promise&lt;string[]&gt;;
- 返回值:
| 类型 | 说明 |
| ------------- | -------------- |
| Promise&lt;string[]&gt;| Promise实例,返回所有创建的 KvStore 数据库的 storeId。 |
......@@ -517,7 +517,7 @@ off(event: 'distributedDataServiceDie', deathCallback?: Callback&lt;void&gt;): v
| ----- | ------ | ---- | ----------------------- |
| event | 'distributedDataServiceDie' | 是 | 服务状态改变时触发的事件名。 |
| deathCallback | Callback&lt;void&gt; | 否 | 回调函数,取消设备状态改变时获取通知。 |
- 示例
......@@ -633,7 +633,7 @@ appendChild(child: FieldNode): boolean;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| child | [FieldNode](#FieldNode) | 是 | 要附加的域节点。 |
- 返回值:
......@@ -1138,7 +1138,7 @@ reset(): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回重置的 Query 对象。|
| [Query](#query8) |返回重置的 Query 对象。|
- 示例
......@@ -1173,7 +1173,7 @@ equalTo(field: string, value: number|string|boolean): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回重置的 Query 对象。|
| [Query](#query8) |返回重置的 Query 对象。|
- 示例
......@@ -1206,7 +1206,7 @@ notEqualTo(field: string, value: number|string|boolean): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回重置的 Query 对象。|
| [Query](#query8) |返回重置的 Query 对象。|
- 示例
......@@ -1239,7 +1239,7 @@ greaterThan(field: string, value: number|string|boolean): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1272,7 +1272,7 @@ lessThan(field: string, value: number|string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1305,7 +1305,7 @@ greaterThanOrEqualTo(field: string, value: number|string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1338,7 +1338,7 @@ lessThanOrEqualTo(field: string, value: number|string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1370,7 +1370,7 @@ isNull(field: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1403,7 +1403,7 @@ inNumber(field: string, valueList: number[]): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1437,7 +1437,7 @@ inString(field: string, valueList: string[]): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1470,7 +1470,7 @@ notInNumber(field: string, valueList: number[]): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1503,7 +1503,7 @@ notInString(field: string, valueList: string[]): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1536,7 +1536,7 @@ like(field: string, value: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1569,7 +1569,7 @@ unlike(field: string, value: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1595,7 +1595,7 @@ and(): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1623,7 +1623,7 @@ or(): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1657,7 +1657,7 @@ orderByAsc(field: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1690,7 +1690,7 @@ orderByDesc(field: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1725,7 +1725,7 @@ limit(total: number, offset: number): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1758,7 +1758,7 @@ isNotNull(field: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1784,7 +1784,7 @@ beginGroup(): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1812,7 +1812,7 @@ endGroup(): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1846,7 +1846,7 @@ prefixKey(prefix: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1879,7 +1879,7 @@ setSuggestIndex(index: string): Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1913,7 +1913,7 @@ deviceId(deviceId:string):Query;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -1938,7 +1938,7 @@ getSqlLike():string;
| 类型 | 说明 |
| ------ | ------- |
| [Query](#querysup8sup) |返回查询对象。|
| [Query](#query8) |返回查询对象。|
- 示例
......@@ -2121,8 +2121,8 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotific
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| event |'dataChange' | 是 |回调函数名称。 |
| type |[SubscribeType](#subscribetypea) | 是 |表示订阅的类型。 |
| observer |Callback&lt;[ChangeNotification](#changenotificationa)&gt; | 是 |回调函数。 |
| type |[SubscribeType](#subscribetype) | 是 |表示订阅的类型。 |
| observer |Callback&lt;[ChangeNotification](#changenotification)&gt; | 是 |回调函数。 |
- 示例
......@@ -2169,7 +2169,7 @@ off(event:'dataChange', observer?: Callback&lt;ChangeNotification&gt;): void;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| event |'dataChange' | 是 |回调函数名称。 |
| observer |Callback&lt;[ChangeNotification](#changenotificationa)&gt; |否 |回调函数。 |
| observer |Callback&lt;[ChangeNotification](#changenotification)&gt; |否 |回调函数。 |
- 示例
......@@ -2961,7 +2961,7 @@ getEntries(query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示要匹配的键前缀。 |
| query |[Query](#query8) | 是 |表示要匹配的键前缀。 |
| callback |AsyncCallback&lt;Entry[]&gt; | 是 |回调函数,获取指定前缀的键值对列表。 |
- 示例
......@@ -3010,7 +3010,7 @@ getEntries(query: Query): Promise&lt;Entry[]&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
......@@ -3066,7 +3066,7 @@ getResultSet(keyPrefix: string, callback: AsyncCallback&lt;KvStoreResultSet&gt;)
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| keyPrefix |string | 是 |表示要匹配的键前缀。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; | 是 |表示要匹配的键前缀。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | 是 |表示要匹配的键前缀。 |
- 示例
......@@ -3118,7 +3118,7 @@ getResultSet(keyPrefix: string): Promise&lt;KvStoreResultSet&gt;;
| 类型 | 说明 |
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; |Promise实例,用于获取异步返回结果。|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise实例,用于获取异步返回结果。|
- 示例
......@@ -3171,7 +3171,7 @@ getResultSet(query: Query, callback: AsyncCallback&lt;KvStoreResultSet&gt;): voi
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |Query | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; | 是 |回调函数,获取与指定 Query 对象匹配的 KvStoreResultSet 对象。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | 是 |回调函数,获取与指定 Query 对象匹配的 KvStoreResultSet 对象。 |
- 示例
......@@ -3216,13 +3216,13 @@ getResultSet(query: Query): Promise&lt;KvStoreResultSet&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
| 类型 | 说明 |
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)&gt; |Promise实例,用于获取异步返回结果。|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise实例,用于获取异步返回结果。|
- 示例
......@@ -3270,7 +3270,7 @@ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback&lt;void&gt;)
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#kvstoreresultsetsup8sup) | 是 |表示要关闭的 KvStoreResultSet 对象。 |
| resultSet |[KvStoreResultSet](#kvstoreresultset8) | 是 |表示要关闭的 KvStoreResultSet 对象。 |
| callback |AsyncCallback&lt;void&gt; | 是 |回调函数,获取由 getResultSet 返回的 KvStoreResultSet 对象。 |
- 示例
......@@ -3302,7 +3302,7 @@ closeResultSet(resultSet: KvStoreResultSet): Promise&lt;void&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#kvstoreresultsetsup8sup) | 是 |表示要关闭的 KvStoreResultSet 对象。 |
| resultSet |[KvStoreResultSet](#kvstoreresultset8) | 是 |表示要关闭的 KvStoreResultSet 对象。 |
- 返回值:
......@@ -3337,7 +3337,7 @@ getResultSize(query: Query, callback: AsyncCallback&lt;number&gt;): void;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;number&gt; | 是 |回调函数,获取与指定 Query 对象匹配的结果数。 |
- 示例
......@@ -3381,7 +3381,7 @@ getResultSize(query: Query): Promise&lt;number&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
......@@ -3909,7 +3909,7 @@ getEntries(query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | 是 |回调函数,返回与指定 Query 对象匹配的键值对列表。 |
- 示例
......@@ -3960,7 +3960,7 @@ getEntries(query: Query): Promise&lt;Entry[]&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
......@@ -4017,7 +4017,7 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | 是 |键值对所属的设备ID。 |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;[Entry](#entry)[]&gt; | 是 |回调函数,返回与指定 Query 对象匹配的键值对列表。 |
- 示例
......@@ -4069,7 +4069,7 @@ getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | 是 |键值对所属的设备ID。 |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
......@@ -4128,7 +4128,7 @@ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KvS
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | 是 |标识要查询其数据的设备。 |
| keyPrefix |string | 是 |表示要匹配的键前缀。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; | 是 |回调函数,返回 KvStoreResultSet 对象。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | 是 |回调函数,返回 KvStoreResultSet 对象。 |
- 示例
......@@ -4166,7 +4166,7 @@ getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KvStoreResultSet&g
| 类型 | 说明 |
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; |Promise实例,用于获取异步返回结果。|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise实例,用于获取异步返回结果。|
- 示例
......@@ -4201,8 +4201,8 @@ getResultSet(query: Query, callback: AsyncCallback&lt;KvStoreResultSet&gt;): voi
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; | 是 |回调函数,返回与指定 Query 对象匹配的 KvStoreResultSet 对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | 是 |回调函数,返回与指定 Query 对象匹配的 KvStoreResultSet 对象。 |
- 示例
......@@ -4251,13 +4251,13 @@ getResultSet(query: Query): Promise&lt;KvStoreResultSet&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
| 类型 | 说明 |
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; |Promise实例,用于获取异步返回结果。|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise实例,用于获取异步返回结果。|
- 示例
......@@ -4314,8 +4314,8 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KvStoreR
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; | 是 |回调函数,返回与指定 Query 对象匹配的 KvStoreResultSet 对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | 是 |回调函数,返回与指定 Query 对象匹配的 KvStoreResultSet 对象。 |
- 示例
......@@ -4364,13 +4364,13 @@ getResultSet(deviceId: string, query: Query): Promise&lt;KvStoreResultSet&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
| 类型 | 说明 |
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultsetsup8sup)[]&gt; |Promise实例,用于获取异步返回结果。|
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise实例,用于获取异步返回结果。|
- 示例
......@@ -4427,7 +4427,7 @@ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback&lt;void&gt;)
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#getresultsetsup8sup) | 是 |指示要关闭的 KvStoreResultSet 对象。 |
| resultSet |[KvStoreResultSet](#getresultset8) | 是 |指示要关闭的 KvStoreResultSet 对象。 |
| callback |AsyncCallback&lt;void&gt; | 是 |回调函数。 |
- 示例
......@@ -4460,7 +4460,7 @@ closeResultSet(resultSet: KvStoreResultSet): Promise&lt;void&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| resultSet |[KvStoreResultSet](#getresultsetsup8sup) | 是 |指示要关闭的 KvStoreResultSet 对象。 |
| resultSet |[KvStoreResultSet](#getresultset8) | 是 |指示要关闭的 KvStoreResultSet 对象。 |
- 返回值:
......@@ -4496,7 +4496,7 @@ getResultSize(query: Query, callback: AsyncCallback&lt;number&gt;): void;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;number&gt; | 是 |回调函数,返回与指定 Query 对象匹配的结果数。 |
- 示例
......@@ -4541,7 +4541,7 @@ getResultSize(query: Query): Promise&lt;number&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
......@@ -4596,7 +4596,7 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
| callback |AsyncCallback&lt;number&gt; | 是 |回调函数,返回与指定 Query 对象匹配的结果数。 |
- 示例
......@@ -4641,7 +4641,7 @@ getResultSize(deviceId: string, query: Query): Promise&lt;number&gt;;
| 参数名 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ----------------------- |
| deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 |
| query |[Query](#querysup8sup) | 是 |表示查询对象。 |
| query |[Query](#query8) | 是 |表示查询对象。 |
- 返回值:
......
......@@ -13,7 +13,7 @@ Extension运行相关信息。
通过abilityManager中方法获取。
```
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
......@@ -24,15 +24,15 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
### 属性
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| extension | ElementName | 是 | 否 | Extension匹配信息。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| pid | number | 是 | 否 | 进程ID。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| uid | number | 是 | 否 | 用户ID。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| processName | string | 是 | 否 | 进程名称。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| startTime | number | 是 | 否 | Extension启动时间。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| clientPackage | Array&lt;String&gt; | 是 | 否 | 表示当期进程下的所有包名。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| type | [bundle.ExtensionAbilityType](#bundle-extensionabilitytype) | 是 | 否 | Extension类型。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| extension | ElementName | 是 | 否 | Extension匹配信息。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| pid | number | 是 | 否 | 进程ID。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| uid | number | 是 | 否 | 用户ID。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| processName | string | 是 | 否 | 进程名称。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| startTime | number | 是 | 否 | Extension启动时间。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| clientPackage | Array&lt;String&gt; | 是 | 否 | 表示当期进程下的所有包名。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
| type | [bundle.ExtensionAbilityType](#bundleextensionabilitytype) | 是 | 否 | Extension类型。<br><b>系统能力:</b>SystemCapability.Ability.AbilityRuntime.Core |
## bundle.ExtensionAbilityType
......
# 位置服务(新)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```
import geolocation from '@ohos.geolocation';
```
## 权限
ohos.permission.LOCATION
ohos.permission.LOCATION_IN_BACKGROUND
## geolocation.on('locationChange')
on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;) : void
开启位置变化订阅,并发起定位请求。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“locationChange”,表示位置变化。 |
| request | LocationRequest | 是 | 设置位置请求参数。 |
| callback | Callback&lt;[Location](#location)&gt; | 是 | 接收位置变化状态变化监听。 |
- 示例:
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
geolocation.on('locationChange', requestInfo, locationChange);
```
## geolocation.off('locationChange')
off(type: 'locationChange', callback?: Callback&lt;Location&gt;) : void
关闭位置变化订阅,并删除对应的定位请求。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“locationChange”,表示位置变化。 |
| callback | Callback&lt;[Location](#location)&gt; | 否 | 接收位置变化状态变化监听。 |
- 示例:
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
geolocation.on('locationChange', requestInfo, locationChange);
geolocation.off('locationChange', locationChange);
```
## geolocation.on('locationServiceState')
on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void
订阅位置服务状态变化。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“locationServiceState”,表示位置服务状态。 |
| callback | Callback&lt;boolean&gt; | 是 | 接收位置服务状态变化监听。 |
- 示例:
```
var locationServiceState = (state) => {
console.log('locationServiceState: ' + state);
}
geolocation.on('locationServiceState', locationServiceState);
```
## geolocation.off('locationServiceState')
off(type: 'locationServiceState', callback?: Callback&lt;boolean&gt;) : void;
取消订阅位置服务状态变化。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“locationServiceState”,表示位置服务状态。 |
| callback | Callback&lt;boolean&gt; | 否 | 接收位置服务状态变化监听。 |
- 示例:
```
var locationServiceState = (state) => {
console.log('locationServiceState: state: ' + state);
}
geolocation.on('locationServiceState', locationServiceState);
geolocation.off('locationServiceState', locationServiceState);
```
## geolocation.on('cachedGnssLocationsReporting')
on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;) : void;
订阅缓存GNSS定位结果上报事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“cachedGnssLocationsReporting”,表示GNSS缓存定位结果上报。 |
| request | CachedGnssLocationsRequest | 是 | GNSS缓存功能配置参数 |
| callback | Callback&lt;boolean&gt; | 是 | 接收GNSS缓存位置上报。 |
- 示例:
```
var cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsReporting: locations: ' + locations);
}
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);
```
## geolocation.off('cachedGnssLocationsReporting')
off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;) : void;
取消订阅缓存GNSS定位结果上报事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“cachedGnssLocationsReporting”,表示GNSS缓存定位结果上报。 |
| callback | Callback&lt;boolean&gt; | 否 | 接收GNSS缓存位置上报。 |
- 示例:
```
var cachedLocationsCb = (locations) => {
console.log('cachedGnssLocationsReporting: locations: ' + locations);
}
var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);
geolocation.off('cachedGnssLocationsReporting');
```
## geolocation.on('gnssStatusChange')
on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) : void;
订阅GNSS卫星状态信息上报事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 |
| callback | Callback&lt;SatelliteStatusInfo&gt; | 是 | 接收GNSS卫星状态信息上报。 |
- 示例:
```
var gnssStatusCb = (satelliteStatusInfo) => {
console.log('gnssStatusChange: ' + satelliteStatusInfo);
}
geolocation.on('gnssStatusChange', gnssStatusCb);
```
## geolocation.off('gnssStatusChange')
off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;) : void;
取消订阅GNSS卫星状态信息上报事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 |
| callback | Callback&lt;SatelliteStatusInfo&gt; | 否 | 接收GNSS卫星状态信息上报。 |
- 示例:
```
var gnssStatusCb = (satelliteStatusInfo) => {
console.log('gnssStatusChange: ' + satelliteStatusInfo);
}
geolocation.on('gnssStatusChange', gnssStatusCb);
geolocation.off('gnssStatusChange', gnssStatusCb);
```
## geolocation.on('nmeaMessageChange')
on(type: 'nmeaMessageChange', callback: Callback&lt;string&gt;) : void;
订阅GNSS NMEA信息上报事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“nmeaMessageChange”,表示订阅GNSS&nbsp;NMEA信息上报。 |
| callback | Callback&lt;string&gt; | 是 | 接收GNSS&nbsp;NMEA信息上报。 |
- 示例:
```
var nmeaCb = (str) => {
console.log('nmeaMessageChange: ' + str);
}
geolocation.on('nmeaMessageChange', nmeaCb );
```
## geolocation.off('nmeaMessageChange')
off(type: 'nmeaMessageChange', callback?: Callback&lt;string&gt;) : void;
取消订阅GNSS NMEA信息上报事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“nmeaMessageChange”,表示订阅GNSS&nbsp;NMEA信息上报。 |
| callback | Callback&lt;string&gt; | 否 | 接收GNSS&nbsp;NMEA信息上报。 |
- 示例:
```
var nmeaCb = (str) => {
console.log('nmeaMessageChange: ' + str);
}
geolocation.on('nmeaMessageChange', nmeaCb);
geolocation.off('nmeaMessageChange', nmeaCb);
```
## geolocation.on('fenceStatusChange')
on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void;
添加一个围栏,并订阅地理围栏事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 |
| request | GeofenceRequest | 是 | 围栏的配置参数。 |
| want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 |
- 示例:
```
import WantAgent from '@ohos.wantAgent';
import { OperationType, WantAgentFlags } from '@ohos.wantagent';
//wantAgent对象
var wantAgent;
//getWantAgent回调
function getWantAgentCallback(err, data) {
console.info("==========================>getWantAgentCallback=======================>");
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
//WantAgentInfo对象
var wantAgentInfo = {
wants: [
{
deviceId: "deviceId",
bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters:
{
mykey0: 2222,
mykey1: [1, 2, 3],
mykey2: "[1, 2, 3]",
mykey3: "ssssssssssssssssssssssssss",
mykey4: [false, true, false],
mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
mykey6: true,
}
}
],
operationType: OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG]
}
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
geolocation.on('fenceStatusChange', requestInfo, wantAgent);
```
## geolocation.off('fenceStatusChange')
off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void;
删除一个围栏,并取消订阅该围栏事件。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 |
| request | GeofenceRequest | 是 | 围栏的配置参数。 |
| want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 |
- 示例:
```
import WantAgent from '@ohos.wantAgent';
import { OperationType, WantAgentFlags } from '@ohos.wantagent';
//wantAgent对象
var wantAgent;
//getWantAgent回调
function getWantAgentCallback(err, data) {
console.info("==========================>getWantAgentCallback=======================>");
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
//WantAgentInfo对象
var wantAgentInfo = {
wants: [
{
deviceId: "deviceId",
bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters:
{
mykey0: 2222,
mykey1: [1, 2, 3],
mykey2: "[1, 2, 3]",
mykey3: "ssssssssssssssssssssssssss",
mykey4: [false, true, false],
mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"],
mykey6: true,
}
}
],
operationType: OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG]
}
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
geolocation.on('fenceStatusChange', requestInfo, wantAgent);
geolocation.off('fenceStatusChange', requestInfo, wantAgent);
```
## geolocation.getCurrentLocation
getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;) : void
获取当前位置,使用callback回调异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| request | [CurrentLocationRequest](#currentlocationrequest) | 否 | 设置位置请求参数。 |
| callback | AsyncCallback&lt;[Location](#location)&gt; | 是 | 用来接收位置信息的回调。 |
- 示例:
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
var locationChange = (err, location) => {
console.log('locationChanger: ' + err + 'data: ' + location);
};
geolocation.getCurrentLocation(requestInfo, locationChange);
geolocation.getCurrentLocation(locationChange);
```
## geolocation.getCurrentLocation
getCurrentLocation(request?: CurrentLocationRequest) : Promise&lt;Location&gt;
获取当前位置,使用Promise方式异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| request | [CurrentLocationRequest](#currentlocationrequest) | 否 | 设置位置请求参数。 |
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;[Location](#location)&gt; | 返回位置信息。 |
- 示例:
```
var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
locationEventListener.getCurrentLocation(requestInfo).then((result) => {
console.log('current location: ' + JSON.stringify(result));
});
```
## geolocation.getLastLocation
getLastLocation(callback: AsyncCallback&lt;Location&gt;) : void
获取上一次位置,使用callback回调异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[Location](#location)&gt; | 是 | 用来接收上次位置的回调。 |
- 示例:
```
geolocation.getLastLocation((err, data) => {
console.log('getLastLocation: ' + err + " data: " + JSON.stringify(data));
});
```
## geolocation.getLastLocation
getLastLocation() : Promise&lt;Location&gt;
获取上一次位置,使用Promise方式异步返回结果。
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;[Location](#location)&gt; | 返回上次位置信息。 |
- 示例:
```
geolocation.getLastLocation().then((result) => {
console.log('getLastLocation: result: ' + JSON.stringify(result));
});
```
## geolocation.isLocationEnabled
isLocationEnabled(callback: AsyncCallback&lt;boolean&gt;) : void
判断位置服务是否已经打开,使用callback回调异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 用来接收位置服务状态的回调。 |
- 示例:
```
geolocation.isLocationEnabled((err, data) => {
console.log('isLocationEnabled: ' + err + " data: " + data);
});
```
## geolocation.isLocationEnabled
isLocationEnabled() : Promise&lt;boolean&gt;
判断位置服务是否已经开启,使用Promise方式异步返回结果。
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 返回位置服务是否可用的状态。 |
- 示例:
```
geolocation.isLocationEnabled().then((result) => {
console.log('promise, isLocationEnabled: ' + result);
});
```
## geolocation.requestEnableLocation
requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;) : void
请求打开位置服务,使用callback回调异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 用来接收位置服务状态的回调。 |
- 示例:
```
geolocation.requestEnableLocation((err, data) => {
console.log('requestEnableLocation: ' + err + " data: " + data);
});
```
## geolocation.requestEnableLocation
requestEnableLocation() : Promise&lt;boolean&gt;
请求打开位置服务,使用Promise方式异步返回结果。
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 返回位置服务是否可用。 |
- 示例:
```
geolocation.requestEnableLocation().then((result) => {
console.log('promise, requestEnableLocation: ' + result);
});
```
## geolocation.isGeoServiceAvailable
isGeoServiceAvailable(callback: AsyncCallback&lt;boolean&gt;) : void
判断(逆)地理编码服务状态,使用callback回调异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 用来接收地理编码服务状态的回调。 |
- 示例:
```
geolocation.isGeoServiceAvailable((err, data) => {
console.log('isGeoServiceAvailable: ' + err + " data: " + data);
});
```
## geolocation.isGeoServiceAvailable
isGeoServiceAvailable() : Promise&lt;boolean&gt;
判断(逆)地理编码服务状态,使用Promise方式异步返回结果。
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 返回地理编码服务是否可用的状态。 |
- 示例:
```
geolocation.isGeoServiceAvailable().then((result) => {
console.log('promise, isGeoServiceAvailable: ' + result);
});
```
## geolocation.getAddressesFromLocation
getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void
调用逆地理编码服务,将坐标转换为地理描述,使用callback回调异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| request | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 设置逆地理编码请求的相关参数。 |
| callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | 是 | 设置接收逆地理编码请求的回调参数。 |
- 示例:
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
console.log('getAddressesFromLocation: ' + err + " data: " + JSON.stringify(data));
});
```
## geolocation.getAddressesFromLocation
getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt;;
调用逆地理编码服务,将坐标转换为地理描述,使用Promise方式异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| request | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 设置逆地理编码请求的相关参数。 |
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | 返回地理描述信息。 |
- 示例:
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data));
});
```
## geolocation.getAddressesFromLocationName
getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void
调用地理编码服务,将地理描述转换为具体坐标,使用callback回调异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| request | [GeoCodeRequest](#geocoderequest) | 是 | 设置地理编码请求的相关参数。 |
| callback | AsyncCallback&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | 是 | 设置接收地理编码请求的回调参数。 |
- 示例:
```
var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
console.log('getAddressesFromLocationName: ' + err + " data: " + JSON.stringify(data));
});
```
## geolocation.getAddressesFromLocationName
getAddressesFromLocationName(request: GeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt;
调用地理编码服务,将地理描述转换为具体坐标,使用Promise方式异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| request | [GeoCodeRequest](#geocoderequest) | 是 | 设置地理编码请求的相关参数。 |
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | 设置接收地理编码请求的回调参数。 |
- 示例:
```
var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(result));
});
```
## geolocation.getCachedGnssLocationsSize
getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;) : void;
获取GNSS芯片缓存位置的个数。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | 是 | 用来接收GNSS芯片缓存位置个数的回调。 |
- 示例:
```
geolocation.getCachedGnssLocationsSize((err, size) => {
console.log('getCachedGnssLocationsSize: err:' + err + " size: " + size);
});
```
## geolocation.getCachedGnssLocationsSize
getCachedGnssLocationsSize() : Promise&lt;number&gt;;
获取GNSS芯片缓存位置的个数。
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;number&gt; | 返回GNSS缓存位置的个数。 |
- 示例:
```
geolocation.getCachedGnssLocationsSize().then((result) => {
console.log('promise, getCachedGnssLocationsSize: ' + result);
});
```
## geolocation.flushCachedGnssLocations
flushCachedGnssLocations(callback: AsyncCallback&lt;boolean&gt;) : void;
读取并清空GNSS芯片所有缓存位置。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 用来接收清空GNSS芯片缓存位置操作的结果。 |
- 示例:
```
geolocation.flushCachedGnssLocations((err, result) => {
console.log('flushCachedGnssLocations: err:' + err + " result: " + result);
});
```
## geolocation.flushCachedGnssLocations
flushCachedGnssLocations() : Promise&lt;boolean&gt;;
读取并清空GNSS芯片所有缓存位置。
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 清空所有GNSS缓存位置是否成功。 |
- 示例:
```
geolocation.flushCachedGnssLocations().then((result) => {
console.log('promise, flushCachedGnssLocations: ' + result);
});
```
## geolocation.sendCommand
sendCommand(command: LocationCommand, callback: AsyncCallback&lt;boolean&gt;) : void;
给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| command | LocationCommand | 是 | 指定目标场景,和将要发送的命令(字符串)。 |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 用来接收命令发送的结果。 |
- 示例:
```
var requestInfo = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo, (err, result) => {
console.log('sendCommand: err:' + err + " result: " + result);
});
```
## geolocation.sendCommand
sendCommand(command: LocationCommand) : Promise&lt;boolean&gt;;
给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| command | LocationCommand | 是 | 指定目标场景,和将要发送的命令(字符串)。 |
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 表示命令发送成功或失败。 |
- 示例:
```
var requestInfo = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo).then((result) => {
console.log('promise, sendCommand: ' + result);
});
```
## geolocation.isLocationPrivacyConfirmed
isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback&lt;boolean&gt;) : void;
查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 表示用户是否同意定位服务隐私申明。 |
- 示例:
```
geolocation.isLocationPrivacyConfirmed(1, (err, result) => {
console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result);
});
```
## geolocation.isLocationPrivacyConfirmed
isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise&lt;boolean&gt;;
查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 |
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 表示用户是否同意定位服务隐私申明。 |
- 示例:
```
geolocation.isLocationPrivacyConfirmed(1).then((result) => {
console.log('promise, isLocationPrivacyConfirmed: ' + result);
});
```
## geolocation.setLocationPrivacyConfirmStatus
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback&lt;boolean&gt;) : void;
设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 |
| isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 表示操作是否成功。 |
- 示例:
```
geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => {
console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result);
});
```
## geolocation.setLocationPrivacyConfirmStatus
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise&lt;boolean&gt;;
设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 |
| isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 |
- 返回值:
| 参数名 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 表示操作是否成功。 |
- 示例:
```
geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => {
console.log('promise, setLocationPrivacyConfirmStatus: ' + result);
});
```
## LocationRequestPriority
位置请求中位置信息优先级设置。
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| UNSET | 0x200 | 表示未设置优先级。 |
| ACCURACY | 0x201 | 表示精度优先。 |
| LOW_POWER | 0x202 | 表示低功耗优先。 |
| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 |
## LocationRequestScenario
位置请求中定位场景设置。
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| UNSET | 0x300 | 表示未设置场景信息。 |
| NAVIGATION | 0x301 | 表示导航场景。 |
| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 |
| CAR_HAILING | 0x303 | 表示打车场景。 |
| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 |
| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 |
## GeoLocationErrorCode
位置服务中的错误码信息。
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| INPUT_PARAMS_ERROR | 101 | 表示输入参数错误。 |
| REVERSE_GEOCODE_ERROR | 102 | 表示逆地理编码接口调用失败。 |
| GEOCODE_ERROR | 103 | 表示地理编码接口调用失败。 |
| LOCATOR_ERROR | 104 | 表示定位失败。 |
| LOCATION_SWITCH_ERROR | 105 | 表示定位开关。 |
| LAST_KNOWN_LOCATION_ERROR | 106 | 表示获取上次位置失败。 |
| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | 表示单次定位,没有在指定时间内返回位置。 |
## ReverseGeoCodeRequest
逆地理编码请求接口。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| locale | string | 否 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 |
| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 |
| longitude | number | 是 | 表示经度信息,正值表示东经,负值表示西经。 |
| maxItems | number | 否 | 指定返回位置信息的最大个数。 |
## GeoCodeRequest
地理编码请求接口。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 |
| description | number | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 |
| maxItems | number | 否 | 表示返回位置信息的最大个数。 |
| minLatitude | number | 否 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 |
| minLongitude | number | 否 | 表示最小经度信息。 |
| maxLatitude | number | 否 | 表示最大纬度信息。 |
| maxLongitude | number | 否 | 表示最大经度信息。 |
## GeoAddress
地理编码类型。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| latitude | number | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 |
| longitude | number | 否 | 表示经度信息,正值表示东经,负值表是西经。 |
| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 |
| placeName | string | 否 | 表示地区信息。 |
| countryCode | string | 否 | 表示国家码信息。 |
| countryName | string | 否 | 表示国家信息。 |
| administrativeArea | string | 否 | 表示省份区域信息。 |
| subAdministrativeArea | string | 否 | 表示表示子区域信息。 |
| locality | string | 否 | 表示城市信息。 |
| subLocality | string | 否 | 表示子城市信息。 |
| roadName | string | 否 | 表示路名信息。 |
| subRoadName | string | 否 | 表示子路名信息。 |
| premises | string | 否 | 表示门牌号信息。 |
| postalCode | string | 否 | 表示邮政编码信息。 |
| phoneNumber | string | 否 | 表示联系方式信息。 |
| addressUrl | string | 否 | 表示位置信息附件的网址信息。 |
| descriptions | Array&lt;string&gt; | 否 | 表示附加的描述信息。 |
| descriptionsSize | number | 否 | 表示附加的描述信息数量。 |
## LocationRequest
位置信息请求类型。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 |
| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示场景信息。 |
| timeInterval | number | 否 | 表示上报位置信息的时间间隔。 |
| distanceInterval | number | 否 | 表示上报位置信息的距离间隔。 |
| maxAccuracy | number | 否 | 表示精度信息。 |
## CurrentLocationRequest
当前位置信息请求类型。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 |
| scenario | [LocationRequestScenario](#locationrequestscenario) | 否 | 表示场景信息。 |
| maxAccuracy | number | 否 | 表示精度信息,单位是米。 |
| timeoutMs | number | 否 | 表示超时时间,单位是毫秒,最小为1000毫秒。 |
## SatelliteStatusInfo
卫星状态信息。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| satellitesNumber | number | 是 | 表示卫星个数。 |
| satelliteIds | Array&lt;number&gt; | 是 | 表示每个卫星的ID,数组类型。 |
| carrierToNoiseDensitys | Array&lt;number&gt; | 是 | 表示载波噪声功率谱密度比,即cn0。 |
| altitudes | Array&lt;number&gt; | 是 | 表示高程信息。 |
| azimuths | Array&lt;number&gt; | 是 | 表示方位角。 |
| carrierFrequencies | Array&lt;number&gt; | 是 | 表示载波频率。 |
## CachedGnssLocationsRequest
请求订阅GNSS缓存位置上报功能接口的配置参数。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| reportingPeriodSec | number | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 |
| wakeUpCacheQueueFull | boolean | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。<br/>false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 |
## Geofence
GNSS围栏的配置参数。目前只支持圆形围栏。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| latitude | number | 是 | 表示纬度。 |
| longitude | number | 是 | 表示经度。 |
| radius | number | 是 | 表示圆形围栏的半径。 |
| expiration | number | 是 | 围栏存活的时间,单位是毫秒。 |
## GeofenceRequest
请求添加GNSS围栏消息中携带的参数,包括定位优先级、定位场景和围栏信息。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| priority | LocationRequestPriority | 是 | 表示位置信息优先级。 |
| scenario | LocationRequestScenario | 是 | 表示定位场景。 |
| geofence | Geofence | 是 | 表示围栏信息。 |
## LocationPrivacyType
定位服务隐私协议类型。
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| OTHERS | 0 | 其他场景。 |
| STARTUP | 1 | 开机向导场景下的隐私协议。 |
| CORE_LOCATION | 2 | 开启网络定位时弹出的隐私协议。 |
## LocationCommand
扩展命令结构体。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| scenario | LocationRequestScenario | 是 | 表示定位场景。 |
| command | string | 是 | 扩展命令字符串。 |
## Location
位置信息类型。
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 |
| longitude | number | 是 | 表示经度信息,正值表示东经,负值表是西经。 |
| altitude | number | 是 | 表示高度信息,单位米。 |
| accuracy | number | 是 | 表示精度信息,单位米。 |
| speed | number | 是 | 表示速度信息,单位米每秒。 |
| timeStamp | number | 是 | 表示位置时间戳,UTC格式。 |
| direction | number | 是 | 表示航向信息。 |
| timeSinceBoot | number | 是 | 表示位置时间戳,开机时间格式。 |
| additions | Array&lt;string&gt; | 否 | 附加信息。 |
| additionSize | number | 否 | 附加信息数量。 |
......@@ -259,7 +259,7 @@ Codec MIME类型枚举。
## AudioPlayer
音频播放管理类,用于管理和播放音频媒体。在调用AudioPlayer的方法前,需要先通过[createAudioPlayer()](#media.createaudioplayer)构建一个[AudioPlayer](#audioplayer)实例。
音频播放管理类,用于管理和播放音频媒体。在调用AudioPlayer的方法前,需要先通过[createAudioPlayer()](#mediacreateaudioplayer)构建一个[AudioPlayer](#audioplayer)实例。
音频播放demo可参考:[音频播放开发指导](../../media/audio-playback.md)
......
# RPC通信
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```
import rpc from '@ohos.rpc';
```
## 权限列表
## MessageParcel
该类提供读写基础类型及数组、IPC对象、接口描述符和自定义序列化对象的方法。
### create
create(): MessageParcel
静态方法,创建MessageParcel对象。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| MessageParcel | 返回创建的MessageParcel对象。 |
- 示例
```
let data = rpc.MessageParcel.create();
console.log("RpcClient: data is " + data);
```
### reclaim
reclaim(): void
释放不再使用的MessageParcel对象。
- 示例
```
let reply = rpc.MessageParcel.create();
reply.reclaim();
```
### writeRemoteObject
writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean
序列化远程对象并将其写入MessageParcel对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| object | [IRemoteObject](#iremoteobject) | 是 | 要序列化并写入MessageParcel的远程对象。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let data = rpc.MessageParcel.create();
let testRemoteObject = new TestRemoteObject("testObject");
data.writeRemoteObject(testRemoteObject);
```
### readRemoteObject
readRemoteObject(): IRemoteObject
从MessageParcel读取远程对象。此方法用于反序列化MessageParcel对象以生成IRemoteObject。远程对象按写入MessageParcel的顺序读取。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| [IRemoteObject](#iremoteobject) | 读取到的远程对象。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let data = rpc.MessageParcel.create();
let testRemoteObject = new TestRemoteObject("testObject");
data.writeRemoteObject(testRemoteObject);
let proxy = data.readRemoteObject();
```
### writeInterfaceToken
writeInterfaceToken(token: string): boolean
将接口描述符写入MessageParcel对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | string | 是 | 字符串类型描述符。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeInterfaceToken("aaa");
console.log("RpcServer: writeInterfaceToken is " + result);
```
### readInterfaceToken
readInterfaceToken(): string
从MessageParcel中读取接口描述符。接口描述符按写入MessageParcel的顺序读取。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 返回读取到的接口描述符。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let interfaceToken = data.readInterfaceToken();
console.log("RpcServer: interfaceToken is " + interfaceToken);
return true;
}
}
```
### getSize
getSize(): number
获取当前MessageParcel的数据大小。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 获取的MessageParcel的数据大小。以字节为单位。 |
- 示例
```
let data = rpc.MessageParcel.create();
let size = data.getSize();
console.log("RpcClient: size is " + size);
```
### getCapacity
getCapacity(): number
获取当前MessageParcel的容量。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 获取的MessageParcel的容量大小。以字节为单位。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.getCapacity();
console.log("RpcClient: capacity is " + result);
```
### setSize
setSize(size: number): boolean
设置MessageParcel实例中包含的数据大小。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| size | number | 是 | MessageParcel实例的数据大小。以字节为单位。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 设置成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let setSize = data.setSize(16);
console.log("RpcClient: setSize is " + setSize);
```
### setCapacity
setCapacity(size: number): boolean
设置MessageParcel实例的存储容量。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| size | number | 是 | MessageParcel实例的存储容量。以字节为单位。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 设置成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.setCapacity(100);
console.log("RpcClient: setCapacity is " + result);
```
### getWritableBytes
getWritableBytes(): number
获取MessageParcel的可写字节空间。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 获取到的MessageParcel的可写字节空间。以字节为单位。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let getWritableBytes = data.getWritableBytes();
console.log("RpcServer: getWritableBytes is " + getWritableBytes);
return true;
}
}
```
### getReadableBytes
getReadableBytes(): number
获取MessageParcel的可读字节空间。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 获取到的MessageParcel的可读字节空间。以字节为单位。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let result = data.getReadableBytes();
console.log("RpcServer: getReadableBytes is " + result);
return true;
}
}
```
### getReadPosition
getReadPosition(): number
获取MessageParcel的读位置。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回MessageParcel实例中的当前读取位置。 |
- 示例
```
let data = rpc.MessageParcel.create();
let readPos = data.getReadPosition();
console.log("RpcClient: readPos is " + readPos);
```
### getWritePosition
getWritePosition(): number
获取MessageParcel的写位置。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回MessageParcel实例中的当前写入位置。 |
- 示例
```
let data = rpc.MessageParcel.create();
data.writeInt(10);
let bwPos = data.getWritePosition();
console.log("RpcClient: bwPos is " + bwPos);
```
### rewindRead
rewindRead(pos: number): boolean
重新偏移读取位置到指定的位置。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| pos | number | 是 | 开始读取数据的目标位置。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果读取位置发生更改,则返回true;否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
data.writeInt(12);
data.writeString("parcel");
let number = data.readInt();
console.log("RpcClient: number is " + number);
data.rewindRead(0);
let number2 = data.readInt();
console.log("RpcClient: rewindRead is " + number2);
```
### rewindWrite
rewindWrite(pos: number): boolean
重新偏移写位置到指定的位置。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| pos | number | 是 | 开始写入数据的目标位置。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果写入位置更改,则返回true;否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
data.writeInt(4);
data.rewindWrite(0);
data.writeInt(5);
let number = data.readInt();
console.log("RpcClient: rewindWrite is: " + number);
```
### writeByte
writeByte(val: number): boolean
将字节值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | number | 是 | 要写入的字节值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回成功,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result);
```
### readByte
readByte(): number
从MessageParcel实例读取字节值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回字节值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result);
let ret = data.readByte();
console.log("RpcClient: readByte is: " + ret);
```
### writeShort
writeShort(val: number): boolean
将短整数值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | number | 是 | 要写入的短整数值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result);
```
### readShort
readShort(): number
从MessageParcel实例读取短整数值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回短整数值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result);
let ret = data.readShort();
console.log("RpcClient: readShort is: " + ret);
```
### writeInt
writeInt(val: number): boolean
将整数值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | number | 是 | 要写入的整数值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回成功,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result);
```
### readInt
readInt(): number
从MessageParcel实例读取整数值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回整数值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result);
let ret = data.readInt();
console.log("RpcClient: readInt is " + ret);
```
### writeLong
writeLong(val: number): boolean
将长整数值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | number | 是 | 要写入的长整数值 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result);
```
### readLong
readLong(): number
从MessageParcel实例中读取长整数值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回长整数值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result);
let ret = data.readlong();
console.log("RpcClient: readLong is " + ret);
```
### writeFloat
writeFloat(val: number): boolean
将浮点值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | number | 是 | 要写入的浮点值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result);
```
### readFloat
readFloat(): number
从MessageParcel实例中读取浮点值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回浮点值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result);
let ret = data.readFloat();
console.log("RpcClient: readFloat is " + ret);
```
### writeDouble
writeDouble(val: number): boolean
将双精度浮点值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | number | 是 | 要写入的双精度浮点值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result);
```
### readDouble
readDouble(): number
从MessageParcel实例读取双精度浮点值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回双精度浮点值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result);
let ret = data.readDouble();
console.log("RpcClient: readDouble is " + ret);
```
### writeBoolean
writeBoolean(val: boolean): boolean
将布尔值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | boolean | 是 | 要写入的布尔值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result);
```
### readBoolean
readBoolean(): boolean
从MessageParcel实例读取布尔值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 返回读取到的布尔值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result);
let ret = data.readBoolean();
console.log("RpcClient: readBoolean is " + ret);
```
### writeChar
writeChar(val: number): boolean
将单个字符值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | number | 是 | 要写入的单个字符值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeChar('a');
console.log("RpcClient: writeChar is " + result);
```
### readChar
readChar(): number
从MessageParcel实例中读取单个字符值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回单个字符值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeChar('a');
console.log("RpcClient: writeChar is " + result);
let ret = data.readChar();
console.log("RpcClient: readChar is " + ret);
```
### writeString
writeString(val: string): boolean
将字符串值写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | string | 是 | 要写入的字符串值。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result);
```
### readString
readString(): string
从MessageParcel实例读取字符串值。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 返回字符串值。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result);
let ret = data.readString();
console.log("RpcClient: readString is " + ret);
```
### writeSequenceable
writeSequenceable(val: Sequenceable): boolean
将自定义序列化对象写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| val | [Sequenceable](#sequenceable) | 是 | 要写入的可序列对象。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
```
### readSequenceable
readSequenceable(dataIn: Sequenceable) : boolean
从MessageParcel实例中读取成员变量到指定的对象(dataIn)。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | [Sequenceable](#sequenceable) | 是 | 需要从MessageParcel读取成员变量的对象。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果反序列成功,则返回true;否则返回false。 |
- 示例
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
let ret = new MySequenceable(0, "");
let result2 = data.readSequenceable(ret);
console.log("RpcClient: writeSequenceable is " + result2);
```
### writeByteArray
writeByteArray(byteArray: number[]): boolean
将字节数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| byteArray | number[] | 是 | 要写入的字节数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result);
```
### readByteArray
readByteArray(dataIn: number[]) : void
从MessageParcel实例读取字节数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | 是 | 要读取的字节数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result);
let array = new Array(5);
data.readByteArray(array);
```
### readByteArray
readByteArray(): number[]
从MessageParcel实例中读取字节数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回字节数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result);
let array = data.readByteArray();
console.log("RpcClient: readByteArray is " + array);
```
### writeShortArray
writeShortArray(shortArray: number[]): boolean
将短整数数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| shortArray | number[] | 是 | 要写入的短整数数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
```
### readShortArray
readShortArray(dataIn: number[]) : void
从MessageParcel实例中读取短整数数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | 是 | 要读取的短整数数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
let array = new Array(3);
data.readShortArray(array);
```
### readShortArray
readShortArray(): number[]
从MessageParcel实例中读取短整数数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回短整数数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
let array = data.readShortArray();
console.log("RpcClient: readShortArray is " + array);
```
### writeIntArray
writeIntArray(intArray: number[]): boolean
将整数数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| intArray | number[] | 是 | 要写入的整数数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
```
### readIntArray
readIntArray(dataIn: number[]) : void
从MessageParcel实例中读取整数数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | 是 | 要读取的整数数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
let array = new Array(3);
data.readIntArray(array);
```
### readIntArray
readIntArray(): number[]
从MessageParcel实例中读取整数数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回整数数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
let array = data.readIntArray();
console.log("RpcClient: readIntArray is " + array);
```
### writeLongArray
writeLongArray(longArray: number[]): boolean
将长整数数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| longArray | number[] | 是 | 要写入的长整数数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
```
### readLongArray
readLongArray(dataIn: number[]) : void
从MessageParcel实例读取长整数数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | 是 | 要读取的长整数数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
let array = new Array(3);
data.readLongArray(array);
```
### readLongArray
readLongArray(): number[]
从MessageParcel实例中读取长整数数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回长整数数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
let array = data.readLongArray();
console.log("RpcClient: readLongArray is " + array);
```
### writeFloatArray
writeFloatArray(floatArray: number[]): boolean
将浮点数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| floatArray | number[] | 是 | 要写入的浮点数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
```
### readFloatArray
readFloatArray(dataIn: number[]) : void
从MessageParcel实例中读取浮点数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | 是 | 要读取的浮点数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
let array = new Array(3);
data.readFloatArray(array);
```
### readFloatArray
readFloatArray(): number[]
从MessageParcel实例中读取浮点数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回浮点数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
let array = data.readFloatArray();
console.log("RpcClient: readFloatArray is " + array);
```
### writeDoubleArray
writeDoubleArray(doubleArray: number[]): boolean
将双精度浮点数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| doubleArray | number[] | 是 | 要写入的双精度浮点数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
```
### readDoubleArray
readDoubleArray(dataIn: number[]) : void
从MessageParcel实例中读取双精度浮点数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | number[] | 是 | 要读取的双精度浮点数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
let array = new Array(3);
data.readDoubleArray(array);
```
### readDoubleArray
readDoubleArray(): number[]
从MessageParcel实例读取双精度浮点数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回双精度浮点数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
let array = data.readDoubleArray();
console.log("RpcClient: readDoubleArray is " + array);
```
### writeBooleanArray
writeBooleanArray(booleanArray: boolean[]): boolean
将布尔数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| booleanArray | boolean[] | 是 | 要写入的布尔数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
```
### readBooleanArray
readBooleanArray(dataIn: boolean[]) : void
从MessageParcel实例中读取布尔数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | boolean[] | 是 | 要读取的布尔数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
let array = new Array(3);
data.readBooleanArray(array);
```
### readBooleanArray
readBooleanArray(): boolean[]
从MessageParcel实例中读取布尔数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean[] | 返回布尔数组。 |
```
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
let array = data.readBooleanArray();
console.log("RpcClient: readBooleanArray is " + array);
```
### writeCharArray
writeCharArray(charArray: number[]): boolean
将单个字符数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| charArray | number[] | 是 | 要写入的单个字符数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeCharArray(['a', 'b', 'c']);
console.log("RpcClient: writeCharArray is " + result);
```
### readCharArray
readCharArray(dataIn: boolean[]) : void
从MessageParcel实例中读取单个字符数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | boolean[] | 是 | 要读取的单个字符数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeCharArray(['a', 'b', 'c']);
console.log("RpcClient: writeCharArray is " + result);
let array = new Array(3);
data.readCharArray(array);
```
### readCharArray
readCharArray(): boolean[]
从MessageParcel实例读取单个字符数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean[] | 返回单个字符数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeCharArray(['a', 'b', 'c']);
console.log("RpcClient: writeCharArray is " + result);
let array = data.readCharArray();
console.log("RpcClient: readCharArray is " + array);
```
### writeStringArray
writeStringArray(stringArray: string[]): boolean
将字符串数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| stringArray | string[] | 是 | 要写入的字符串数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
```
### readStringArray
readStringArray(dataIn: string[]) : void
从MessageParcel实例读取字符串数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | string[] | 是 | 要读取的字符串数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
let array = new Array(2);
data.readStringArray(array);
```
### readStringArray
readStringArray(): string[]
从MessageParcel实例读取字符串数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string[] | 返回字符串数组。 |
- 示例
```
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
let array = data.readStringArray();
console.log("RpcClient: readStringArray is " + array);
```
### writeNoException<sup>8+</sup>
writeNoException(): void
向MessageParcel写入“指示未发生异常”的信息。
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
onRemoteRequest(code, data, reply, option) {
if (code === 1) {
console.log("RpcServer: onRemoteRequest called");
reply.writeNoException();
return true;
} else {
console.log("RpcServer: unknown code: " + code);
return false;
}
}
}
```
### readException<sup>8+</sup>
readException(): void
从MessageParcel中读取异常。
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option)
.then(function(errCode) {
if (errCode === 0) {
console.log("sendRequest got result");
reply.readException();
let msg = reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
### writeSequenceableArray
writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean
将可序列化对象数组写入MessageParcel实例。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| sequenceableArray | Sequenceable[] | 是 | 要写入的可序列化对象数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 写入成功返回true,否则返回false。 |
- 示例
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let sequenceable2 = new MySequenceable(2, "bbb");
let sequenceable3 = new MySequenceable(3, "ccc");
let a = [sequenceable, sequenceable2, sequenceable3];
let data = rpc.MessageParcel.create();
let result = data.writeSequenceableArray(a);
console.log("RpcClient: writeSequenceableArray is " + result);
```
### readSequenceableArray<sup>8+</sup>
readSequenceableArray(sequenceableArray: Sequenceable[]): void
从MessageParcel实例读取可序列化对象数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| sequenceableArray | Sequenceable[] | 是 | 要读取的可序列化对象数组。 |
- 示例
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let sequenceable2 = new MySequenceable(2, "bbb");
let sequenceable3 = new MySequenceable(3, "ccc");
let a = [sequenceable, sequenceable2, sequenceable3];
let data = rpc.MessageParcel.create();
let result = data.writeSequenceableArray(a);
console.log("RpcClient: writeSequenceableArray is " + result);
let b = [new MySequenceable(0, ""), new MySequenceable(0, ""), new MySequenceable(0, "")];
data.readSequenceableArray(b);
```
### writeRemoteObjectArray<sup>8+</sup>
writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean
将IRemoteObject对象数组写入MessageParcel。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| objectArray | IRemoteObject[] | 是 | 要写入MessageParcel的IRemoteObject对象数组。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果IRemoteObject对象数组成功写入MessageParcel,则返回true;如果对象为null或数组写入MessageParcel失败,则返回false。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")];
let data = rpc.MessageParcel.create();
let result = data.writeRemoteObjectArray(a);
console.log("RpcClient: writeRemoteObjectArray is " + result);
```
### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(objects: IRemoteObject[]): void
从MessageParcel读取IRemoteObject对象数组。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| objects | IRemoteObject[] | 是 | 从MessageParcel读取的IRemoteObject对象数组。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")];
let data = rpc.MessageParcel.create();
let result = data.writeRemoteObjectArray(a);
let b = new Array(3);
data.readRemoteObjectArray(b);
```
### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(): IRemoteObject[]
从MessageParcel读取IRemoteObject对象数组。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| IRemoteObject[] | 返回IRemoteObject对象数组。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")];
let data = rpc.MessageParcel.create();
let result = data.writeRemoteObjectArray(a);
console.log("RpcClient: readRemoteObjectArray is " + result);
let b = data.readRemoteObjectArray();
console.log("RpcClient: readRemoteObjectArray is " + b);
```
### closeFileDescriptor<sup>8+</sup>
static closeFileDescriptor(fd: number): void
关闭给定的文件描述符。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fd | number | 是 | 要关闭的文件描述符。 |
- 示例
```
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
rpc.MessageParcel.closeFileDescriptor(fd);
```
### dupFileDescriptor<sup>8+</sup>
static dupFileDescriptor(fd: number) :number
复制给定的文件描述符。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fd | number | 是 | 表示已存在的文件描述符。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回新的文件描述符。 |
- 示例
```
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let newFd = rpc.MessageParcel.dupFileDescriptor(fd);
```
### containFileDescriptors<sup>8+</sup>
containFileDescriptors(): boolean
检查此MessageParcel对象是否包含文件描述符。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果此MessageParcel对象包含文件描述符,则返回true;否则返回false。 |
- 示例
```
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let r1 = parcel.containFileDescriptors();
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
console.log("RpcTest: parcel writeFd result is : " + writeResult);
let containFD = parcel.containFileDescriptors();
console.log("RpcTest: parcel after write fd containFd result is : " + containFD);
```
### writeFileDescriptor<sup>8+</sup>
writeFileDescriptor(fd: number): boolean
写入文件描述符到MessageParcel。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fd | number | 是 | 文件描述符。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
- 示例
```
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
console.log("RpcTest: parcel writeFd result is : " + writeResult);
```
### readFileDescriptor<sup>8+</sup>
readFileDescriptor(): number
从MessageParcel中读取文件描述符。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回文件描述符。 |
- 示例
```
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
let readFD = parcel.readFileDescriptor();
console.log("RpcTest: parcel read fd is : " + readFD);
```
### writeAshmem<sup>8+</sup>
writeAshmem(ashmem: Ashmem): boolean
将指定的匿名共享对象写入此MessageParcel。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ashmem | Ashmem | 是 | 要写入MessageParcel的匿名共享对象。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果匿名共享对象成功写入此MessageParcel,则返回true;否则返回false。 |
- 示例
```
let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem);
console.log("RpcTest: write ashmem to result is : " + isWriteSuccess);
```
### readAshmem<sup>8+</sup>
readAshmem(): Ashmem
从MessageParcel读取匿名共享对象。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| Ashmem | 返回匿名共享对象。 |
- 示例
```
let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem);
console.log("RpcTest: write ashmem to result is : " + isWriteSuccess);
let readAshmem = parcel.readAshmem();
console.log("RpcTest: read ashmem to result is : " + readAshmem);
```
### getRawDataCapacity<sup>8+</sup>
getRawDataCapacity(): number
获取MessageParcel可以容纳的最大原始数据量。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回MessageParcel可以容纳的最大原始数据量,即128&nbsp;Mb。 |
- 示例
```
let parcel = new rpc.MessageParcel();
let result = parcel.getRawDataCapacity();
console.log("RpcTest: parcel get RawDataCapacity result is : " + result);
```
### writeRawData<sup>8+</sup>
writeRawData(rawData: number[], size: number): boolean
将原始数据写入MessageParcel对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| rawData | number[] | 是 | 要写入的原始数据。 |
| size | number | 是 | 发送的原始数据大小,以字节为单位。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
- 示例
```
let parcel = new rpc.MessageParcel();
let arr = new Int8Array([1, 2, 3, 4, 5]);
let isWriteSuccess = parcel.writeRawData(arr, arr.length);
console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess);
```
### readRawData<sup>8+</sup>
readRawData(size: number): number[]
从MessageParcel读取原始数据。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| size | number | 是 | 要读取的原始数据的大小。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回原始数据(以字节为单位)。 |
- 示例
```
let parcel = new rpc.MessageParcel();
let arr = new Int8Array([1, 2, 3, 4, 5]);
let isWriteSuccess = parcel.writeRawData(arr, arr.length);
console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess);
let result = parcel.readRawData(5);
console.log("RpcTest: parcel read raw data result is : " + result);
```
### getDataVersion<sup>8+</sup>
getDataVersion(): number
从MessageParcel对象返回数据格式版本。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 从MessageParcel返回数据格式版本。 |
- 示例
```
let parcel = new rpc.MessageParcel();
let version = parcel.getDataVersion();
console.log("RpcTest: parcel get data version is : " + version);
```
### updateDataVersion<sup>8+</sup>
updateDataVersion(proxy: IRemoteObject): void
将远程对象数据格式版本更新到MessageParcel对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| proxy | IRemoteObject | 是 | 使用该MessageParcel对象发送请求的远程对象。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let parcel = new rpc.MessageParcel();
parcel.updateDataVersion(proxy);
```
## Sequenceable
在进程间通信(IPC)期间,将类的对象写入MessageParcel并从MessageParcel中恢复它们。
### marshalling
marshalling(dataOut: MessageParcel): boolean
将此可序列对象封送到MessageParcel中。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataOut | [MessageParcel](#messageparcel) | 是 | 可序列对象将被封送到的MessageParcel对象。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果封送成功,则返回true;否则返回false。 |
- 示例
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
let ret = new MySequenceable(0, "");
let result2 = data.readSequenceable(ret);
console.log("RpcClient: readSequenceable is " + result2);
```
### unmarshalling
unmarshalling(dataIn: MessageParcel) : boolean
从MessageParcel中解封此可序列对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataIn | [MessageParcel](#messageparcel) | 是 | 已将可序列对象封送到其中的MessageParcel对象。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果可序列化成功,则返回true;否则返回false。 |
- 示例
```
class MySequenceable {
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
return true;
}
}
let sequenceable = new MySequenceable(1, "aaa");
let data = rpc.MessageParcel.create();
let result = data.writeSequenceable(sequenceable);
console.log("RpcClient: writeSequenceable is " + result);
let ret = new MySequenceable(0, "");
let result2 = data.readSequenceable(ret);
console.log("RpcClient: readSequenceable is " + result2);
```
## IRemoteBroker
远端对象的代理持有者。用于获取代理对象。
### asObject
asObject(): IRemoteObject
需派生类实现,获取代理或远端对象。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| [IRemoteObject](#iremoteobject) | 如果调用者是[RemoteObject](#ashmem8)对象,则直接返回本身;如果调用者是[RemoteProxy](#remoteproxy)对象,则返回它的持有者[IRemoteObject](#iremoteobject)。 |
- 示例
```
class TestAbility extends rpc.RemoteObject {
asObject() {
return this;
}
}
```
- 示例
```
class TestProxy {
constructor(remote) {
this.remote = remote;
}
asObject() {
return this.remote;
}
}
```
## DeathRecipient
用于订阅远端对象的死亡通知。当被订阅该通知的远端对象死亡时,本端可收到消息,调用[onRemoteDied](#onremotedied)接口。远端对象死亡可以为远端对象所在进程死亡,远端对象所在设备关机或重启,当远端对象与本端对象属于不同设备时,也可为远端对象离开组网时。
### onRemoteDied
onRemoteDied(): void
在成功添加死亡通知订阅后,当远端对象死亡时,将自动调用本方法。
- 示例
```
class MyDeathRecipient {
onRemoteDied() {
console.log("server is died");
}
}
```
## SendRequestResult<sup>8+</sup>
发送请求的响应结果。
| 参数 | 值 | 说明 |
| -------- | -------- | -------- |
| errCode | number | 错误码。 |
| code | number | 消息代码。 |
| data | MessageParcel | 发送给对端进程的MessageParcel对象。 |
| reply | MessageParcel | 对端进程返回的MessageParcel对象。 |
## IRemoteObject
该接口可用于查询或获取接口描述符、添加或删除死亡通知、转储对象状态到特定文件、发送消息。
### queryLocalInterface
queryLocalInterface(descriptor: string): IRemoteBroker
查询接口。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| descriptor | string | 是 | 接口描述符的字符串。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| IRemoteBroker | 返回绑定到指定接口描述符的IRemoteBroker对象。 |
### sendRequest
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;number&gt;<sup>7</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;<sup>8+</sup>
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 |
| data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的&nbsp;MessageParcel对象。 |
| reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 |
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;number&gt;<sup>7</sup><br/>Promise&lt;SendRequestResult&gt;<sup>8+</sup> | 返回一个期约,兑现值是sendRequest错误码。0表示成功,其他情况表示失败。<sup>7</sup><br/>返回一个期约,兑现值是sendRequestResult实例。<sup>8+</sup> |
### sendRequest<sup>8+</sup>
sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback&lt;SendRequestResult&gt;): void
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 |
| data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的&nbsp;MessageParcel对象。 |
| reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 |
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
| callback | AsyncCallback&lt;SendRequestResult&gt; | 是 | 接收发送结果的回调。 |
### addDeathrecipient
addDeathRecipient(recipient: DeathRecipient, flags: number): boolean
注册用于接收远程对象死亡通知的回调。如果与RemoteProxy对象匹配的远程对象进程死亡,则调用此方法。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | 是 | 要注册的回调。 |
| flags | number | 是 | 死亡通知标志。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果回调注册成功,则返回true;否则返回false。 |
### removeDeathRecipient
removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean
注销用于接收远程对象死亡通知的回调。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | 是 | 要注销的回调。 |
| flags | number | 是 | 死亡通知标志。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果回调成功注销,则返回true;否则返回false。 |
### getInterfaceDescriptor
getInterfaceDescriptor(): string
获取对象的接口描述符。接口描述符为字符串。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 返回接口描述符。 |
### isObjectDead
isObjectDead(): boolean
检查当前对象是否死亡。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果对象已死亡,则返回true;否则返回false。 |
## RemoteProxy
实现IRemoteObject代理对象。
### sendRequest
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;number&gt;<sup>7</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;<sup>8+</sup>
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 |
| data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的&nbsp;MessageParcel对象。 |
| reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 |
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;number&gt;<sup>7</sup><br/>Promise&lt;SendRequestResult&gt;<sup>8+</sup> | 返回一个期约,兑现值是sendRequest错误码。0表示成功,其他情况表示失败。<sup>7</sup><br/>返回一个期约,兑现值是sendRequestResult实例。<sup>8+</sup> |
- 示例<sup>7</sup>
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option)
.then(function(errCode) {
if (errCode === 0) {
console.log("sendRequest got result");
let msg = reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
- 示例<sup>8+</sup>
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option)
.then(function(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
### sendRequest<sup>8+</sup>
sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback&lt;SendRequestResult&gt;): void
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 |
| data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的&nbsp;MessageParcel对象。 |
| reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 |
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
| callback | AsyncCallback&lt;SendRequestResult&gt; | 是 | 接收发送结果的回调。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
function sendRequestCallback(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
console.log("RPCTest: sendRequest ends, reclaim parcel");
result.data.reclaim();
result.reply.reclaim();
}
FA.connectAbility(want, connect);
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
proxy.sendRequest(1, data, reply, option, sendRequestCallback);
```
### queryLocalInterface
queryLocalInterface(interface: string): IRemoteBroker
查询并获取当前接口描述符对应的本地接口对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| interface | string | 是 | 需要查询的接口描述符。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| IRemoteBroker | 默认返回Null,标识该接口是一个代理侧接口。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function (elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName":"com.huawei.server",
"abilityName":"com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let broker = proxy.queryLocalInterface("testObject");
console.log("RpcClient: queryLocalInterface is " + broker);
```
### addDeathRecippient
addDeathRecipient(recipient : DeathRecipient, flags : number): boolean
注册用于接收远程对象死亡通知的回调,增加proxy对象上的死亡通知。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | 是 | 收件人表示要注册的回调。 |
| flags | number | 是 | 死亡通知标志。保留参数。设置为0。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果回调注册成功,则返回true;否则返回false。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
class MyDeathRecipient {
onRemoteDied() {
console.log("server is died");
}
}
let deathRecipient = new MyDeathRecipient();
proxy.addDeathRecippient(deathRecipient, 0);
```
### removeDeathRecipient
removeDeathRecipient(recipient : DeathRecipient, flags : number): boolean
注销用于接收远程对象死亡通知的回调。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| recipient | [DeathRecipient](#deathrecipient) | 是 | 要注销的死亡回调。 |
| flags | number | 是 | 死亡通知标志。保留参数。设置为0。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果回调成功注销,则返回true;否则返回false。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
class MyDeathRecipient {
onRemoteDied() {
console.log("server is died");
}
}
let deathRecipient = new MyDeathRecipient();
proxy.addDeathRecippient(deathRecipient, 0);
proxy.removeDeathRecipient(deathRecipient, 0);
```
### getInterfaceDescriptor
getInterfaceDescriptor(): string
查询当前代理对象接口的描述符。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 当前的接口描述符。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let descriptor = proxy.getInterfaceDescriptor();
console.log("RpcClient: descriptor is " + descriptor);
```
### isObjectDead
isObjectDead(): boolean
指示对应的RemoteObject是否死亡。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果对应的RemoteObject已经死亡,返回true,否则返回false。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let isDead = proxy.isObjectDead();
console.log("RpcClient: isObjectDead is " + isDead);
```
### setDataVersion<sup>8+</sup>
setDataVersion(dataVersion: number): boolean
将数据格式版本设置到RemoteProxy对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataVersion | number | 是 | 数据格式版本。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果设置数据格式版本成功,则返回true;否则返回false。 |
- 示例
```
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.huawei.server",
"abilityName": "com.huawei.server.MainAbility",
};
FA.connectAbility(want, connect);
let result = proxy.setDataVersion(1);
console.log("RpcClient: set Data Version is " + result);
```
## MessageOption
公共消息选项(int标志,int等待时间),使用标志中指定的标志构造指定的MessageOption对象。
| 参数 | 值 | 说明 |
| -------- | -------- | -------- |
| TF_SYNC | 0 | 同步调用。 |
| TF_ASYNC | 1 | 异步调用。 |
| TF_ACCEPT_FDS | 0x10 | 指示[sendRequest](#sendrequest8)接口可以返回文件描述符。 |
| TF_WAIT_TIME | 8 | 等待时间。单位秒。 |
### constructor
constructor(syncFlags?: number, waitTime = TF_WAIT_TIME)
MessageOption构造函数。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| syncFlags | number | 否 | 同步调用或异步调用标志。默认同步调用。 |
| waitTime | number | 否 | 调用rpc最长等待时间。默认&nbsp;TF_WAIT_TIME。 |
### getFlags
getFlags(): number
获取同步调用或异步调用标志。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 调用成功返回同步调用或异步调用标志。 |
### setFlags
setFlags(flags: number): void
设置同步调用或异步调用标志。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| flags | number | 是 | 同步调用或异步调用标志。 |
### getWaitTime
getWaitTime(): number
获取rpc调用的最长等待时间。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | rpc最长等待时间。 |
### setWaitTime
setWaitTime(waitTime: number): void
设置rpc调用最长等待时间。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| waitTime | number | 是 | rpc调用最长等待时间。 |
## IPCSkeleton
用于获取IPC上下文信息,包括获取UID和PID、获取本端和对端设备ID、检查接口调用是否在同一设备上。
### getContextObject
static getContextObject(): IRemoteObject
获取系统能力的管理者。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| [IRemoteObject](#iremoteobject) | 返回系统能力管理者。 |
- 示例
```
let samgr = rpc.IPCSkeleton.getContextObject();
console.log("RpcServer: getContextObject result: " + samgr);
```
### getCallingPid
static getCallingPid(): number
获取调用者的PID。此方法由RemoteObject对象在onRemoteRequest方法中调用,不在IPC上下文环境(onRemoteRequest)中调用则返回本进程的PID。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回调用者的PID。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callerPid = rpc.IPCSkeleton.getCallingPid();
console.log("RpcServer: getCallingPid result: " + callerPid);
return true;
}
}
```
### getCallingUid
static getCallingUid(): number
获取调用者的UID。此方法由RemoteObject对象在onRemoteRequest方法中调用,不在IPC上下文环境(onRemoteRequest)中调用则返回本进程的UID。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回调用者的UID。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callerUid = rpc.IPCSkeleton.getCallingUid();
console.log("RpcServer: getCallingUid result: " + callerUid);
return true;
}
}
```
### getCalligDeviceID
static getCallingDeviceID(): string
获取调用者进程所在的设备ID。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 返回调用者进程所在的设备ID。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callerDeviceID = rpc.IPCSkeleton.getCalligDeviceID();
console.log("RpcServer: callerDeviceID is: " + callerDeviceID);
return true;
}
}
```
### getLocalDeviceID
static getLocalDeviceID(): string
获取本端设备ID。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 返回本地设备的ID。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID();
console.log("RpcServer: localDeviceID is: " + localDeviceID);
return true;
}
}
```
### isLocalCalling
static isLocalCalling(): boolean
检查当前通信对端是否是本设备的进程。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果调用是在同一设备上进行的,则返回true,否则返回false。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let isLocalCalling = rpc.IPCSkeleton.isLocalCalling();
console.log("RpcServer: isLocalCalling is: " + isLocalCalling);
return true;
}
}
```
### flushCommands
static flushCommands(object : IRemoteObject): number
将所有挂起的命令从指定的RemoteProxy刷新到相应的RemoteObject。建议在执行任何时间敏感操作之前调用此方法。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| object | [IRemoteObject](#iremoteobject) | 是 | 指定的RemoteProxy。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 如果操作成功,返回0;如果输入对象为空或RemoteObject,或者操作失败,返回错误代码。 |
- 示例
```
let remoteObject = new rpc.RemoteObject("aaa", 3);
let ret = rpc.IPCSkeleton.flushCommands(remoteObject);
console.log("RpcServer: flushCommands result: " + ret);
```
### resetCallingIdentity
static resetCallingIdentity(): string
将远程用户的UID和PID替换为本地用户的UID和PID。它可以用于身份验证等场景。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 返回包含远程用户的UID和PID的字符串。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity();
console.log("RpcServer: callingIdentity is: " + callingIdentity);
return true;
}
}
```
### setCallingIdentity
static setCallingIdentity(identity : string): boolean
将UID和PID恢复为远程用户的UID和PID。它通常在使用resetCallingIdentity后调用,需要resetCallingIdentity返回的远程用户的UID和PID。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| identity | string | 是 | 标识表示包含远程用户UID和PID的字符串。由resetCallingIdentity返回。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
- 示例
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let callingIdentity = null;
try {
callingIdentity = rpc.IPCSkeleton.resetCallingIdentity();
console.log("RpcServer: callingIdentity is: " + callingIdentity);
} finally {
let ret = rpc.IPCSkeleton.setCallingIdentity("callingIdentity ");
console.log("RpcServer: setCallingIdentity is: " + ret);
}
return true;
}
}
```
## RemoteObject
实现远程对象。服务提供者必须继承此类。
### constructor
constructor(descriptor: string)
RemoteObject构造函数。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| descriptor | string | 是 | 接口描述符。 |
### sendRequest
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;number&gt;<sup>7</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;<sup>8+</sup>
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 |
| data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的&nbsp;MessageParcel对象。 |
| reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 |
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;number&gt;<sup>7</sup><br/>Promise&lt;SendRequestResult&gt;<sup>8+</sup> | 返回一个期约,兑现值是sendRequest错误码。0表示成功,其他情况表示失败。<sup>7</sup><br/>返回一个期约,兑现值是sendRequestResult实例。<sup>8+</sup> |
- 示例<sup>7</sup>
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
testRemoteObject.sendRequest(1, data, reply, option)
.then(function(errCode) {
if (errCode === 0) {
console.log("sendRequest got result");
let msg = reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
- 示例<sup>8+</sup>
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
testRemoteObject.sendRequest(1, data, reply, option)
.then(function(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
}).catch(function(e) {
console.log("RPCTest: sendRequest got exception: " + e.message);
}).finally (() => {
console.log("RPCTest: sendRequest ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
```
### sendRequest<sup>8+</sup>
sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback&lt;SendRequestResult&gt;): void
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则立即收到回调,reply报文里没有内容。如果为选项设置了同步模式,则将在sendRequest返回时收到回调,回复内容在reply报文里。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 |
| data | [MessageParcel](#messageparcel) | 是 | 保存待发送数据的&nbsp;MessageParcel对象。 |
| reply | [MessageParcel](#messageparcel) | 是 | 接收应答数据的MessageParcel对象。 |
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
| AsyncCallback | AsyncCallback&lt;SendRequestResult&gt; | 是 | 接收发送结果的回调。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
function sendRequestCallback(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
let msg = result.reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
console.log("RPCTest: sendRequest failed, errCode: " + result.errCode);
}
console.log("RPCTest: sendRequest ends, reclaim parcel");
result.data.reclaim();
result.reply.reclaim();
}
let testRemoteObject = new TestRemoteObject("testObject");
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
testRemoteObject.sendRequest(1, data, reply, option, sendRequestCallback);
```
### onRemoteRequest
onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean
sendRequest请求的响应处理函数,服务端在该函数里处理请求,回复结果。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 对端发送的服务请求码。 |
| data | [MessageParcel](#messageparcel) | 是 | 携带客户端调用参数的MessageParcel对象。 |
| reply | [MessageParcel](#messageparcel) | 是 | 写入结果的MessageParcel对象。 |
| option | [MessageOption](#messageoption) | 是 | 指示操作是同步还是异步。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
onRemoteRequest(code, data, reply, option) {
if (code === 1) {
console.log("RpcServer: onRemoteRequest called");
return true;
} else {
console.log("RpcServer: unknown code: " + code);
return false;
}
}
}
```
### getCallingUid
getCallingUid(): number
获取通信对端的进程Uid。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回通信对端的进程Uid。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
console.log("RpcServer: getCallingUid: " + testRemoteObject.getCallingUid());
```
### getCallingPid
getCallingPid(): number
获取通信对端的进程Pid。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回通信对端的进程Pid。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
console.log("RpcServer: getCallingPid: " + testRemoteObject.getCallingPid());
```
### queryLocalInterface
queryLocalInterface(descriptor: descriptor): IRemoteBroker
查询并获取当前接口描述符对应的远端对象是否已经存在。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| descriptor | descriptor | 是 | 需要查询的接口描述符。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| IRemoteBroker | 如果接口描述符对应的远端对象存在,则返回该远端对象,否则返回Null。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let broker = testRemoteObject.queryLocalInterface("testObject");
```
### getInterfaceDescriptor
getInterfaceDescriptor(): string
查询接口描述符。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| string | 返回接口描述符。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
let descriptor = testRemoteObject.getInterfaceDescriptor();
console.log("RpcServer: descriptor is: " + descriptor);
```
### attachLocalInterface
attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
此接口用于把接口描述符和IRemoteBroker对象绑定。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| localInterface | IRemoteBroker | 是 | 将与描述符绑定的IRemoteBroker对象。 |
| descriptor | string | 是 | 用于与IRemoteBroker对象绑定的描述符。 |
- 示例
```
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
this.attachLocalInterface(this, descriptor);
}
}
let testRemoteObject = new TestRemoteObject("testObject");
```
## Ashmem<sup>8+</sup>
提供与匿名共享内存对象相关的方法,包括创建、关闭、映射和取消映射Ashmem、从Ashmem读取数据和写入数据、获取Ashmem大小、设置Ashmem保护。
映射内存保护类型:
| 参数名 | 值 | 说明 |
| -------- | -------- | -------- |
| PROT_EXEC | 4 | 映射的内存可执行 |
| PROT_NONE | 0 | 映射的内存不可访问 |
| PROT_READ | 1 | 映射的内存可读 |
| PROT_WRITE | 2 | 映射的内存可写 |
### createAshmem
static createAshmem(name: string, size: number): Ashmem
根据指定的名称和大小创建Ashmem对象。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| name | string | 是 | 名称,用于查询Ashmem信息。 |
| size | number | 是 | Ashmem的大小,以字节为单位。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| Ashmem | 返回创建的Ashmem对象;如果创建失败,返回null。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmem : " + ashmem + " size is : " + size);
```
### createAshmemFromExisting
static createAshmemFromExisting(ashmem: Ashmem): Ashmem
通过复制现有Ashmem对象的文件描述符(fd)来创建Ashmem对象。两个Ashmem对象指向同一个共享内存区域。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ashmem | Ashmem | 是 | 已存在的Ashmem对象。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| Ashmem | 返回创建的Ashmem对象。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let ashmem2 = rpc.Ashmem.createAshmemFromExisting(ashmem);
let size = ashmem2.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmemFromExisting : " + ashmem2 + " size is : " + size);
```
### closeAshmem
closeAshmem(): void
关闭这个Ashmem。
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
ashmem.closeAshmem();
```
### unmapAshmem
unmapAshmem(): void
删除该Ashmem对象的地址映射。
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
ashmem.unmapAshmem();
```
### getAshmemSize
getAshmemSize(): number
获取Ashmem对象的内存大小。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number | 返回Ashmem对象的内存大小。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashmem is " + ashmem + " size is : " + size);
```
### mapAshmem
mapAshmem(mapType: number): boolean
在此进程的虚拟地址空间上创建共享文件映射,映射区域大小由此Ashmem对象指定。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| mapType | number | 是 | 指定映射的内存区域的保护等级。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果映射成功,则返回true;否则返回false。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapReadAndWrite = ashmem.mapAshmem(rpc.Ashmem.PROT_READ | rpc.Ashmem.PROT_WRITE);
console.log("RpcTest: map ashmem result is : " + mapReadAndWrite);
```
### mapReadAndWriteAshmem
mapReadAndWriteAshmem(): boolean
在此进程虚拟地址空间上创建可读写的共享文件映射。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果映射成功,则返回true;否则返回false。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem();
console.log("RpcTest: map ashmem result is : " + mapResult);
```
### mapReadOnlyAshmem
mapReadOnlyAshmem(): boolean
在此进程虚拟地址空间上创建只读的共享文件映射。
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果映射成功,则返回true;否则返回false。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadOnlyAshmem();
console.log("RpcTest: Ashmem mapReadOnlyAshmem result is : " + mapResult);
```
### setProtection
setProtection(protectionType: number): boolean
设置映射内存区域的保护等级。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| protectionType | number | 是 | 要设置的保护类型。 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果设置成功,则返回true;否则返回false。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let result = ashmem.setProtection(rpc.Ashmem.PROT_READ);
console.log("RpcTest: Ashmem setProtection result is : " + result);
```
### writeToAshmem
writeToAshmem(buf: number[], size: number, offset: number): boolean
将数据写入此Ashmem对象关联的共享文件。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| buf | number[] | 是 | 写入Ashmem对象的数据。 |
| size | number | 是 | 要写入的数据大小。 |
| offset | number | 是 | 要写入的数据在此Ashmem对象关联的内存区间的起始位置 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果数据写入成功,则返回true;在其他情况下,如数据写入越界或未获得写入权限,则返回false。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0);
console.log("RpcTest: write to Ashmem result is : " + writeResult);
```
### readFromAshmem
readFromAshmem(size: number, offset: number): number[]
从此Ashmem对象关联的共享文件中读取数据。
- 参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| size | number | 是 | 要读取的数据的大小。 |
| offset | number | 是 | 要读取的数据在此Ashmem对象关联的内存区间的起始位置 |
- 返回值
| 类型 | 说明 |
| -------- | -------- |
| number[] | 返回读取的数据。 |
- 示例
```
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
var ByteArrayVar = new Int8Array([1, 2, 3, 4, 5]);
let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0);
console.log("RpcTest: write to Ashmem result is : " + writeResult);
let readResult = ashmem.readFromAshmem(5, 0);
console.log("RpcTest: read to Ashmem result is : " + readResult);
```
......@@ -57,7 +57,7 @@
| [shadowColor](#shadowcolor) | &lt;color&gt; | - | 设置绘制阴影时的阴影颜色。 |
| [shadowOffsetX](#shadowoffsetx) | number | - | 设置绘制阴影时和原有对象的水平偏移值。 |
| [shadowOffsetY](#shadowoffsety) | number | - | 设置绘制阴影时和原有对象的垂直偏移值。 |
| [imageSmoothingEnabled](#imagesmoothingenabled6-)<sup>6+</sup> | boolean | true | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。 |
| [imageSmoothingEnabled](#imagesmoothingenabled6)<sup>6+</sup> | boolean | true | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。 |
### fillStyle
......
# USB服务
- [USB服务开发概述](usb-overview.md)
- [USB服务开发指导](usb-guidelines.md)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册