提交 b523f2d8 编写于 作者: Z z00524957

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

......@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share
|query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.|
For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md).
For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md).
**Table 2** APIs of the data consumer
......@@ -34,11 +34,49 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### Data Provider Application Development (Only for System Applications)
1. Import dependencies.
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
- **onCreate**
Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server.
- **insert**
Inserts data. This API is called when the client requests to insert data.
- **update**
Updates data. This API is called when the client requests to update data.
- **delete**
Deletes data. This API is called when the client requests to delete data.
- **query**
Queries data. This API is called when the client requests to query data.
- **batchInsert**
Batch inserts data. This API is called when the client requests to batch insert data.
- **normalizeUri**
Converts the URI provided by the client to the URI used by the server.
- **denormalizeUri**
Converts the URI used by the server to the initial URI passed by the client.
Before implementing a **DataShare** service, you need to create a **DataShareExtensionAbility** object in the DevEco Studio project as follows:
1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **DataShareAbility**.
2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**.
3. In the **DataShareAbility.ts** file, import **DataShareExtensionAbility** and other dependencies.
```ts
import Extension from '@ohos.application.DataShareExtensionAbility';
......@@ -47,9 +85,9 @@ Examples are given below.
import dataSharePredicates from '@ohos.data.dataSharePredicates';
```
2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
4. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts
const DB_NAME = "DB00.db";
......@@ -63,20 +101,22 @@ Examples are given below.
export default class DataShareExtAbility extends Extension {
private rdbStore_;
// Override onCreate().
onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt'
result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store.
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
});
callback();
if (callback) {
callback();
}
});
}
......@@ -103,19 +143,20 @@ Examples are given below.
};
```
4. Define **DataShareExtensionAbility** in **module.json5**.
| Field| Description |
| ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
6. Define **DataShareExtensionAbility** in **module.json5**.
**module.json5 example**
| Field | Description |
| --------- | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. |
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. |
**module.json5 example**
```json
"extensionAbilities": [
"extensionAbilities": [
{
"srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts",
"name": "DataShareExtAbility",
......@@ -127,31 +168,33 @@ Examples are given below.
}
]
```
### Data Consumer Application Development
1. Import dependencies.
```ts
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
```
2. Define the URI string for communicating with the data provider.
```ts
// Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
let dseUri = ("datashare:///com.samples.datasharetest.DataShare");
```
3. Create a **DataShareHelper** instance.
```ts
let dsHelper;
let abilityContext;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
......@@ -160,7 +203,7 @@ Examples are given below.
}
}
```
4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data.
```ts
......@@ -168,7 +211,7 @@ Examples are given below.
let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*");
let valArray = ['*'];
// Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data);
......@@ -183,7 +226,6 @@ Examples are given below.
});
// Delete data.
dsHelper.delete(dseUri, predicates, (err, data) => {
console.log("dsHelper delete result: " + data);
console.log("dsHelper delete result: " + data);
});
```
......@@ -68,16 +68,16 @@ The following uses a single KV store as an example to describe the development p
grantPermission();
// Stage model
import AbilityStage from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends AbilityStage {
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let context = this.context;
}
}
function grantPermission() {
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
......@@ -86,7 +86,7 @@ The following uses a single KV store as an example to describe the development p
console.error('failed: ${error}');
});
}
grantPermission();
```
......@@ -103,9 +103,9 @@ The following uses a single KV store as an example to describe the development p
let context = featureAbility.getContext();
// Obtain the context of the stage model.
import AbilityStage from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends AbilityStage{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......
......@@ -113,10 +113,10 @@ You can use the following APIs to delete a **Preferences** instance or data file
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability'
import UIAbility from '@ohos.app.ability.UIAbility'
let context = null;
let preferences = null;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -159,7 +159,7 @@ You can use the following APIs to delete a **Preferences** instance or data file
5. Store data persistently.
Use **flush()** to flush data from the **Preferences** instance to its file.
Use **preferences.flush()** to flush data from the **Preferences** instance to its file.
```js
preferences.flush();
......@@ -186,7 +186,7 @@ You can use the following APIs to delete a **Preferences** instance or data file
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Flushed data successfully."); // The observer will be called.
console.info("Flushed data successfully."); // The observer will be called.
})
})
```
......@@ -200,6 +200,6 @@ You can use the following APIs to delete a **Preferences** instance or data file
proDelete.then(() => {
console.info("Deleted data successfully.");
}).catch((err) => {
console.info("Failed to delete data. Cause: " + err);
console.info("Failed to delete data. Cause: " + err);
})
```
......@@ -4,9 +4,7 @@
- [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)
- [Location Service Development](location-guidelines.md)
- Sensor
- [Sensor Overview](sensor-overview.md)
- [Sensor Development](sensor-guidelines.md)
......
# Geocoding and Reverse Geocoding Capabilities
## When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa.
The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address.
## Available APIs
The following table describes APIs available for mutual conversion between coordinates and location information.
**Table1** APIs for geocoding and reverse geocoding
| API | Description |
| -------- | -------- |
| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. |
| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. |
## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
```
import geolocation from '@ohos.geolocation';
```
2. Query whether geocoder service is available.
- Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```
geolocation.isGeoServiceAvailable((err, data) => {
if (err) {
console.log('isGeoServiceAvailable err: ' + JSON.stringify(err));
} else {
console.log('isGeoServiceAvailable data: ' + JSON.stringify(data));
}
});
```
3. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information.
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
});
```
Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
- Call **getAddressesFromLocationName** to convert geographic description into coordinates.
```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
});
```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
# Obtaining Device Location Information
## When to Use
You can call location-related APIs in OpenHarmony to obtain the real-time location or last known location of a mobile device.
Real-time location of the device is recommended for location-sensitive services. If you want to lower power consumption when the real-time location of the device is not needed, you may consider obtaining the last known location of the device.
## Available APIs
The following table describes APIs available for obtaining device location information.
**Table 1** APIs for obtaining device location information
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Registers a listener for location changes with a location request initiated. |
| off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted. |
| on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events. |
| off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events. |
| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports. |
| off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports. |
| on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events. |
| off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events. |
| on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Registers a listener for GNSS NMEA message change events. |
| off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unregisters the listener for GNSS NMEA message change events. |
| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence. |
| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence. |
| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtains the current location. This API uses an asynchronous callback to return the result. |
| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This API uses a promise to return the result. |
| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This API uses an asynchronous callback to return the result. |
| getLastLocation() : Promise<Location> | Obtains the previous location. This API uses a promise to return the result. |
| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. |
| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This API uses a promise to return the result. |
| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result. |
| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This API uses a promise to return the result. |
| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This API uses an asynchronous callback to return the result. |
| enableLocation() : Promise<boolean> | Enables the location service. This API uses a promise to return the result. |
| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This API uses an asynchronous callback to return the result. |
| disableLocation() : Promise<boolean> | Disables the location service. This API uses a promise to return the result. |
| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This API uses an asynchronous callback to return the result. |
| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This API uses a promise to return the result. |
| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses an asynchronous callback to return the result.|
| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses a promise to return the result.|
| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This API uses an asynchronous callback to return the result.|
| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This API uses a promise to return the result. |
| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | Checks whether a user agrees with the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | Checks whether a user agrees with the privacy statement of the location service. This API uses a promise to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Sets the user confirmation status for the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Sets the user confirmation status for the privacy statement of the location service. This API uses a promise to return the result.|
## How to Develop
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md).
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below.
The system provides the following location permissions:
- ohos.permission.LOCATION
- ohos.permission.LOCATION_IN_BACKGROUND
The **ohos.permission.LOCATION** permission is a must if your application needs to access the device location information.
If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
```
import geolocation from '@ohos.geolocation';
```
3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.<br>
**Method 1:**
To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported.
```
export enum LocationRequestScenario {
UNSET = 0x300,
NAVIGATION,
TRAJECTORY_TRACKING,
CAR_HAILING,
DAILY_LIFE_SERVICE,
NO_POWER,
}
```
**Table 2** Common use cases of the location function
| Use Case | Constant | Description |
| ------------ | ------------------- | ------------------------------------------------------------ |
| Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
Sample code for initializing **requestInfo** for navigation:
```
var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
**Method 2:**
If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system.
```
export enum LocationRequestPriority {
UNSET = 0x200,
ACCURACY,
LOW_POWER,
FIRST_FIX,
}
```
**Table 3** Location priority policies
| Policy | Constant | Description |
| ------------------ | -------------- | ------------------------------------------------------------ |
| Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.<br>To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.|
Sample code for initializing **requestInfo** for the location accuracy priority policy:
```
var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
4. Instantiate the **Callback** object for the system to report location results.
Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic.
```
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
```
5. Start device location.
```
geolocation.on('locationChange', requestInfo, locationChange);
```
6. (Optional) Stop device location.
```
geolocation.off('locationChange', locationChange);
```
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```
geolocation.getLastLocation((err, data) => {
if (err) {
console.log('getLastLocation: err: ' + JSON.stringify(err));
} else {
console.log('getLastLocation: data: ' + JSON.stringify(data));
}
});
```
To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user.
# Location Overview
People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices.
With the location awareness capability offered by , mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users.
Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording.
## Basic Concepts
Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors.
- **Coordinate**
A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
- **GNSS positioning**
GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device.
- **Base station positioning**
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network.
- **WLAN or Bluetooth positioning**
WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network.
## Working Principles
Location awareness is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a location request to the system and stop the location request when the service scenario ends. In this process, the system reports the location information to the application on a real-time basis.
## Limitations and Constraints
Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application.
Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information.
## Samples
The following sample is provided to help you better understand how to develop location services:
-[`Location`: Location (eTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location)
此差异已折叠。
......@@ -8,7 +8,7 @@ In Host mode, you can obtain the list of connected USB devices, enable or disabl
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md).
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usbManager.md).
**Table 1** Open USB APIs
......@@ -18,7 +18,7 @@ The following table lists the USB APIs currently available. For details, see the
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device list returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise\<number> | Performs bulk transfer. |
......@@ -36,7 +36,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
```js
// Import the USB API package.
import usb from '@ohos.usbV9';
import usb from '@ohos.usbManager';
// Obtain the USB device list.
let deviceList = usb.getDevices();
/*
......
......@@ -6,7 +6,7 @@ The [intl](intl-guidelines.md) module provides basic i18n capabilities through t
## Obtaining and Setting i18n Information
The system provides APIs to configure information such as the system language, preferred language, country or region, 24-hour clock, and local digit switch.
The following table lists the APIs used to configure information such as the system language, preferred language, country or region, 24-hour clock, and use of local digits.
### Available APIs
......@@ -30,15 +30,15 @@ The system provides APIs to configure information such as the system language, p
| System | getPreferredLanguageList()<sup>9+</sup> | Obtains the preferred language list. |
| System | getFirstPreferredLanguage()<sup>9+</sup> | Obtains the first language in the preferred language list. |
| System | getAppPreferredLanguage()<sup>9+</sup> | Obtains the preferred language of an application. |
| System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Sets whether to enable the local digit switch. |
| System | getUsingLocalDigit()<sup>9+</sup> | Checks whether the local digit switch is turned on. |
| System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Specifies whether to enable use of local digits. |
| System | getUsingLocalDigit()<sup>9+</sup> | Checks whether use of local digits is enabled. |
| | isRTL(locale:string):boolean<sup>9+</sup> | Checks whether the locale uses a right-to-left (RTL) language.|
### How to Develop
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Obtain and set the system language.
......@@ -51,7 +51,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLanguage("en"); // Set the system language to en.
let language = I18n.System.getSystemLanguage(); // language = "en"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -65,7 +65,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemRegion("CN"); // Set the system country to CN.
let region = I18n.System.getSystemRegion(); // region = "CN"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -79,7 +79,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN.
let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -92,7 +92,7 @@ The system provides APIs to configure information such as the system language, p
let rtl = I18n.isRTL("zh-CN"); // rtl = false
rtl = I18n.isRTL("ar"); // rtl = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -106,7 +106,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.set24HourClock(true);
let hourClock = I18n.System.is24HourClock(); // hourClock = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -121,7 +121,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false;
let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -136,7 +136,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false;
let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S."
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -150,7 +150,7 @@ The system provides APIs to configure information such as the system language, p
let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"]
let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -162,7 +162,7 @@ The system provides APIs to configure information such as the system language, p
try {
let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -182,7 +182,7 @@ The system provides APIs to configure information such as the system language, p
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB"
let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources.
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -190,14 +190,14 @@ The system provides APIs to configure information such as the system language, p
Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.)
Call **getUsingLocalDigit** to check whether the local digit switch is enabled.
Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur".
Currently, use of local digits is supported only for the following languages: **ar**, **as**, **bn**, **fa**, **mr**, **my**, **ne**, **ur**.
```js
try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
let status = I18n.System.getUsingLocalDigit(); // status = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -220,14 +220,14 @@ try {
| Calendar | getMinimalDaysInFirstWeek():number<sup>8+</sup> | Obtains the minimum number of days in the first week of a year. |
| Calendar | setMinimalDaysInFirstWeek(value:number): void<sup>8+</sup> | Sets the minimum number of days in the first week of a year. |
| Calendar | getDisplayName(locale:string):string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. |
| Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether the specified date in this **Calendar** object is a weekend. |
| Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether a given date is a weekend in the calendar. |
### How to Develop
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate a **Calendar** object.
......@@ -254,7 +254,7 @@ try {
Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object.
```js
calendar.set(2021, 12, 21, 6, 0, 0)
calendar.set(2021, 12, 21, 6, 0, 0);
```
5. Set and obtain the time zone for the **Calendar** object.
......@@ -317,7 +317,7 @@ try {
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate a **PhoneNumberFormat** object.
......@@ -359,7 +359,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Convert a measurement unit.
......@@ -393,7 +393,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiates an **IndexUtil** object.
......@@ -418,7 +418,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
Call **addLocale** to add the alphabet index of a new locale to the current index list.
```js
indexUtil.addLocale("ar")
indexUtil.addLocale("ar");
```
5. Obtain the index of a string.
......@@ -454,7 +454,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate a **BreakIterator** object.
......@@ -462,7 +462,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
Call **getLineInstance** to instantiate a **BreakIterator** object.
```js
let locale = "en-US"
let locale = "en-US";
let breakIterator = I18n.getLineInstance(locale);
```
......@@ -531,7 +531,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate the **TimeZone** object, and obtain the time zone information.
......@@ -592,7 +592,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Obtains the transliterator ID list.
......@@ -637,7 +637,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Check the input character has a certain attribute.
......@@ -719,7 +719,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Check the sequence of year, month, and day in a date.
......
......@@ -25,7 +25,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiates a **Locale** object.
......@@ -100,7 +100,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **DateTimeFormat** object.
......@@ -170,7 +170,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **NumberFormat** object.
......@@ -195,7 +195,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
```js
let options = {compactDisplay: "short", notation: "compact"};
let numberFormat = new Intl.NumberFormat("zh-CN", options);
let number = 1234.5678
let number = 1234.5678;
let formatResult = numberFormat.format(number); // formatResult = "1235"
```
......@@ -229,7 +229,7 @@ Users in different regions have different requirements for string sorting. [Coll
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **Collator** object.
......@@ -290,7 +290,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **PluralRules** object.
......@@ -313,7 +313,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
let number = 1234.5678
let number = 1234.5678;
let categoryResult = pluralRules.select(number); // categoryResult = "other"
```
......@@ -338,7 +338,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **RelativeTimeFormat** object.
......@@ -362,7 +362,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2;
let unit = "year"
let unit = "year";
let formatResult = relativeTimeFormat.format(number, unit); // 2 years later
```
......@@ -373,7 +373,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2;
let unit = "year"
let unit = "year";
let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}]
```
......
......@@ -312,7 +312,7 @@
- [@ohos.systemParameterV9 (System Parameter)](js-apis-system-parameterV9.md)
- [@ohos.thermal (Thermal Management)](js-apis-thermal.md)
- [@ohos.update (Update)](js-apis-update.md)
- [@ohos.usbV9 (USB Management)](js-apis-usb.md)
- [@ohos.usbManager (USB Manager)](js-apis-usbManager.md)
- [@ohos.vibrator (Vibrator)](js-apis-vibrator.md)
- Account Management
- [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md)
......
......@@ -2,9 +2,11 @@
The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
......@@ -20,18 +22,18 @@ Describes battery information.
| Name | Type | Readable| Writable| Description |
| --------------- | ------------------- | ---- | ---- | ---------------------|
| batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. |
| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the device. |
| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the device. |
| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging status of the device. |
| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health status of the device. |
| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. |
| voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. |
| technology | string | Yes | No | Battery technology of the device. |
| batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. |
| isBatteryPresent<sup>7+</sup> | boolean | Yes | No | Whether the battery is supported or present. |
| batteryCapacityLevel<sup>9+</sup> | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. |
| estimatedRemainingChargeTime<sup>9+</sup> | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. |
| totalEnergy<sup>9+</sup> | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. |
| nowCurrent<sup>9+</sup> | number | Yes | No | Battery current of the device, in unit of mA. This is a system API. |
| remainingEnergy<sup>9+</sup> | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. This is a system API.|
| estimatedRemainingChargeTime<sup>9+</sup> | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. This is a system API. |
| totalEnergy<sup>9+</sup> | number | Yes | No | Total battery capacity of the device, in unit of mAh. **System API**: This is a system API. |
| nowCurrent<sup>9+</sup> | number | Yes | No | Battery current of the device, in unit of mA. **System API**: This is a system API. |
| remainingEnergy<sup>9+</sup> | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. **System API**: This is a system API.|
## BatteryPluggedType
......@@ -41,10 +43,10 @@ Enumerates charger types.
| Name | Value | Description |
| -------- | ---- | ----------------- |
| NONE | 0 | Unknown type |
| AC | 1 | AC charger|
| USB | 2 | USB charger |
| WIRELESS | 3 | Wireless charger|
| NONE | 0 | Unknown charger type. |
| AC | 1 | AC charger.|
| USB | 2 | USB charger. |
| WIRELESS | 3 | Wireless charger.|
## BatteryChargeState
......@@ -82,14 +84,15 @@ Enumerates battery levels.
| Name | Value| Description |
| -------------- | ------ | ---------------------------- |
| LEVEL_NONE | 0 | Unknown battery level. |
| LEVEL_FULL | 1 | Full battery level. |
| LEVEL_HIGH | 2 | High battery level. |
| LEVEL_NORMAL | 3 | Normal battery level.|
| LEVEL_LOW | 4 | Low battery level. |
| LEVEL_CRITICAL | 5 | Ultra-low battery level.|
| LEVEL_WARNING | 5 | Alarm battery level.|
| LEVEL_CRITICAL | 6 | Ultra-low battery level.|
| LEVEL_SHUTDOWN | 7 | Power-down battery level.|
## CommonEventBatteryChangedCode<sup>9+</sup>
## CommonEventBatteryChangedKey<sup>9+</sup>
Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event.
......@@ -97,14 +100,12 @@ Enumerates keys for querying the additional information about the **COMMON_EVENT
| Name | Value| Description |
| -------------------- | ------ | -------------------------------------------------- |
| EXTRA_SOC | 0 | Remaining battery level in percentage. |
| EXTRA_VOLTAGE | 1 | Battery voltage of the device. |
| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. |
| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. |
| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. |
| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. |
| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. |
| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. |
| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. |
| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.|
| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. |
| EXTRA_SOC | "soc" | Remaining battery level in percentage. |
| EXTRA_CHARGE_STATE | "chargeState" | Battery charging status of the device. |
| EXTRA_HEALTH_STATE | "healthState" | Battery health status of the device. |
| EXTRA_PLUGGED_TYPE | "pluggedType" | Type of the charger connected to the device. |
| EXTRA_VOLTAGE | "voltage" | Battery voltage of the device. |
| EXTRA_TECHNOLOGY | "technology" | Battery technology of the device. |
| EXTRA_TEMPERATURE | "temperature" | Battery temperature of the device. |
| EXTRA_PRESENT | "present" | Whether the battery is supported by the device or installed.|
| EXTRA_CAPACITY_LEVEL | "capacityLevel" | Battery level of the device. |
......@@ -175,7 +175,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono
| -------- | -------------------- | ---- | ------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.|
| uri | string | Yes | URI of the data.|
| callback | AsyncCallback&lt;void&gt; | No | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | No | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
......
......@@ -53,10 +53,10 @@ Stage model:
```ts
// Import the module.
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -110,7 +110,7 @@ Called when the **revokeSave()** API is successfully called.
## DistributedObjectV9
Provides APIs for managing a distributed data object.
Represents a distributed data object.
### setSessionId<sup>9+</sup>
......@@ -156,10 +156,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -218,10 +218,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -257,7 +257,7 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to|
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
......@@ -294,10 +294,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -321,7 +321,7 @@ g_object.setSessionId().then (()=>{
on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Subscribes to data changes of this distributed data object.
Subscribes to the data change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
......@@ -357,10 +357,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -381,7 +381,7 @@ g_object.on("change", globalThis.changeCallback);
off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void
Unsubscribes from the data changes of this distributed data object.
Unsubscribes from the data change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
......@@ -413,10 +413,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -432,7 +432,7 @@ g_object.off("change");
on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void
Subscribes to statue changes of this distributed data object.
Subscribes to the status change of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
......@@ -463,10 +463,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -507,7 +507,7 @@ let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:fals
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
// Unregister the specified status change callback.
// Unsubscribe from the specified status change callback for the distributed data object.
g_object.off("status",globalThis.statusCallback);
// Unregister all status change callbacks.
g_object.off("status");
......@@ -517,10 +517,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -529,7 +529,7 @@ let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:fals
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
// Unregister the specified status change callback.
// Unsubscribe from all status change callbacks for the distributed data object.
g_object.off("status",globalThis.statusCallback);
// Unregister all status change callbacks.
g_object.off("status");
......@@ -579,10 +579,10 @@ g_object.save("local", (result) => {
Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -627,6 +627,8 @@ The saved data will be released in the following cases:
**Example**
FA model:
```js
import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility';
......@@ -643,13 +645,14 @@ g_object.save("local").then((result) => {
console.error("save failed");
});
```
Stage model:
```js
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
}
......@@ -712,10 +715,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability {
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context
}
......@@ -786,10 +789,10 @@ Stage model:
```ts
import distributedObject from '@ohos.data.distributedDataObject';
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
// Obtain the context.
let context;
class MainAbility extends Ability {
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context
}
......@@ -1000,7 +1003,7 @@ Unsubscribes from the status change of this distributed data object.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object. |
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
......
......@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
......@@ -69,9 +69,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -103,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.|
**Return value**
......@@ -139,9 +139,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
......@@ -215,9 +215,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value**
......@@ -294,9 +294,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
......@@ -358,9 +358,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value**
......@@ -428,9 +428,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -662,7 +662,7 @@ try {
has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result..
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
......@@ -698,7 +698,7 @@ try {
has(key: string): Promise&lt;boolean&gt;
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result..
Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
......@@ -987,7 +987,7 @@ Unsubscribes from data changes.
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. |
| callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.|
| callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, all callbacks for data changes will be unregistered. |
**Example**
......
......@@ -47,11 +47,11 @@ Adds one or more rules. HiChecker detects unexpected operations or gives feedbac
```js
try {
// Add a rule.
hichecker.addCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);}
hichecker.addCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);
// Add multiple rules.
hichecker.addCheckRule(
hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH);
catch (err) {
// hichecker.addCheckRule(
// hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH);
} catch (err) {
console.error(`code: ${err.code}, message: ${err.message}`);
}
```
......@@ -77,9 +77,9 @@ try {
// Remove a rule.
hichecker.removeCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);
// Remove multiple rules.
hichecker.removeCheckRule(
hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH);
catch (err) {
// hichecker.removeCheckRule(
// hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH);
} catch (err) {
console.error(`code: ${err.code}, message: ${err.message}`);
}
```
......@@ -114,7 +114,7 @@ try {
// Check whether the added rule exists in the collection of added rules.
hichecker.containsCheckRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true;
hichecker.containsCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); // return false;
catch (err) {
} catch (err) {
console.error(`code: ${err.code}, message: ${err.message}`);
}
```
......
......@@ -297,7 +297,7 @@ import hidebug from '@ohos.hidebug'
try {
hidebug.startJsCpuProfiling("cpu_profiling");
...
// ...
hidebug.stopJsCpuProfiling();
} catch (error) {
console.info(error.code)
......@@ -326,7 +326,7 @@ import hidebug from '@ohos.hidebug'
try {
hidebug.startJsCpuProfiling("cpu_profiling");
...
// ...
hidebug.stopJsCpuProfiling();
} catch (error) {
console.info(error.code)
......
......@@ -581,6 +581,8 @@ httpResponseCache.delete().then(() => {
| 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. |
For details about the error codes, see [libcurl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
## HttpDataType<sup>9+</sup>
Enumerates HTTP data types.
......
# @ohos.i18n (Internationalization)
The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402.
The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402.
The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities.
> **NOTE**
......@@ -53,7 +53,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China"
} catch(error) {
console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -92,7 +92,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese
} catch(error) {
console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -100,7 +100,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLanguages(): Array&lt;string&gt;
Obtains the list of system languages.
Obtains the list of system languages. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
......@@ -123,7 +123,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ]
} catch(error) {
console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -131,7 +131,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemCountries(language: string): Array&lt;string&gt;
Obtains the list of countries and regions supported for the specified language.
Obtains the list of countries and regions supported for the specified language. For details about countries or regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
......@@ -160,7 +160,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total
} catch(error) {
console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -198,7 +198,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let res = I18n.System.isSuggested('zh', 'CN'); // res = true
} catch(error) {
console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -206,7 +206,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLanguage(): string
Obtains the system language.
Obtains the system language. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
......@@ -229,7 +229,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language.
} catch(error) {
console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -264,7 +264,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setSystemLanguage('zh'); // Set the current system language to zh.
} catch(error) {
console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -272,7 +272,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemRegion(): string
Obtains the system region.
Obtains the system region. For details about system regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
......@@ -295,7 +295,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region.
} catch(error) {
console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -330,7 +330,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setSystemRegion('CN'); // Set the current system region to CN.
} catch(error) {
console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -338,7 +338,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLocale(): string
Obtains the system locale.
Obtains the system locale. For details about system locales, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
......@@ -361,7 +361,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale.
} catch(error) {
console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -396,7 +396,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN.
} catch(error) {
console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -427,7 +427,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled.
} catch(error) {
console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -463,7 +463,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.set24HourClock(true);
} catch(error) {
console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -502,7 +502,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list.
} catch(error) {
console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -539,7 +539,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.removePreferredLanguage(index);
} catch(error) {
console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -570,7 +570,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list.
} catch(error) {
console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -601,7 +601,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list.
} catch(error) {
console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -632,7 +632,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application.
} catch(error) {
console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -640,7 +640,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static setUsingLocalDigit(flag: boolean): void
Sets whether to enable the local digit switch.
Specifies whether to enable use of local digits.
**System API**: This is a system API.
......@@ -667,7 +667,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
} catch(error) {
console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -675,7 +675,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getUsingLocalDigit(): boolean
Checks whether the local digit switch is turned on.
Checks whether use of local digits is enabled.
**System capability**: SystemCapability.Global.I18n
......@@ -698,7 +698,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled.
} catch(error) {
console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`)
console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
}
```
......@@ -1025,7 +1025,7 @@ Checks whether the specified date in this **Calendar** object is a weekend.
| Name | Type | Mandatory | Description |
| ---- | ---- | ---- | ---------------------------------------- |
| date | Date | No | Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.|
| date | Date | No | Specified date in this **Calendar** object. If the **date** parameter is not specified, the system checks whether the current date is a weekend.|
**Return value**
......
# @ohos.intl (Internationalization)
The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402.
The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402.
The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities.
> **NOTE**
......@@ -48,9 +48,9 @@ Creates a **Locale** object.
**Example**
```js
// The default constructor uses the current system locale to create a Locale object.
let locale = new Intl.Locale()
let locale = new Intl.Locale();
// Return the current system locale.
let localeID = locale.toString()
let localeID = locale.toString();
```
......@@ -72,8 +72,8 @@ Creates a **Locale** object.
**Example**
```js
// Create a Locale object named zh-CN.
let locale = new Intl.Locale("zh-CN")
let localeID = locale.toString() // localeID = "zh-CN"
let locale = new Intl.Locale("zh-CN");
let localeID = locale.toString(); // localeID = "zh-CN"
```
......@@ -429,7 +429,7 @@ Obtains the options of the **NumberFormat** object.
// Obtain the options of the NumberFormat object.
let options = numfmt.resolvedOptions();
let style = options.style; // style = decimal
let notation = options.notation // notation = scientific
let notation = options.notation; // notation = scientific
```
......@@ -552,7 +552,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
// Obtain the options of the Collator object.
let options = collator.resolvedOptions();
let usage = options.usage; // usage = "sort"
let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true
let ignorePunctuation = options.ignorePunctuation; // ignorePunctuation = true
```
......@@ -631,7 +631,7 @@ Obtains a string that represents the singular-plural type of the specified numbe
| Type | Description |
| ------ | ---------------------------------------- |
| string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.|
| string | Singular-plural type. The value can be any of the following: **zero**, **one**, **two**, **few**, **many**, **others**.|
**Example**
```js
......
......@@ -15,8 +15,8 @@ import resourceManager from '@ohos.resourceManager';
## Instruction
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model.
For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md).
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object.
For details about how to reference context in the stage model, see [Context in the Stage Model](../..//application-models/application-context-stage.md).
```ts
import Ability from '@ohos.application.Ability';
......@@ -60,6 +60,7 @@ Obtains the **ResourceManager** object of this application. This API uses an asy
});
});
```
> **NOTE**<br>In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
## resourceManager.getResourceManager
......@@ -116,6 +117,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
console.log("error is " + error);
});
```
> **NOTE**<br>In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
## resourceManager.getResourceManager
......@@ -1767,7 +1769,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaByName(resName: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......
......@@ -5,6 +5,7 @@ The **usb** module provides USB device management functions, including USB devic
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md) instead.
## Modules to Import
......
......@@ -4,6 +4,7 @@ The **usb** module provides USB device management functions, including USB devic
> **NOTE**<br>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md) instead.
## Modules to Import
......
此差异已折叠。
......@@ -94,39 +94,6 @@ Declare the events for service widgets in the **actions** field in the JSON file
}
```
You can also implement redirection to the target application using a **want**, which contains the **abilityName**, **bundleName**, and **parameters** fields.
| Selector | Type | Default Value | Description |
| ------ | ------ | -------- | ---------------------------------------- |
| action | string | "router" | Event type.<br>- **"router"**: redirection event.<br>- **"message"**: message event.|
| want | [Want](../apis/js-apis-app-ability-want.md) | - | Information about the target application. For details, see the **want** format. |
```json
{
"data": {
"mainAbility": "xxx.xxx.xxx"
},
"actions": {
"routerEventName1": {
"action": "router",
"want": {
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility"
}
},
"routerEventName2": {
"action": "router",
"want": {
"action": "xxx.intent.action.DIAL",
"uri": "tel:12345678"
}
}
}
}
```
In API version 8, the [featureAbility.getWant](../apis/js-apis-ability-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters.
- Message event properties
......
......@@ -4569,7 +4569,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
表示返回码的枚举。
> **说明:**<br/>
> 从API version 8开始支持,从API version 9开始废弃。建议查看[错误码文档](../errorcodes/errorcode-app-account.md)替代。
> 从API version 8开始支持,从API version 9开始废弃。相关信息建议查看[错误码文档](../errorcodes/errorcode-account.md)替代。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册