提交 f155c062 编写于 作者: zyjhandsome's avatar zyjhandsome

Merge branch 'master' of https://gitee.com/openharmony/docs

...@@ -192,7 +192,7 @@ zh-cn/application-dev/napi/rawfile_guidelines.md @ningningW ...@@ -192,7 +192,7 @@ zh-cn/application-dev/napi/rawfile_guidelines.md @ningningW
zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih
zh-cn/application-dev/background-task-management/ @ningningW @wangwenli_wolf @tangtiantian2021 @nan-xiansen zh-cn/application-dev/background-task-management/ @ningningW @wangwenli_wolf @tangtiantian2021 @nan-xiansen
zh-cn/application-dev/work-scheduler/ @ningningW zh-cn/application-dev/work-scheduler/ @ningningW
zh-cn/application-dev/internationalization/ @ningningW @Buda-Liu @budda-wang @yangqing3 zh-cn/application-dev/internationalization/ @ningningW @Buda-Liu @mengjingzhimo @yangqing3
zh-cn/application-dev/device/usb-overview.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123 zh-cn/application-dev/device/usb-overview.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123
zh-cn/application-dev/device/usb-guidelines.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123 zh-cn/application-dev/device/usb-guidelines.md @ge-yafang @jasonyujia @andeszhang @liuhonggang123
zh-cn/application-dev/device/device-location-overview.md @RayShih zh-cn/application-dev/device/device-location-overview.md @RayShih
......
...@@ -10,17 +10,18 @@ The geographic description helps users understand a location easily by providing ...@@ -10,17 +10,18 @@ The geographic description helps users understand a location easily by providing
## Available APIs ## Available APIs
The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md). The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md).
**Table1** APIs for geocoding and reverse geocoding **Table1** APIs for geocoding and reverse geocoding
| API | Description | | API | Description |
| -------- | -------- | | -------- | -------- |
| isGeocoderAvailable(): boolean; | Obtains the (reverse) geocoding service status.| | isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result.|
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. | | isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result.|
| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>> | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. | | getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. | | getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>> | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. | | getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. |
## How to Develop ## How to Develop
...@@ -29,21 +30,22 @@ The following table describes APIs available for mutual conversion between coord ...@@ -29,21 +30,22 @@ The following table describes APIs available for mutual conversion between coord
> >
> 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. > The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
1. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. 1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geolocation from '@ohos.geolocation';
``` ```
2. Query whether geocoder service is available. 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. - Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; geolocation.isGeoServiceAvailable((err, data) => {
try { if (err) {
var isAvailable = geoLocationManager.isGeocoderAvailable(); console.log('isGeoServiceAvailable err: ' + JSON.stringify(err));
} catch (err) { } else {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.log('isGeoServiceAvailable data: ' + JSON.stringify(data));
} }
});
``` ```
3. Obtain the conversion result. 3. Obtain the conversion result.
...@@ -51,7 +53,7 @@ The following table describes APIs available for mutual conversion between coord ...@@ -51,7 +53,7 @@ The following table describes APIs available for mutual conversion between coord
```ts ```ts
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) { if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else { } else {
...@@ -60,12 +62,12 @@ The following table describes APIs available for mutual conversion between coord ...@@ -60,12 +62,12 @@ The following table describes APIs available for mutual conversion between coord
}); });
``` ```
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-geoLocationManager.md). 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. - Call **getAddressesFromLocationName** to convert geographic description into coordinates.
```ts ```ts
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) { if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else { } else {
...@@ -74,6 +76,6 @@ The following table describes APIs available for mutual conversion between coord ...@@ -74,6 +76,6 @@ The following table describes APIs available for mutual conversion between coord
}); });
``` ```
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-geoLocationManager.md). 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**. To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
...@@ -10,11 +10,11 @@ Real-time location of the device is recommended for location-sensitive services. ...@@ -10,11 +10,11 @@ Real-time location of the device is recommended for location-sensitive services.
## Available APIs ## Available APIs
For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md). For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md).
## How to Develop ## How to Develop
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geoLocationManager.md). 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. 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: The system provides the following location permissions:
...@@ -41,10 +41,10 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -41,10 +41,10 @@ To learn more about the APIs for obtaining device location information, see [Geo
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md). You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
2. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities. 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
```ts ```
import geoLocationManager from '@ohos.geoLocationManager'; 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> 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>
...@@ -53,7 +53,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -53,7 +53,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
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. 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.
```ts ```
export enum LocationRequestScenario { export enum LocationRequestScenario {
UNSET = 0x300, UNSET = 0x300,
NAVIGATION, NAVIGATION,
...@@ -78,7 +78,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -78,7 +78,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
Sample code for initializing **requestInfo** for navigation: Sample code for initializing **requestInfo** for navigation:
```ts ```ts
var requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
**Method 2:** **Method 2:**
...@@ -107,7 +107,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -107,7 +107,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
Sample code for initializing **requestInfo** for the location accuracy priority policy: Sample code for initializing **requestInfo** for the location accuracy priority policy:
```ts ```ts
var requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
4. Instantiate the **Callback** object for the system to report location results. 4. Instantiate the **Callback** object for the system to report location results.
...@@ -122,24 +122,25 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -122,24 +122,25 @@ To learn more about the APIs for obtaining device location information, see [Geo
5. Start device location. 5. Start device location.
```ts ```ts
geoLocationManager.on('locationChange', requestInfo, locationChange); geolocation.on('locationChange', requestInfo, locationChange);
``` ```
6. (Optional) Stop device location. 6. (Optional) Stop device location.
```ts ```ts
geoLocationManager.off('locationChange', locationChange); 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. If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; geolocation.getLastLocation((err, data) => {
try { if (err) {
var location = geoLocationManager.getLastLocation(); console.log('getLastLocation: err: ' + JSON.stringify(err));
} catch (err) { } else {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.log('getLastLocation: data: ' + JSON.stringify(data));
} }
});
``` ```
To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user. To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user.
...@@ -385,7 +385,6 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; ...@@ -385,7 +385,6 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID.
let permissionFlag = 1;
try { try {
atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => {
console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`);
...@@ -459,11 +458,12 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ...@@ -459,11 +458,12 @@ For details about the error codes, see [Ability Access Control Error Codes](../e
**Example** **Example**
```js ```js
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let tokenIDList: Array<number> = []; let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100);
let permissionNameList = []; let tokenIDList: Array<number> = [appInfo.accessTokenId];
let permissionNameList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
try { try {
atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => { atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => {
console.debug("receive permission state change, data:" + JSON.stringify(data)); console.debug("receive permission state change, data:" + JSON.stringify(data));
...@@ -508,11 +508,12 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ...@@ -508,11 +508,12 @@ For details about the error codes, see [Ability Access Control Error Codes](../e
**Example** **Example**
```js ```js
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let tokenIDList: Array<number> = []; let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100);
let permissionNameList = []; let tokenIDList: Array<number> = [appInfo.accessTokenId];
let permissionNameList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
try { try {
atManager.off('permissionStateChange', tokenIDList, permissionNameList); atManager.off('permissionStateChange', tokenIDList, permissionNameList);
} catch(err) { } catch(err) {
......
# Fault Logger # Fault Logger
> **NOTE**<br/> > **NOTE**<br/>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......
...@@ -30,7 +30,7 @@ If your application needs to access the device location information, it must fir ...@@ -30,7 +30,7 @@ If your application needs to access the device location information, it must fir
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters|
If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION\_IN\_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md). You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md).
...@@ -1615,7 +1615,7 @@ Obtains the current country code. ...@@ -1615,7 +1615,7 @@ Obtains the current country code.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;[CountryCode](#countrycode)&gt; | [CountryCode](#countrycode) | NA | Promise used to return the country code.| | Promise&lt;[CountryCode](#countrycode)&gt; | [CountryCode](#countrycode) | NA | Callback used to return the country code.|
**Error codes** **Error codes**
...@@ -1815,7 +1815,7 @@ For details about the following error codes, see [Location Error Codes](../error ...@@ -1815,7 +1815,7 @@ For details about the following error codes, see [Location Error Codes](../error
setReverseGeocodingMockInfo(mockInfos: Array&lt;ReverseGeocodingMockInfo&gt;): void; setReverseGeocodingMockInfo(mockInfos: Array&lt;ReverseGeocodingMockInfo&gt;): void;
Sets information of the mock reverse geocoding function, including the mapping between a location and geographical name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographical name will be returned. Sets information of the mock reverse geocoding function, including the mapping between a location and geographic name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographic name will be returned.
**System capability**: SystemCapability.Location.Location.Core **System capability**: SystemCapability.Location.Location.Core
...@@ -1825,7 +1825,7 @@ Sets information of the mock reverse geocoding function, including the mapping b ...@@ -1825,7 +1825,7 @@ Sets information of the mock reverse geocoding function, including the mapping b
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| mockInfos | Array&lt;[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)&gt; | Yes| Array of information of the mock reverse geocoding function, including a location and a geographical name.| | mockInfos | Array&lt;[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)&gt; | Yes| Array of information of the mock reverse geocoding function, including a location and a geographic name.|
**Error codes** **Error codes**
...@@ -1874,7 +1874,7 @@ Checks whether a user agrees with the privacy statement of the location service. ...@@ -1874,7 +1874,7 @@ Checks whether a user agrees with the privacy statement of the location service.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| boolean | boolean | NA | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| | boolean | boolean | NA | Result indicating whether the user agrees with the privacy statement.|
**Error codes** **Error codes**
...@@ -1913,7 +1913,7 @@ Sets the user confirmation status for the privacy statement of the location serv ...@@ -1913,7 +1913,7 @@ Sets the user confirmation status for the privacy statement of the location serv
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | [LocationPrivacyType](#locationprivacytype) | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.| | type | [LocationPrivacyType](#locationprivacytype) | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.|
| isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| | isConfirmed | boolean | Yes| Whether the user agrees with the privacy statement.|
**Error codes** **Error codes**
...@@ -1975,7 +1975,7 @@ Defines a reverse geocoding request. ...@@ -1975,7 +1975,7 @@ Defines a reverse geocoding request.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| | locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| | longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| | maxItems | number | Yes| Yes| Maximum number of location records to be returned.|
...@@ -2005,7 +2005,7 @@ Defines a geographic location. ...@@ -2005,7 +2005,7 @@ Defines a geographic location.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| latitude | number | Yes| No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude | number | Yes| No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude | number | Yes| No | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| | longitude | number | Yes| No | Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| locale | string | Yes| No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| | locale | string | Yes| No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| placeName | string | Yes| No | Landmark of the location.| | placeName | string | Yes| No | Landmark of the location.|
| countryCode | string | Yes| No | Country code.| | countryCode | string | Yes| No | Country code.|
...@@ -2022,7 +2022,7 @@ Defines a geographic location. ...@@ -2022,7 +2022,7 @@ Defines a geographic location.
| addressUrl | string | Yes| No| Website URL.| | addressUrl | string | Yes| No| Website URL.|
| descriptions | Array&lt;string&gt; | Yes| No| Additional descriptions.| | descriptions | Array&lt;string&gt; | Yes| No| Additional descriptions.|
| descriptionsSize | number | Yes| No| Total number of additional descriptions.| | descriptionsSize | number | Yes| No| Total number of additional descriptions.|
| isFromMock | Boolean | Yes| No| Whether the geographical name is from the mock reverse geocoding function.| | isFromMock | Boolean | Yes| No| Whether the geographic name is from the mock reverse geocoding function.|
## LocationRequest ## LocationRequest
...@@ -2142,7 +2142,7 @@ Defines a location. ...@@ -2142,7 +2142,7 @@ Defines a location.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| latitude | number| Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude | number| Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude | number| Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| | longitude | number| Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| altitude | number | Yes| No| Location altitude, in meters.| | altitude | number | Yes| No| Location altitude, in meters.|
| accuracy | number | Yes| No| Location accuracy, in meters.| | accuracy | number | Yes| No| Location accuracy, in meters.|
| speed | number | Yes| No|Speed, in m/s.| | speed | number | Yes| No|Speed, in m/s.|
...@@ -2165,7 +2165,7 @@ Represents information of the mock reverse geocoding function. ...@@ -2165,7 +2165,7 @@ Represents information of the mock reverse geocoding function.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Yes| Latitude and longitude information.| | location | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Yes| Latitude and longitude information.|
| geoAddress | [GeoAddress](#geoaddress) | Yes| Yes|Geographical name.| | geoAddress | [GeoAddress](#geoaddress) | Yes| Yes|Geographic name.|
## LocationMockConfig ## LocationMockConfig
......
...@@ -19,9 +19,9 @@ The system provides the following location permissions: ...@@ -19,9 +19,9 @@ The system provides the following location permissions:
If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking:
API versions earlier than 9: Apply for **ohos.permission.LOCATION**. - API versions earlier than 9: Apply for **ohos.permission.LOCATION**.
API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. - API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately.
| API Version| Location Permission| Permission Application Result| Location Accuracy| | API Version| Location Permission| Permission Application Result| Location Accuracy|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -30,7 +30,7 @@ API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, ...@@ -30,7 +30,7 @@ API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**,
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| | 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters|
If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION\_IN\_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md). You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md).
...@@ -971,7 +971,7 @@ Converts geographic description into coordinates through geocoding. This API use ...@@ -971,7 +971,7 @@ Converts geographic description into coordinates through geocoding. This API use
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Array&lt;[GeoAddress](#geoaddress)&gt;|NA|Callback used to return the geocoding result.| | Promise&lt;Array&lt;[GeoAddress](#geoaddress)&gt;&gt; | Array&lt;[GeoAddress](#geoaddress)&gt;|NA|Promise used to return the geocoding result.|
**Example** **Example**
...@@ -1265,7 +1265,7 @@ Defines a reverse geocoding request. ...@@ -1265,7 +1265,7 @@ Defines a reverse geocoding request.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| | locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| | longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| | maxItems | number | Yes| Yes| Maximum number of location records to be returned.|
...@@ -1305,7 +1305,7 @@ Defines a geographic location. ...@@ -1305,7 +1305,7 @@ Defines a geographic location.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| | longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| locale<sup>7+</sup> | string | Yes| No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| | locale<sup>7+</sup> | string | Yes| No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.|
| placeName<sup>7+</sup> | string | Yes| No| Landmark of the location.| | placeName<sup>7+</sup> | string | Yes| No| Landmark of the location.|
| countryCode<sup>7+</sup> | string | Yes| No| Country code.| | countryCode<sup>7+</sup> | string | Yes| No| Country code.|
...@@ -1493,7 +1493,7 @@ Defines a location. ...@@ -1493,7 +1493,7 @@ Defines a location.
| Name| Type| Readable|Writable| Description| | Name| Type| Readable|Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| | latitude<sup>7+</sup> | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.|
| longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| | longitude<sup>7+</sup> | number | Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.|
| altitude<sup>7+</sup> | number | Yes| No| Location altitude, in meters.| | altitude<sup>7+</sup> | number | Yes| No| Location altitude, in meters.|
| accuracy<sup>7+</sup> | number | Yes| No| Location accuracy, in meters.| | accuracy<sup>7+</sup> | number | Yes| No| Location accuracy, in meters.|
| speed<sup>7+</sup> | number | Yes| No| Speed, in m/s.| | speed<sup>7+</sup> | number | Yes| No| Speed, in m/s.|
......
# HiAppEvent # HiAppEvent
This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE** > **NOTE**
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead. > - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
......
# HiDebug # HiDebug
> **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
This module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. The HiDebug module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
## Modules to Import ## Modules to Import
......
...@@ -45,7 +45,7 @@ Enumerates the log levels. ...@@ -45,7 +45,7 @@ Enumerates the log levels.
**System capability**: SystemCapability.HiviewDFX.HiLog **System capability**: SystemCapability.HiviewDFX.HiLog
| Name | Default Value| Description | | Name | Value| Description |
| ----- | ------ | ------------------------------------------------------------ | | ----- | ------ | ------------------------------------------------------------ |
| DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.| | DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.|
| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| | INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.|
......
...@@ -18,9 +18,9 @@ import http from '@ohos.net.http'; ...@@ -18,9 +18,9 @@ import http from '@ohos.net.http';
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. // Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision. // This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
...@@ -38,14 +38,18 @@ httpRequest.request( ...@@ -38,14 +38,18 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // Optional. The default value is 60000, in ms. expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements. // data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result); console.info('Result:' + data.result);
console.info('code:' + data.responseCode); console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements. // data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + data.cookies); // 8+
} else { } else {
...@@ -78,10 +82,9 @@ import http from '@ohos.net.http'; ...@@ -78,10 +82,9 @@ import http from '@ohos.net.http';
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
``` ```
## HttpRequest ## HttpRequest
HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request ### request
...@@ -89,7 +92,7 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void ...@@ -89,7 +92,7 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -121,7 +124,7 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR ...@@ -121,7 +124,7 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -158,14 +161,13 @@ httpRequest.request("EXAMPLE_URL", ...@@ -158,14 +161,13 @@ httpRequest.request("EXAMPLE_URL",
}); });
``` ```
### request ### request
request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
Initiates an HTTP request to a given URL. This API uses a promise to return the result. Initiates an HTTP request to a given URL. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -174,7 +176,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the ...@@ -174,7 +176,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | ----------------------------------------------- | | ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. | | url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| | options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
**Return value** **Return value**
...@@ -226,7 +228,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void ...@@ -226,7 +228,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
>This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead. >This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -250,14 +252,13 @@ httpRequest.on('headerReceive', (err, data) => { ...@@ -250,14 +252,13 @@ httpRequest.on('headerReceive', (err, data) => {
}); });
``` ```
### off\('headerReceive'\) ### off\('headerReceive'\)
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
> >
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead. >1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead.
> >
...@@ -301,14 +302,13 @@ httpRequest.on('headersReceive', (header) => { ...@@ -301,14 +302,13 @@ httpRequest.on('headersReceive', (header) => {
}); });
``` ```
### off\('headersReceive'\)<sup>8+</sup> ### off\('headersReceive'\)<sup>8+</sup>
off\(type: 'headersReceive', callback?: Callback<Object\>\): void off\(type: 'headersReceive', callback?: Callback<Object\>\): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -358,10 +358,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques ...@@ -358,10 +358,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. | | method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> | | extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is \[1,1000]. The default value is **1**. |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
## RequestMethod ## RequestMethod
...@@ -371,14 +375,14 @@ Defines an HTTP request method. ...@@ -371,14 +375,14 @@ Defines an HTTP request method.
| Name | Value | Description | | Name | Value | Description |
| :------ | ------- | :------------------ | | :------ | ------- | :------------------ |
| OPTIONS | OPTIONS | OPTIONS method.| | OPTIONS | "OPTIONS" | OPTIONS method.|
| GET | GET | GET method. | | GET | "GET" | GET method. |
| HEAD | HEAD | HEAD method. | | HEAD | "HEAD" | HEAD method. |
| POST | POST | POST method. | | POST | "POST" | POST method. |
| PUT | PUT | PUT method. | | PUT | "PUT" | PUT method. |
| DELETE | DELETE | DELETE method. | | DELETE | "DELETE" | DELETE method. |
| TRACE | TRACE | TRACE method. | | TRACE | "TRACE" | TRACE method. |
| CONNECT | CONNECT | CONNECT method.| | CONNECT | "CONNECT" | CONNECT method.|
## ResponseCode ## ResponseCode
...@@ -388,7 +392,7 @@ Enumerates the response codes for an HTTP request. ...@@ -388,7 +392,7 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description | | Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ | | ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. | | OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
...@@ -433,17 +437,171 @@ Defines the response to an HTTP request. ...@@ -433,17 +437,171 @@ Defines the response to an HTTP request.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| | result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. | | cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup>
createHttpResponseCache(cacheSize?: number): HttpResponseCache
Creates a default object to store responses to HTTP access requests.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.|
**Return value**
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.|
**Example**
```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```
## HttpResponseCache<sup>9+</sup>
Defines an object that stores the response to an HTTP request.
### flush<sup>9+</sup>
flush(callback: AsyncCallback\<void>): void
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
httpResponseCache.flush(err => {
if (err) {
console.log('flush fail');
return;
}
console.log('flush success');
});
```
### flush<sup>9+</sup>
flush(): Promise\<void>
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | Promise used to return the result.|
**Example**
```js
httpResponseCache.flush().then(() => {
console.log('flush success');
}).catch(err => {
console.log('flush fail');
});
```
### delete<sup>9+</sup>
delete(callback: AsyncCallback\<void>): void
Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
httpResponseCache.delete(err => {
if (err) {
console.log('delete fail');
return;
}
console.log('delete success');
});
```
### delete<sup>9+</sup>
delete(): Promise\<void>
Disables the cache and deletes the data in it. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
httpResponseCache.delete().then(() => {
console.log('delete success');
}).catch(err => {
console.log('delete fail');
});
```
## Error Codes ## Error Codes
| Error Code| Description | | Error Code| Description |
| ------ | ------------------------------------------------------------ | | ------ | ------------------------------------------------------------ |
| -1 | Incorrect parameters. | | -1 | Incorrect parameter. Check whether the number and type of parameters are correct. |
| 3 | Incorrect URL format. | | 3 | Incorrect URL format. Check whether the format and syntax of the URL are correct. |
| 4 | Built-in request function, protocol, or option not found during build. | | 4 | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions. |
| 5 | Unable to resolve the proxy. | | 5 | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 6 | Unable to resolve the host. | | 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. | | 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. |
## HttpDataType<sup>9+</sup>
Enumerates HTTP data types.
**System capability**: SystemCapability.Communication.NetStack
| Name| Value| Description |
| ------------------ | -- | ----------- |
| STRING | 0 | String type.|
| OBJECT | 1 | Object type. |
| ARRAY_BUFFER | 2 | Binary array type.|
## HttpProtocol<sup>9+</sup>
Enumerates HTTP protocol versions.
**System capability**: SystemCapability.Communication.NetStack
| Name | Description |
| :-------- | :----------- |
| HTTP1_1 | HTTP1.1 |
| HTTP2 | HTTP2 |
...@@ -16,7 +16,7 @@ import resourceManager from '@ohos.resourceManager'; ...@@ -16,7 +16,7 @@ import resourceManager from '@ohos.resourceManager';
## Instruction ## Instruction
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model.
For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../ability/context-userguide.md). For details about how to reference **context** in the stage model, see [Context in the Stage Model].
```ts ```ts
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
...@@ -1375,15 +1375,16 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ...@@ -1375,15 +1375,16 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
try { try {
this.context.resourceManager.getRawFd("test.xml", (error, value) => { this.context.resourceManager.getRawFd("test.xml", (error, value) => {
if (error != null) { if (error != null) {
console.log("error is " + error); console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
} else { } else {
let fd = value.fd; let fd = value.fd;
let offset = value.offset; let offset = value.offset;
let length = value.length; let length = value.length;
} }
}).catch(error => {
console.log("getRawFd callback error is " + error);
}); });
} catch (error) {
console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`)
};
``` ```
### getRawFd<sup>9+</sup> ### getRawFd<sup>9+</sup>
...@@ -1421,10 +1422,10 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ...@@ -1421,10 +1422,10 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
let offset = value.offset; let offset = value.offset;
let length = value.length; let length = value.length;
}).catch(error => { }).catch(error => {
console.log("getRawFd promise error is " + error); console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`);
}); });
} catch (error) { } catch (error) {
console.log("getRawFd promise error is " + error); console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}; };
``` ```
......
# Socket Connection # Socket Connection
>![](public_sys-resources/icon-note.gif) **NOTE:** > **NOTE**
>
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import socket from '@ohos.net.socket'; import socket from '@ohos.net.socket';
``` ```
...@@ -19,7 +18,7 @@ Creates a **UDPSocket** object. ...@@ -19,7 +18,7 @@ Creates a **UDPSocket** object.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :---------------------- | | :--------------------------------- | :---------------------- |
...@@ -28,7 +27,7 @@ Creates a **UDPSocket** object. ...@@ -28,7 +27,7 @@ Creates a **UDPSocket** object.
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
``` ```
...@@ -43,7 +42,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void ...@@ -43,7 +42,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -56,7 +55,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -56,7 +55,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
...@@ -74,7 +73,7 @@ bind\(address: NetAddress\): Promise<void\> ...@@ -74,7 +73,7 @@ bind\(address: NetAddress\): Promise<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -85,7 +84,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -85,7 +84,7 @@ Binds the IP address and port number. The port number can be specified or random
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :----------------------------------------- | | :-------------- | :----------------------------------------- |
...@@ -93,7 +92,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -93,7 +92,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1}); let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1});
promise .then(() => { promise .then(() => {
...@@ -112,7 +111,7 @@ Sends data over a UDPSocket connection. This API uses an asynchronous callback t ...@@ -112,7 +111,7 @@ Sends data over a UDPSocket connection. This API uses an asynchronous callback t
Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -125,7 +124,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -125,7 +124,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.send({ udp.send({
data:'Hello, server!', data:'Hello, server!',
...@@ -152,7 +151,7 @@ Sends data over a UDPSocket connection. This API uses a promise to return the re ...@@ -152,7 +151,7 @@ Sends data over a UDPSocket connection. This API uses a promise to return the re
Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -162,7 +161,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -162,7 +161,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------- | | :-------------- | :--------------------------------------------- |
...@@ -170,7 +169,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -170,7 +169,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.send({ let promise = udp.send({
data:'Hello, server!', data:'Hello, server!',
...@@ -194,7 +193,7 @@ close\(callback: AsyncCallback<void\>\): void ...@@ -194,7 +193,7 @@ close\(callback: AsyncCallback<void\>\): void
Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. Closes a UDPSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -206,7 +205,7 @@ Closes a UDPSocket connection. This API uses an asynchronous callback to return ...@@ -206,7 +205,7 @@ Closes a UDPSocket connection. This API uses an asynchronous callback to return
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.close(err => { udp.close(err => {
if (err) { if (err) {
...@@ -224,11 +223,11 @@ close\(\): Promise<void\> ...@@ -224,11 +223,11 @@ close\(\): Promise<void\>
Closes a UDPSocket connection. This API uses a promise to return the result. Closes a UDPSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :----------------------------------------- | | :-------------- | :----------------------------------------- |
...@@ -236,7 +235,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result. ...@@ -236,7 +235,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result.
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.close(); let promise = udp.close();
promise.then(() => { promise.then(() => {
...@@ -253,10 +252,10 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void ...@@ -253,10 +252,10 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -268,7 +267,7 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca ...@@ -268,7 +267,7 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
...@@ -293,14 +292,14 @@ getState\(\): Promise<SocketStateBase\> ...@@ -293,14 +292,14 @@ getState\(\): Promise<SocketStateBase\>
Obtains the status of the UDPSocket connection. This API uses a promise to return the result. Obtains the status of the UDPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :----------------------------------------------- | :----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
...@@ -308,7 +307,7 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur ...@@ -308,7 +307,7 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
...@@ -332,10 +331,10 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): voi ...@@ -332,10 +331,10 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): voi
Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -349,7 +348,7 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous ...@@ -349,7 +348,7 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
if (err) { if (err) {
...@@ -380,10 +379,10 @@ setExtraOptions\(options: UDPExtraOptions\): Promise<void\> ...@@ -380,10 +379,10 @@ setExtraOptions\(options: UDPExtraOptions\): Promise<void\>
Sets other properties of the UDPSocket connection. This API uses a promise to return the result. Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -393,7 +392,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re ...@@ -393,7 +392,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| | options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
...@@ -401,7 +400,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re ...@@ -401,7 +400,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}); let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1});
promise.then(() => { promise.then(() => {
...@@ -436,12 +435,12 @@ Enables listening for message receiving events of the UDPSocket connection. This ...@@ -436,12 +435,12 @@ Enables listening for message receiving events of the UDPSocket connection. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.on('message', value => { udp.on('message', value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
...@@ -455,7 +454,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So ...@@ -455,7 +454,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -464,18 +463,18 @@ Disables listening for message receiving events of the UDPSocket connection. Thi ...@@ -464,18 +463,18 @@ Disables listening for message receiving events of the UDPSocket connection. Thi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let callback = value =>{ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
udp.on('message', callback); udp.on('message', callback);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('message', callback); udp.off('message', callback);
udp.off('message'); udp.off('message');
``` ```
...@@ -493,12 +492,12 @@ Enables listening for data packet message events or close events of the UDPSocke ...@@ -493,12 +492,12 @@ Enables listening for data packet message events or close events of the UDPSocke
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **listening**: data packet message event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br /><br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.on('listening', () => { udp.on('listening', () => {
console.log("on listening success"); console.log("on listening success");
...@@ -515,7 +514,7 @@ off\(type: 'listening' | 'close', callback?: Callback<void\>\): void ...@@ -515,7 +514,7 @@ off\(type: 'listening' | 'close', callback?: Callback<void\>\): void
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -524,25 +523,25 @@ Disables listening for data packet message events or close events of the UDPSock ...@@ -524,25 +523,25 @@ Disables listening for data packet message events or close events of the UDPSock
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **listening**: data packet message event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. | | callback | Callback\<void\> | No | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{ let callback1 = () =>{
console.log("on listening, success"); console.log("on listening, success");
} }
udp.on('listening', callback1); udp.on('listening', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('listening', callback1); udp.off('listening', callback1);
udp.off('listening'); udp.off('listening');
let callback2 = () =>{ let callback2 = () =>{
console.log("on close, success"); console.log("on close, success");
} }
udp.on('close', callback2); udp.on('close', callback2);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('close', callback2); udp.off('close', callback2);
udp.off('close'); udp.off('close');
``` ```
...@@ -560,13 +559,13 @@ Enables listening for error events of the UDPSocket connection. This API uses an ...@@ -560,13 +559,13 @@ Enables listening for error events of the UDPSocket connection. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.on('error', err => { udp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err)) console.log("on error, err:" + JSON.stringify(err))
...@@ -580,7 +579,7 @@ off\(type: 'error', callback?: ErrorCallback\): void ...@@ -580,7 +579,7 @@ off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -589,18 +588,18 @@ Disables listening for error events of the UDPSocket connection. This API uses a ...@@ -589,18 +588,18 @@ Disables listening for error events of the UDPSocket connection. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. | | callback | ErrorCallback | No | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let callback = err =>{ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err)); console.log("on error, err:" + JSON.stringify(err));
} }
udp.on('error', callback); udp.on('error', callback);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('error', callback); udp.off('error', callback);
udp.off('error'); udp.off('error');
``` ```
...@@ -645,7 +644,7 @@ Defines other properties of the UDPSocket connection. ...@@ -645,7 +644,7 @@ Defines other properties of the UDPSocket connection.
## SocketStateBase ## SocketStateBase
Defines the status of the UDPSocket connection. Defines the status of the socket connection.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -657,7 +656,7 @@ Defines the status of the UDPSocket connection. ...@@ -657,7 +656,7 @@ Defines the status of the UDPSocket connection.
## SocketRemoteInfo ## SocketRemoteInfo
Defines information about the UDPSocket connection. Defines information about the socket connection.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -676,7 +675,7 @@ Creates a **TCPSocket** object. ...@@ -676,7 +675,7 @@ Creates a **TCPSocket** object.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :---------------------- | | :--------------------------------- | :---------------------- |
...@@ -684,7 +683,7 @@ Creates a **TCPSocket** object. ...@@ -684,7 +683,7 @@ Creates a **TCPSocket** object.
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
``` ```
...@@ -699,7 +698,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void ...@@ -699,7 +698,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -713,7 +712,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -713,7 +712,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
...@@ -731,7 +730,7 @@ bind\(address: NetAddress\): Promise<void\> ...@@ -731,7 +730,7 @@ bind\(address: NetAddress\): Promise<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -741,7 +740,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -741,7 +740,7 @@ Binds the IP address and port number. The port number can be specified or random
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :------------------------------------------------------- | | :-------------- | :------------------------------------------------------- |
...@@ -749,7 +748,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -749,7 +748,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => { promise.then(() => {
...@@ -766,7 +765,7 @@ connect\(options: TCPConnectOptions, callback: AsyncCallback<void\>\): void ...@@ -766,7 +765,7 @@ connect\(options: TCPConnectOptions, callback: AsyncCallback<void\>\): void
Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -779,7 +778,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -779,7 +778,7 @@ Sets up a connection to the specified IP address and port number. This API uses
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => { tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => {
if (err) { if (err) {
...@@ -797,7 +796,7 @@ connect\(options: TCPConnectOptions\): Promise<void\> ...@@ -797,7 +796,7 @@ connect\(options: TCPConnectOptions\): Promise<void\>
Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. Sets up a connection to the specified IP address and port number. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -807,7 +806,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -807,7 +806,7 @@ Sets up a connection to the specified IP address and port number. This API uses
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| | options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------------------- | | :-------------- | :--------------------------------------------------------- |
...@@ -815,7 +814,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -815,7 +814,7 @@ Sets up a connection to the specified IP address and port number. This API uses
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => { promise.then(() => {
...@@ -832,10 +831,10 @@ send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void ...@@ -832,10 +831,10 @@ send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void
Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -848,7 +847,7 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t ...@@ -848,7 +847,7 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => { promise.then(() => {
...@@ -874,10 +873,10 @@ send\(options: TCPSendOptions\): Promise<void\> ...@@ -874,10 +873,10 @@ send\(options: TCPSendOptions\): Promise<void\>
Sends data over a TCPSocket connection. This API uses a promise to return the result. Sends data over a TCPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -887,7 +886,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re ...@@ -887,7 +886,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| | options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :------------------------------------------------- | | :-------------- | :------------------------------------------------- |
...@@ -895,7 +894,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re ...@@ -895,7 +894,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise1.then(() => { promise1.then(() => {
...@@ -920,7 +919,7 @@ close\(callback: AsyncCallback<void\>\): void ...@@ -920,7 +919,7 @@ close\(callback: AsyncCallback<void\>\): void
Closes a TCPSocket connection. This API uses an asynchronous callback to return the result. Closes a TCPSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -933,7 +932,7 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return ...@@ -933,7 +932,7 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.close(err => { tcp.close(err => {
if (err) { if (err) {
...@@ -951,11 +950,11 @@ close\(\): Promise<void\> ...@@ -951,11 +950,11 @@ close\(\): Promise<void\>
Closes a TCPSocket connection. This API uses a promise to return the result. Closes a TCPSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :----------------------------------------- | | :-------------- | :----------------------------------------- |
...@@ -963,7 +962,7 @@ Closes a TCPSocket connection. This API uses a promise to return the result. ...@@ -963,7 +962,7 @@ Closes a TCPSocket connection. This API uses a promise to return the result.
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.close(); let promise = tcp.close();
promise.then(() => { promise.then(() => {
...@@ -978,12 +977,12 @@ promise.then(() => { ...@@ -978,12 +977,12 @@ promise.then(() => {
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
Obtains the remote address of a TCPSocket connection. This API uses an asynchronous callback to return the result. Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -995,7 +994,7 @@ Obtains the remote address of a TCPSocket connection. This API uses an asynchron ...@@ -995,7 +994,7 @@ Obtains the remote address of a TCPSocket connection. This API uses an asynchron
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => { promise.then(() => {
...@@ -1017,16 +1016,16 @@ promise.then(() => { ...@@ -1017,16 +1016,16 @@ promise.then(() => {
getRemoteAddress\(\): Promise<NetAddress\> getRemoteAddress\(\): Promise<NetAddress\>
Obtains the remote address of a TCPSocket connection. This API uses a promise to return the result. Obtains the remote address of a socket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------------------------------ | :------------------------------------------ | | :------------------------------------------ | :------------------------------------------ |
...@@ -1034,7 +1033,7 @@ Obtains the remote address of a TCPSocket connection. This API uses a promise to ...@@ -1034,7 +1033,7 @@ Obtains the remote address of a TCPSocket connection. This API uses a promise to
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise1.then(() => { promise1.then(() => {
...@@ -1057,10 +1056,10 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void ...@@ -1057,10 +1056,10 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1073,7 +1072,7 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca ...@@ -1073,7 +1072,7 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => { promise.then(() => {
...@@ -1097,14 +1096,14 @@ getState\(\): Promise<SocketStateBase\> ...@@ -1097,14 +1096,14 @@ getState\(\): Promise<SocketStateBase\>
Obtains the status of the TCPSocket connection. This API uses a promise to return the result. Obtains the status of the TCPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :----------------------------------------------- | :----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
...@@ -1113,7 +1112,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur ...@@ -1113,7 +1112,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => { promise.then(() => {
...@@ -1136,10 +1135,10 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): voi ...@@ -1136,10 +1135,10 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): voi
Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1152,7 +1151,7 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous ...@@ -1152,7 +1151,7 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => { promise.then(() => {
...@@ -1185,10 +1184,10 @@ setExtraOptions\(options: TCPExtraOptions\): Promise<void\> ...@@ -1185,10 +1184,10 @@ setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
Sets other properties of the TCPSocket connection. This API uses a promise to return the result. Sets other properties of the TCPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1198,7 +1197,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re ...@@ -1198,7 +1197,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| | options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
...@@ -1207,7 +1206,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re ...@@ -1207,7 +1206,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => { promise.then(() => {
...@@ -1245,12 +1244,12 @@ Enables listening for message receiving events of the TCPSocket connection. This ...@@ -1245,12 +1244,12 @@ Enables listening for message receiving events of the TCPSocket connection. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.on('message', value => { tcp.on('message', value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo) console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo)
...@@ -1264,7 +1263,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So ...@@ -1264,7 +1263,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1273,18 +1272,18 @@ Disables listening for message receiving events of the TCPSocket connection. Thi ...@@ -1273,18 +1272,18 @@ Disables listening for message receiving events of the TCPSocket connection. Thi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let callback = value =>{ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
tcp.on('message', callback); tcp.on('message', callback);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('message', callback); tcp.off('message', callback);
tcp.off('message'); tcp.off('message');
``` ```
...@@ -1302,13 +1301,13 @@ Enables listening for connection or close events of the TCPSocket connection. Th ...@@ -1302,13 +1301,13 @@ Enables listening for connection or close events of the TCPSocket connection. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.on('connect', () => { tcp.on('connect', () => {
console.log("on connect success") console.log("on connect success")
...@@ -1325,7 +1324,7 @@ off\(type: 'connect' | 'close', callback?: Callback<void\>\): void ...@@ -1325,7 +1324,7 @@ off\(type: 'connect' | 'close', callback?: Callback<void\>\): void
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1334,25 +1333,25 @@ Disables listening for connection or close events of the TCPSocket connection. T ...@@ -1334,25 +1333,25 @@ Disables listening for connection or close events of the TCPSocket connection. T
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. | | callback | Callback\<void\> | No | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{ let callback1 = () =>{
console.log("on connect success"); console.log("on connect success");
} }
tcp.on('connect', callback1); tcp.on('connect', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('connect', callback1); tcp.off('connect', callback1);
tcp.off('connect'); tcp.off('connect');
let callback2 = () =>{ let callback2 = () =>{
console.log("on close success"); console.log("on close success");
} }
tcp.on('close', callback2); tcp.on('close', callback2);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('close', callback2); tcp.off('close', callback2);
tcp.off('close'); tcp.off('close');
``` ```
...@@ -1370,12 +1369,12 @@ Enables listening for error events of the TCPSocket connection. This API uses an ...@@ -1370,12 +1369,12 @@ Enables listening for error events of the TCPSocket connection. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => { tcp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err)) console.log("on error, err:" + JSON.stringify(err))
...@@ -1389,7 +1388,7 @@ off\(type: 'error', callback?: ErrorCallback\): void ...@@ -1389,7 +1388,7 @@ off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1398,18 +1397,18 @@ Disables listening for error events of the TCPSocket connection. This API uses a ...@@ -1398,18 +1397,18 @@ Disables listening for error events of the TCPSocket connection. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. | | callback | ErrorCallback | No | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let callback = err =>{ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err)); console.log("on error, err:" + JSON.stringify(err));
} }
tcp.on('error', callback); tcp.on('error', callback);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('error', callback); tcp.off('error', callback);
tcp.off('error'); tcp.off('error');
``` ```
...@@ -1453,3 +1452,1080 @@ Defines other properties of the TCPSocket connection. ...@@ -1453,3 +1452,1080 @@ Defines other properties of the TCPSocket connection.
| sendBufferSize | number | No | Size of the send buffer, in bytes. | | sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. | | socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. |
## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket
Creates a **TLSSocket** object.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| [TLSSocket](#tlssocket9) | **TLSSocket** object.|
**Example**
```js
let tls = socket.constructTLSSocketInstance();
```
## TLSSocket<sup>9+</sup>
Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object.
### bind<sup>9+</sup>
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
Binds the IP address and port number. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation is successful, the result of binding the local IP address and port number is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
```
### bind<sup>9+</sup>
bind\(address: NetAddress\): Promise<void\>
Binds the IP address and port number. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
**Return value**
| Type | Description |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**Example**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### getState<sup>9+</sup>
getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result. If the operation is successful, the status of the TLSSocket connection is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
});
```
### getState<sup>9+</sup>
getState\(\): Promise<SocketStateBase\>
Obtains the status of the TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :----------------------------------------------- | :----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.getState();
promise.then(() => {
console.log('getState success');
}).catch(err => {
console.log('getState fail');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation is successful, the result of setting other properties of the TCPSocket connection is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
},err => {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | ---------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the TLSSocket connection.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "192.168.xx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions): Promise\<void>
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | --------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.|
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "xxxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddress fail');
return;
}
console.log('getRemoteAddress success:' + JSON.stringify(data));
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(\): Promise\<NetAddress>
Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :------------------------------------------ | :------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
let promise = tls.getRemoteAddress();
promise.then(() => {
console.log('getRemoteAddress success');
}).catch(err => {
console.log('getRemoteAddress fail');
});
```
### getCertificate<sup>9+</sup>
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCertificate((err, data) => {
if (err) {
console.log("getCertificate callback error = " + err);
} else {
console.log("getCertificate callback = " + data);
}
});
```
### getCertificate<sup>9+</sup>
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getRemoteCertificate((err, data) => {
if (err) {
console.log("getRemoteCertificate callback error = " + err);
} else {
console.log("getRemoteCertificate callback = " + data);
}
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getRemoteCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getProtocol<sup>9+</sup>
getProtocol(callback: AsyncCallback\<string>): void
Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<string> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getProtocol((err, data) => {
if (err) {
console.log("getProtocol callback error = " + err);
} else {
console.log("getProtocol callback = " + data);
}
});
```
### getProtocol<sup>9+</sup>
getProtocol():Promise\<string>
Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<string> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getProtocol().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(callback: AsyncCallback\<Array\<string>>): void
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCipherSuite((err, data) => {
if (err) {
console.log("getCipherSuite callback error = " + err);
} else {
console.log("getCipherSuite callback = " + data);
}
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(): Promise\<Array\<string>>
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| ---------------------- | --------------------- |
| Promise\<Array\<string>> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCipherSuite().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string>>): void
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getSignatureAlgorithms((err, data) => {
if (err) {
console.log("getSignatureAlgorithms callback error = " + err);
} else {
console.log("getSignatureAlgorithms callback = " + data);
}
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(): Promise\<Array\<string>>
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| ---------------------- | -------------------- |
| Promise\<Array\<string>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getSignatureAlgorithms().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### send<sup>9+</sup>
send(data: string, callback: AsyncCallback\<void>): void
Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------|
| data | string | Yes | Data content of the message to send. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
tls.send("xxxx", (err) => {
if (err) {
console.log("send callback error = " + err);
} else {
console.log("send success");
}
});
```
### send<sup>9+</sup>
send(data: string): Promise\<void>
Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------|
| data | string | Yes | Data content of the message to send. |
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
tls.send("xxxx").then(() =>{
console.log("send success");
}).catch(err => {
console.error(err);
});
```
### close<sup>9+</sup>
close(callback: AsyncCallback\<void>): void
Closes a TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
});
```
### close<sup>9+</sup>
close(): Promise\<void>
Closes a TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
tls.close().then(() =>{
console.log("close success");
}).catch(err => {
console.error(err);
});
```
## TLSConnectOptions<sup>9+</sup>
Defines TLS connection options.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | Yes | Gateway address. |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.|
| ALPNProtocols | Array\<string> | No| Application Layer Protocol Negotiation (ALPN) protocols. |
## TLSSecureOptions<sup>9+</sup>
Defines TLS security options. The CA certificate is mandatory, and other parameters are optional. When **cert** (local certificate) and **key** (private key) are not empty, the two-way authentication mode is enabled. If **cert** or **key** is empty, one-way authentication is enabled.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
| ca | string \| Array\<string> | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.|
| cert | string | No| Digital certificate of the local client. |
| key | string | No| Private key of the local digital certificate. |
| passwd | string | No| Password for reading the private key. |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | No| TLS protocol version. |
| useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. |
| signatureAlgorithms | string | No| Signing algorithm used during communication. |
| cipherSuite | string | No| Cipher suite used during communication. |
## Protocol<sup>9+</sup>
Enumerates TLS protocol versions.
**System capability**: SystemCapability.Communication.NetStack
| Name | Value | Description |
| --------- | --------- |------------------ |
| TLSv12 | "TLSv1.2" | TLSv1.2.|
| TLSv13 | "TLSv1.3" | TLSv1.3.|
## X509CertRawData<sup>9+</sup>
Defines the certificate raw data.
**System capability**: SystemCapability.Communication.NetStack
| Type | Description |
| --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | Data and encoding format of the certificate.|
# Geographic Location # Geographic Location
> **NOTE** > **NOTE**
> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.geolocation`](js-apis-geolocation.md).
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead.
## Modules to Import ## Modules to Import
...@@ -18,15 +18,12 @@ import geolocation from '@system.geolocation'; ...@@ -18,15 +18,12 @@ import geolocation from '@system.geolocation';
ohos.permission.LOCATION ohos.permission.LOCATION
## geolocation.getLocation<sup>(deprecated) </sup> ## geolocation.getLocation
getLocation(Object): void getLocation(Object): void
Obtains the geographic location. Obtains the geographic location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation).
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
...@@ -77,15 +74,12 @@ export default { ...@@ -77,15 +74,12 @@ export default {
``` ```
## geolocation.getLocationType<sup>(deprecated) </sup> ## geolocation.getLocationType
getLocationType(Object): void getLocationType(Object): void
Obtains the supported location types. Obtains the supported location types.
> **NOTE**
> This API is deprecated since API version 9.
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
...@@ -120,15 +114,12 @@ export default { ...@@ -120,15 +114,12 @@ export default {
``` ```
## geolocation.subscribe<sup>(deprecated) </sup> ## geolocation.subscribe
subscribe(Object): void subscribe(Object): void
Listens to the geographical location. If this method is called multiple times, the last call takes effect. Listens to the geographical location. If this method is called multiple times, the last call takes effect.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange).
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Parameters** **Parameters**
...@@ -175,15 +166,12 @@ export default { ...@@ -175,15 +166,12 @@ export default {
``` ```
## geolocation.unsubscribe<sup>(deprecated) </sup> ## geolocation.unsubscribe
unsubscribe(): void unsubscribe(): void
Cancels listening to the geographical location. Cancels listening to the geographical location.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange).
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Example** **Example**
...@@ -197,15 +185,12 @@ export default { ...@@ -197,15 +185,12 @@ export default {
``` ```
## geolocation.getSupportedCoordTypes<sup>(deprecated) </sup> ## geolocation.getSupportedCoordTypes
getSupportedCoordTypes(): Array&lt;string&gt; getSupportedCoordTypes(): Array&lt;string&gt;
Obtains coordinate system types supported by the device. Obtains coordinate system types supported by the device.
> **NOTE**
> This API is deprecated since API version 9.
**System capability**: SystemCapability.Location.Location.Lite **System capability**: SystemCapability.Location.Location.Lite
**Return Value** **Return Value**
......
...@@ -348,7 +348,7 @@ let ret = usb.getFileDescriptor(devicepipe); ...@@ -348,7 +348,7 @@ let ret = usb.getFileDescriptor(devicepipe);
## usb.controlTransfer ## usb.controlTransfer
controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise&lt;number&gt; controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout?: number): Promise&lt;number&gt;
Performs control transfer. Performs control transfer.
...@@ -361,7 +361,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -361,7 +361,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| contrlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.| | controlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| | timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value** **Return value**
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
| Ability | An abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule the application. An application can contain one or more **Ability** instances.| | Ability | An abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule the application. An application can contain one or more **Ability** instances.|
| FA | Feature Ability, an ability that provides a UI for user interaction in the ability framework of the FA model. The FA supports only the Page ability template.| | FA | Feature Ability, an ability that provides a UI for user interaction in the ability framework of the FA model. The FA supports only the Page ability template.|
| PA | Particle Ability, an ability that does not have a UI in the ability framework of the FA model. It provides services and support for FAs. For example, a PA can function as a background service to provide computing power or as a data store to provide data access capabilities. The PA supports three types of templates: Service, Data, and Form ability templates.| | PA | Particle Ability, an ability that does not have a UI in the ability framework of the FA model. It provides services and support for FAs. For example, a PA can function as a background service to provide computing power or as a data store to provide data access capabilities. The PA supports three types of templates: Service, Data, and Form ability templates.|
| FA model | One of the two ability framework models. The FA model applies to application development using API version 8 and earlier versions. The FA model provides FAs and PAs. The FA supports the Page ability template, and the PA supports the Service, Data, and Form ability templates. For details, see [FA Model Overview](../../application-dev/ability/fa-brief.md).| | FA model | One of the two ability framework models. The FA model applies to application development using API version 8 and earlier versions. The FA model provides FAs and PAs. The FA supports the Page ability template, and the PA supports the Service, Data, and Form ability templates. For details, see [FA Model Overview](../../application-dev/ability-deprecated/fa-brief.md).|
| Stage model| One of the two ability framework models. The stage model applies to application development using API version 9 and later versions. The stage model provides abilities and Extension abilities. The latter ones are extended to Service Extension abilities, Form Extension abilities, Data Share Extension abilities, and more.| | Stage model| One of the two ability framework models. The stage model applies to application development using API version 9 and later versions. The stage model provides abilities and Extension abilities. The latter ones are extended to Service Extension abilities, Form Extension abilities, Data Share Extension abilities, and more.|
### Function ### Function
......
...@@ -49,7 +49,7 @@ ...@@ -49,7 +49,7 @@
```js ```js
try { try {
I18n.System.setSystemLanguage("en"); // 将系统语言设置为 "en" I18n.System.setSystemLanguage("en"); // 将系统语言设置为 "en"
var language = I18n.System.getSystemLanguage(); // language = "en" let language = I18n.System.getSystemLanguage(); // language = "en"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -63,7 +63,7 @@ ...@@ -63,7 +63,7 @@
```js ```js
try { try {
I18n.System.setSystemRegion("CN"); // 将系统国家设置为 "CN" I18n.System.setSystemRegion("CN"); // 将系统国家设置为 "CN"
var region = I18n.System.getSystemRegion(); // region = "CN" let region = I18n.System.getSystemRegion(); // region = "CN"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -77,7 +77,7 @@ ...@@ -77,7 +77,7 @@
```js ```js
try { try {
I18n.System.setSystemLocale("zh-Hans-CN"); // 将系统Locale设置为 "zh-Hans-CN" I18n.System.setSystemLocale("zh-Hans-CN"); // 将系统Locale设置为 "zh-Hans-CN"
var locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN" let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -88,9 +88,8 @@ ...@@ -88,9 +88,8 @@
调用isRTL接口获取Locale的语言是否为从右到左语言。 调用isRTL接口获取Locale的语言是否为从右到左语言。
```js ```js
try { try {
var rtl = I18n.isRTL("zh-CN"); // rtl = false let rtl = I18n.isRTL("zh-CN"); // rtl = false
rtl = I18n.isRTL("ar"); // rtl = true rtl = I18n.isRTL("ar"); // rtl = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
...@@ -103,10 +102,9 @@ ...@@ -103,10 +102,9 @@
调用is24HourClock接口来判断当前是否打开系统24小时制设置。 调用is24HourClock接口来判断当前是否打开系统24小时制设置。
```js ```js
try { try {
I18n.System.set24HourClock(true); I18n.System.set24HourClock(true);
var hourClock = I18n.System.is24HourClock(); // hourClock = true let hourClock = I18n.System.is24HourClock(); // hourClock = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -117,12 +115,11 @@ ...@@ -117,12 +115,11 @@
调用getDisplayLanguage接口获取某一语言的本地化表示。其中,language表示待本地化显示的语言,locale表示本地化的Locale,sentenceCase结果是否需要首字母大写。 调用getDisplayLanguage接口获取某一语言的本地化表示。其中,language表示待本地化显示的语言,locale表示本地化的Locale,sentenceCase结果是否需要首字母大写。
```js ```js
try { try {
var language = "en"; let language = "en";
var locale = "zh-CN"; let locale = "zh-CN";
var sentenceCase = false; let sentenceCase = false;
var localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "英语" let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "英语"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -133,12 +130,11 @@ ...@@ -133,12 +130,11 @@
调用getDisplayCountry接口获取某一国家的本地化表示。其中,country表示待本地化显示的国家,locale表示本地化的Locale,sentenceCase结果是否需要首字母大写。 调用getDisplayCountry接口获取某一国家的本地化表示。其中,country表示待本地化显示的国家,locale表示本地化的Locale,sentenceCase结果是否需要首字母大写。
```js ```js
try { try {
var country = "US"; let country = "US";
var locale = "zh-CN"; let locale = "zh-CN";
var sentenceCase = false; let sentenceCase = false;
var localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "美国" let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "美国"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -151,8 +147,8 @@ ...@@ -151,8 +147,8 @@
```js ```js
try { try {
var languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"] let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"]
var countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 共240个国家和地区 let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 共240个国家和地区
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -164,7 +160,7 @@ ...@@ -164,7 +160,7 @@
```js ```js
try { try {
var isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -181,10 +177,10 @@ ...@@ -181,10 +177,10 @@
```js ```js
try { try {
I18n.System.addPreferredLanguage("en-GB", 0); // 将"en-GB"设置为系统偏好语言列表的第一个语言 I18n.System.addPreferredLanguage("en-GB", 0); // 将"en-GB"设置为系统偏好语言列表的第一个语言
var list = I18n.System.getPreferredLanguageList(); // 获取当前系统偏好语言列表 list = ["en-GB", ...] let list = I18n.System.getPreferredLanguageList(); // 获取当前系统偏好语言列表 list = ["en-GB", ...]
I18n.System.removePreferredLanguage(list.length - 1); // 移除当前系统偏好语言列表中的最后一个偏好语言 I18n.System.removePreferredLanguage(list.length - 1); // 移除当前系统偏好语言列表中的最后一个偏好语言
var firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB" let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB"
var appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // 当应用中包含 "en-GB"资源时,应用偏好语言为"en-GB" let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // 当应用中包含 "en-GB"资源时,应用偏好语言为"en-GB"
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -199,7 +195,7 @@ ...@@ -199,7 +195,7 @@
```js ```js
try { try {
I18n.System.setUsingLocalDigit(true); // 打开本地化数字开关 I18n.System.setUsingLocalDigit(true); // 打开本地化数字开关
var status = I18n.System.getUsingLocalDigit(); // status = true let status = I18n.System.getUsingLocalDigit(); // status = true
} catch(error) { } catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
} }
...@@ -239,7 +235,7 @@ try { ...@@ -239,7 +235,7 @@ try {
调用getCalendar接口获取指定locale和type的时区对象(i18n为导入的模块)。其中,type表示合法的日历类型,目前合法的日历类型包括:"buddhist", "chinese", "coptic", "ethiopic", "hebrew", "gregory", "indian", "islamic_civil", "islamic_tbla", "islamic_umalqura", "japanese", "persian"。当type没有给出时,采用区域默认的日历类型。 调用getCalendar接口获取指定locale和type的时区对象(i18n为导入的模块)。其中,type表示合法的日历类型,目前合法的日历类型包括:"buddhist", "chinese", "coptic", "ethiopic", "hebrew", "gregory", "indian", "islamic_civil", "islamic_tbla", "islamic_umalqura", "japanese", "persian"。当type没有给出时,采用区域默认的日历类型。
```js ```js
var calendar = I18n.getCalendar("zh-CN", "chinese"); // 创建中文农历日历 let calendar = I18n.getCalendar("zh-CN", "chinese"); // 创建中文农历日历
``` ```
3. 设置日历对象的时间。 3. 设置日历对象的时间。
...@@ -247,9 +243,9 @@ try { ...@@ -247,9 +243,9 @@ try {
调用setTime接口设置日历对象的时间。setTime接口接收两种类型的参数。一种是传入一个Date对象,另一种是传入一个数值表示从1970.1.1 00:00:00 GMT逝去的毫秒数。 调用setTime接口设置日历对象的时间。setTime接口接收两种类型的参数。一种是传入一个Date对象,另一种是传入一个数值表示从1970.1.1 00:00:00 GMT逝去的毫秒数。
```js ```js
var date1 = new Date(); let date1 = new Date();
calendar.setTime(date1); calendar.setTime(date1);
var date2 = 1000; let date2 = 1000;
calendar.setTime(date2); calendar.setTime(date2);
``` ```
...@@ -267,7 +263,7 @@ try { ...@@ -267,7 +263,7 @@ try {
```js ```js
calendar.setTimeZone("Asia/Shanghai"); calendar.setTimeZone("Asia/Shanghai");
var timezone = calendar.getTimeZone(); // timezone = "China Standard Time" let timezone = calendar.getTimeZone(); // timezone = "China Standard Time"
``` ```
6. 设置、获取日历对象的一周起始日。 6. 设置、获取日历对象的一周起始日。
...@@ -276,7 +272,7 @@ try { ...@@ -276,7 +272,7 @@ try {
```js ```js
calendar.setFirstDayOfWeek(1); calendar.setFirstDayOfWeek(1);
var firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1
``` ```
7. 设置、获取日历对象第一周的最小天数。 7. 设置、获取日历对象第一周的最小天数。
...@@ -284,14 +280,14 @@ try { ...@@ -284,14 +280,14 @@ try {
```js ```js
calendar.setMinimalDaysInFirstWeek(3); calendar.setMinimalDaysInFirstWeek(3);
var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3
``` ```
8. 获取日历对象的本地化显示。 8. 获取日历对象的本地化显示。
调用getDisplayName来获取日历对象的本地化显示。 调用getDisplayName来获取日历对象的本地化显示。
```js ```js
var localizedName = calendar.getDisplayName("zh-CN"); // localizedName = "农历" let localizedName = calendar.getDisplayName("zh-CN"); // localizedName = "农历"
``` ```
9. 判断某一个日期是否为周末。 9. 判断某一个日期是否为周末。
...@@ -299,8 +295,8 @@ try { ...@@ -299,8 +295,8 @@ try {
调用isWeekend接口来判断输入的Date是否为周末。 调用isWeekend接口来判断输入的Date是否为周末。
```js ```js
var date = new Date(2022, 12, 12, 12, 12, 12); let date = new Date(2022, 12, 12, 12, 12, 12);
var weekend = calendar.isWeekend(date); // weekend = false let weekend = calendar.isWeekend(date); // weekend = false
``` ```
## 电话号码格式化 ## 电话号码格式化
...@@ -329,7 +325,7 @@ try { ...@@ -329,7 +325,7 @@ try {
调用PhoneNumberFormat的构造函数来实例化电话号码格式化对象,需要传入电话号码的国家代码及格式化选项。其中,格式化选项是可选的,包括style选项,该选项的取值包括:"E164", "INTERNATIONAL", "NATIONAL", "RFC3966"。 调用PhoneNumberFormat的构造函数来实例化电话号码格式化对象,需要传入电话号码的国家代码及格式化选项。其中,格式化选项是可选的,包括style选项,该选项的取值包括:"E164", "INTERNATIONAL", "NATIONAL", "RFC3966"。
```js ```js
var phoneNumberFormat = new I18n.PhoneNumberFormat("CN", {type: "E164"}); let phoneNumberFormat = new I18n.PhoneNumberFormat("CN", {type: "E164"});
``` ```
3. 判断电话号码格式是否正确。 3. 判断电话号码格式是否正确。
...@@ -337,7 +333,7 @@ try { ...@@ -337,7 +333,7 @@ try {
调用isValidNumber接口来判断输入的电话号码的格式是否正确。 调用isValidNumber接口来判断输入的电话号码的格式是否正确。
```js ```js
var validNumber = phoneNumberFormat.isValidNumber("15812341234"); // validNumber = true let validNumber = phoneNumberFormat.isValidNumber("15812341234"); // validNumber = true
``` ```
4. 电话号码格式化。 4. 电话号码格式化。
...@@ -345,7 +341,7 @@ try { ...@@ -345,7 +341,7 @@ try {
调用电话号码格式化对象的format接口来对输入的电话号码进行格式化。 调用电话号码格式化对象的format接口来对输入的电话号码进行格式化。
```js ```js
var formattedNumber = phoneNumberFormat.format("15812341234"); // formattedNumber = "+8615812341234" let formattedNumber = phoneNumberFormat.format("15812341234"); // formattedNumber = "+8615812341234"
``` ```
## 度量衡转换 ## 度量衡转换
...@@ -371,12 +367,12 @@ try { ...@@ -371,12 +367,12 @@ try {
调用[unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9)接口实现度量衡单位转换,并进行格式化显示的功能。 调用[unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9)接口实现度量衡单位转换,并进行格式化显示的功能。
```js ```js
var fromUnit = {unit: "cup", measureSystem: "US"}; let fromUnit = {unit: "cup", measureSystem: "US"};
var toUnit = {unit: "liter", measureSystem: "SI"}; let toUnit = {unit: "liter", measureSystem: "SI"};
var number = 1000; let number = 1000;
var locale = "en-US"; let locale = "en-US";
var style = "long"; let style = "long";
var converttedUnit = I18n.I18NUtil.unitConvert(fromUnit, toUnit, number, locale, style); // converttedUnit = "236.588 liters" let converttedUnit = I18n.I18NUtil.unitConvert(fromUnit, toUnit, number, locale, style); // converttedUnit = "236.588 liters"
``` ```
## 字母表索引 ## 字母表索引
...@@ -406,7 +402,7 @@ try { ...@@ -406,7 +402,7 @@ try {
```js ```js
var indexUtil = I18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
``` ```
3. 获取索引列表。 3. 获取索引列表。
...@@ -414,7 +410,7 @@ try { ...@@ -414,7 +410,7 @@ try {
调用getIndexList接口来获取当前Locale对应的字母表索引列表。 调用getIndexList接口来获取当前Locale对应的字母表索引列表。
```js ```js
var indexList = indexUtil.getIndexList(); // indexList = ["...", "A", "B", "C", ..., "X", "Y", "Z", "..."] let indexList = indexUtil.getIndexList(); // indexList = ["...", "A", "B", "C", ..., "X", "Y", "Z", "..."]
``` ```
4. 增加新的索引。 4. 增加新的索引。
...@@ -430,8 +426,8 @@ try { ...@@ -430,8 +426,8 @@ try {
调用getIndex接口来获取某一字符串对应的字母表索引。 调用getIndex接口来获取某一字符串对应的字母表索引。
```js ```js
var text = "access index"; let text = "access index";
var index = indexUtil.getIndex(text); // index = "A" let index = indexUtil.getIndex(text); // index = "A"
``` ```
## 获取文本断点位置 ## 获取文本断点位置
...@@ -466,8 +462,8 @@ try { ...@@ -466,8 +462,8 @@ try {
调用getLineInstance接口来实例化断行对象。 调用getLineInstance接口来实例化断行对象。
```js ```js
var locale = "en-US" let locale = "en-US"
var breakIterator = I18n.getLineInstance(locale); let breakIterator = I18n.getLineInstance(locale);
``` ```
3. 设置、访问要断行处理的文本。 3. 设置、访问要断行处理的文本。
...@@ -475,9 +471,9 @@ try { ...@@ -475,9 +471,9 @@ try {
调用setLineBreakText接口和getLineBreakText接口来设置、访问要断行处理的文本。 调用setLineBreakText接口和getLineBreakText接口来设置、访问要断行处理的文本。
```js ```js
var text = "Apple is my favorite fruit"; let text = "Apple is my favorite fruit";
breakIterator.setLineBreakText(text); breakIterator.setLineBreakText(text);
var breakText = breakIterator.getLineBreakText(); // breakText = "Apple is my favorite fruit" let breakText = breakIterator.getLineBreakText(); // breakText = "Apple is my favorite fruit"
``` ```
4. 获取断行对象当前的位置。 4. 获取断行对象当前的位置。
...@@ -485,7 +481,7 @@ try { ...@@ -485,7 +481,7 @@ try {
调用current接口来获取断行对象在当前处理文本中的位置。 调用current接口来获取断行对象在当前处理文本中的位置。
```js ```js
var pos = breakIterator.current(); // pos = 0 let pos = breakIterator.current(); // pos = 0
``` ```
5. 设置断行对象的位置。 5. 设置断行对象的位置。
...@@ -493,15 +489,15 @@ try { ...@@ -493,15 +489,15 @@ try {
系统提供了很多接口可以用于调整断行对象在处理文本中的位置,包括first, last, next, previous, following。 系统提供了很多接口可以用于调整断行对象在处理文本中的位置,包括first, last, next, previous, following。
```js ```js
var firstPos = breakIterator.first(); // 将断行对象设置到第一个分割点的位置,即文本的起始位置;firstPos = 0 let firstPos = breakIterator.first(); // 将断行对象设置到第一个分割点的位置,即文本的起始位置;firstPos = 0
var lastPos = breakIterator.last(); // 将断行对象设置到最后一个分割点的位置,即文本末尾的下一个位置;lastPos = 26 let lastPos = breakIterator.last(); // 将断行对象设置到最后一个分割点的位置,即文本末尾的下一个位置;lastPos = 26
// 将断行对象向前或向后移动一定数量的分割点。 // 将断行对象向前或向后移动一定数量的分割点。
// 当传入正数时,向后移动;当传入负数时,向前移动;当未传入数值时,则向后移动一个位置; // 当传入正数时,向后移动;当传入负数时,向前移动;当未传入数值时,则向后移动一个位置;
// 当移动超出了文本的长度范围,则返回-1; // 当移动超出了文本的长度范围,则返回-1;
var nextPos = breakIterator.next(-2); // nextPos = 12 let nextPos = breakIterator.next(-2); // nextPos = 12
var previousPos = breakIterator.previous(); // 将断行对象向前移动向前移动一个分割点,当超出文本长度范围时返回-1; previousPos = 9 let previousPos = breakIterator.previous(); // 将断行对象向前移动向前移动一个分割点,当超出文本长度范围时返回-1; previousPos = 9
// 将断行对象移动到offset指定位置的后面一个分割点。如果offset所指定的位置的下一个分割点超出了文本的长度范围,则返回-1; // 将断行对象移动到offset指定位置的后面一个分割点。如果offset所指定的位置的下一个分割点超出了文本的长度范围,则返回-1;
var followingPos = breakIterator.following(10); // followingPos = 12 let followingPos = breakIterator.following(10); // followingPos = 12
``` ```
6. 判断某个位置是否为分割点。 6. 判断某个位置是否为分割点。
...@@ -509,7 +505,7 @@ try { ...@@ -509,7 +505,7 @@ try {
调用isBoundary接口来判断一个接口是否为分割点;如果该位置是分割点,则返回true,并且将断行对象移动到该位置;如果该位置不是分割点,则返回false,并且将断行对象移动到该位置后的一个分割点。 调用isBoundary接口来判断一个接口是否为分割点;如果该位置是分割点,则返回true,并且将断行对象移动到该位置;如果该位置不是分割点,则返回false,并且将断行对象移动到该位置后的一个分割点。
```js ```js
var isboundary = breakIterator.isBoundary(5); // isboundary = false let isboundary = breakIterator.isBoundary(5); // isboundary = false
``` ```
## 获取时区 ## 获取时区
...@@ -543,16 +539,16 @@ try { ...@@ -543,16 +539,16 @@ try {
调用getTimeZone接口来获取时区对象。 调用getTimeZone接口来获取时区对象。
```js ```js
var timezone = I18n.getTimeZone(); // 使用默认参数可以获取系统时区对象。 let timezone = I18n.getTimeZone(); // 使用默认参数可以获取系统时区对象。
``` ```
获取时区ID、本地化显示、时区偏移量、某一时刻的时区偏移量信息。 获取时区ID、本地化显示、时区偏移量、某一时刻的时区偏移量信息。
```js ```js
var timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai"
var timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "中国标准时间" let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "中国标准时间"
var rawOffset = timezone.getRawOffset(); // rawOffset = 28800000 let rawOffset = timezone.getRawOffset(); // rawOffset = 28800000
var offset = timezone.getOffset(new Date()); // offset = 28800000 let offset = timezone.getOffset(new Date().getTime()); // offset = 28800000
``` ```
3. 获取系统支持的时区ID。 3. 获取系统支持的时区ID。
...@@ -561,9 +557,9 @@ try { ...@@ -561,9 +557,9 @@ try {
时区ID列表中的时区ID可以作为getTimeZone接口的参数,来创建TimeZone对象。 时区ID列表中的时区ID可以作为getTimeZone接口的参数,来创建TimeZone对象。
```js ```js
var timezoneIDs = I18n.TimeZone.getAvailableIDs(); // timezoneIDs = ["America/Adak", ...],共包含24个时区ID let timezoneIDs = I18n.TimeZone.getAvailableIDs(); // timezoneIDs = ["America/Adak", ...],共包含24个时区ID
var timezone = I18n.getTimeZone(timezoneIDs[0]); let timezone = I18n.getTimeZone(timezoneIDs[0]);
var timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "夏威夷-阿留申时间" let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "夏威夷-阿留申时间"
``` ```
4. 获取系统支持的时区城市ID。 4. 获取系统支持的时区城市ID。
...@@ -573,10 +569,10 @@ try { ...@@ -573,10 +569,10 @@ try {
调用getTimezoneFromCity接口基于时区城市ID创建时区对象。 调用getTimezoneFromCity接口基于时区城市ID创建时区对象。
```js ```js
var zoneCityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); // ["Auckland", "Magadan", ...] let zoneCityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); // ["Auckland", "Magadan", ...]
var cityDisplayName = I18n.TimeZone.getCityDisplayName(zoneCityIDs[0], "zh-Hans"); // cityDisplayName = "奥克兰(新西兰)" let cityDisplayName = I18n.TimeZone.getCityDisplayName(zoneCityIDs[0], "zh-Hans"); // cityDisplayName = "奥克兰(新西兰)"
var timezone = I18n.TimeZone.getTimezoneFromCity(zoneCityIDs[0]); let timezone = I18n.TimeZone.getTimezoneFromCity(zoneCityIDs[0]);
var timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "新西兰时间" let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "新西兰时间"
``` ```
## 获取音译对象 ## 获取音译对象
...@@ -605,7 +601,7 @@ try { ...@@ -605,7 +601,7 @@ try {
每个ID的格式为 source-destination,例如 ASCII-Latin,表示将ASCII转换为Latin的音译ID。 每个ID的格式为 source-destination,例如 ASCII-Latin,表示将ASCII转换为Latin的音译ID。
```js ```js
var ids = I18n.Transliterator.getAvailableIDs(); // ids = ["ASCII-Latin", "Accents-Any", ... ],共支持671个语言 let ids = I18n.Transliterator.getAvailableIDs(); // ids = ["ASCII-Latin", "Accents-Any", ... ],共支持671个语言
``` ```
3. 创建音译对象,获取音译字符串。 3. 创建音译对象,获取音译字符串。
...@@ -614,8 +610,8 @@ try { ...@@ -614,8 +610,8 @@ try {
调用transform接口,获取音译字符串。 调用transform接口,获取音译字符串。
```js ```js
var transliterator = I18n.Transliterator.getInstance("Any-Latn"); // Any-Latn表示将任意文本转换为Latn文本 let transliterator = I18n.Transliterator.getInstance("Any-Latn"); // Any-Latn表示将任意文本转换为Latn文本
var transformText = transliterator.transform("你好"); // transformText = "nǐ hǎo " let transformText = transliterator.transform("你好"); // transformText = "nǐ hǎo "
``` ```
## 字符类型判断 ## 字符类型判断
...@@ -649,56 +645,56 @@ try { ...@@ -649,56 +645,56 @@ try {
判断字符是否是数字。 判断字符是否是数字。
```js ```js
var isDigit = I18n.Unicode.isDigit("1"); // isDigit = true let isDigit = I18n.Unicode.isDigit("1"); // isDigit = true
isDigit = I18n.Unicode.isDigit("a"); // isDigit = false isDigit = I18n.Unicode.isDigit("a"); // isDigit = false
``` ```
判断字符是否是空格符。 判断字符是否是空格符。
```js ```js
var isSpaceChar = I18n.Unicode.isSpaceChar(" "); // isSpaceChar = true let isSpaceChar = I18n.Unicode.isSpaceChar(" "); // isSpaceChar = true
isSpaceChar = I18n.Unicode.isSpaceChar("\n"); // isSpaceChar = false isSpaceChar = I18n.Unicode.isSpaceChar("\n"); // isSpaceChar = false
``` ```
判断字符是否是空白符。 判断字符是否是空白符。
```js ```js
var isWhitespace = I18n.Unicode.isWhitespace(" "); // isWhitespace = true let isWhitespace = I18n.Unicode.isWhitespace(" "); // isWhitespace = true
isWhitespace = I18n.Unicode.isWhitespace("\n"); // isWhitespace = true isWhitespace = I18n.Unicode.isWhitespace("\n"); // isWhitespace = true
``` ```
判断字符是否是从左到右书写的文字。 判断字符是否是从左到右书写的文字。
```js ```js
var isRTL = I18n.Unicode.isRTL("مرحبًا"); // isRTL = true,阿拉伯语的文字是从左到右书写的文字 let isRTL = I18n.Unicode.isRTL("مرحبًا"); // isRTL = true,阿拉伯语的文字是从左到右书写的文字
isRTL = I18n.Unicode.isRTL("a"); // isRTL = false isRTL = I18n.Unicode.isRTL("a"); // isRTL = false
``` ```
判断字符是否是表意文字。 判断字符是否是表意文字。
```js ```js
var isIdeograph = I18n.Unicode.isIdeograph("你好"); // isIdeograph = true let isIdeograph = I18n.Unicode.isIdeograph("你好"); // isIdeograph = true
isIdeograph = I18n.Unicode.isIdeograph("a"); // isIdeograph = false isIdeograph = I18n.Unicode.isIdeograph("a"); // isIdeograph = false
``` ```
判断字符是否是字母。 判断字符是否是字母。
```js ```js
var isLetter = I18n.Unicode.isLetter("a"); // isLetter = true let isLetter = I18n.Unicode.isLetter("a"); // isLetter = true
isLetter = I18n.Unicode.isLetter("."); // isLetter = false isLetter = I18n.Unicode.isLetter("."); // isLetter = false
``` ```
判断字符是否是小写字母。 判断字符是否是小写字母。
```js ```js
var isLowerCase = I18n.Unicode.isLowerCase("a"); // isLetter = true let isLowerCase = I18n.Unicode.isLowerCase("a"); // isLetter = true
isLowerCase = I18n.Unicode.isLowerCase("A"); // isLetter = false isLowerCase = I18n.Unicode.isLowerCase("A"); // isLetter = false
``` ```
判断字符是否是大写字母。 判断字符是否是大写字母。
```js ```js
var isUpperCase = I18n.Unicode.isUpperCase("a"); // isUpperCase = false let isUpperCase = I18n.Unicode.isUpperCase("a"); // isUpperCase = false
isUpperCase = I18n.Unicode.isUpperCase("A"); // isUpperCase = true isUpperCase = I18n.Unicode.isUpperCase("A"); // isUpperCase = true
``` ```
...@@ -707,7 +703,7 @@ try { ...@@ -707,7 +703,7 @@ try {
调用getType接口获取字符的类型。 调用getType接口获取字符的类型。
```js ```js
var type = I18n.Unicode.getType("a"); // type = U_LOWER_CASE_LETTER let type = I18n.Unicode.getType("a"); // type = U_LOWER_CASE_LETTER
``` ```
## 获取日期中年月日的排列顺序 ## 获取日期中年月日的排列顺序
...@@ -732,5 +728,5 @@ try { ...@@ -732,5 +728,5 @@ try {
接口返回一个字符串,由"y","L","d"三部分组成,分别表示年、月、日,使用中划线进行拼接。例如,"y-L-d"。 接口返回一个字符串,由"y","L","d"三部分组成,分别表示年、月、日,使用中划线进行拼接。例如,"y-L-d"。
```js ```js
var order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d",表示中文中年月日的顺序为年-月-日。 let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d",表示中文中年月日的顺序为年-月-日。
``` ```
\ No newline at end of file
...@@ -48,9 +48,9 @@ ...@@ -48,9 +48,9 @@
```js ```js
var locale = "zh-CN"; let locale = "zh-CN";
var options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; let options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"};
var localeObj = new Intl.Locale(locale, options); let localeObj = new Intl.Locale(locale, options);
``` ```
3. 获取Locale的字符串表示。 3. 获取Locale的字符串表示。
...@@ -58,7 +58,7 @@ ...@@ -58,7 +58,7 @@
调用toString方法来获取Locale对象的字符串表示,其中包括了语言、区域及其他选项信息。 调用toString方法来获取Locale对象的字符串表示,其中包括了语言、区域及其他选项信息。
```js ```js
var localeStr = localeObj.toString(); // localeStr = "zh-CN-u-ca-chinese-co-pinyin-kf-false let localeStr = localeObj.toString(); // localeStr = "zh-CN-u-ca-chinese-co-pinyin-kf-false
``` ```
4. 最大化区域信息。 4. 最大化区域信息。
...@@ -66,8 +66,8 @@ ...@@ -66,8 +66,8 @@
调用maximize方法来最大化区域信息,即当缺少脚本与地区信息时,对其进行补全。 调用maximize方法来最大化区域信息,即当缺少脚本与地区信息时,对其进行补全。
```js ```js
var maximizedLocale = localeObj.maximize(); let maximizedLocale = localeObj.maximize();
var maximizedLocaleStr = maximizedLocale.toString(); // localeStr = "zh-Hans-CN-u-ca-chinese-co-pinyin-kf-false let maximizedLocaleStr = maximizedLocale.toString(); // localeStr = "zh-Hans-CN-u-ca-chinese-co-pinyin-kf-false
``` ```
5. 最小化区域信息。 5. 最小化区域信息。
...@@ -75,8 +75,8 @@ ...@@ -75,8 +75,8 @@
调用minimize方法来最小化区域信息,即当存在脚本与地区信息时,对其进行删除。 调用minimize方法来最小化区域信息,即当存在脚本与地区信息时,对其进行删除。
```js ```js
var minimizedLocale = localeObj.minimize(); let minimizedLocale = localeObj.minimize();
var minimizedLocaleStr = minimizedLocale.toString(); // zh-u-ca-chinese-co-pinyin-kf-false let minimizedLocaleStr = minimizedLocale.toString(); // zh-u-ca-chinese-co-pinyin-kf-false
``` ```
## 格式化日期时间 ## 格式化日期时间
...@@ -108,14 +108,14 @@ ...@@ -108,14 +108,14 @@
一种方法是使用DateTimeFormat提供的默认构造函数,通过访问系统语言和地区设置,获取系统默认Locale,并将其作为DateTimeFormat对象内部的Locale。 一种方法是使用DateTimeFormat提供的默认构造函数,通过访问系统语言和地区设置,获取系统默认Locale,并将其作为DateTimeFormat对象内部的Locale。
```js ```js
var dateTimeFormat = new Intl.DateTimeFormat(); let dateTimeFormat = new Intl.DateTimeFormat();
``` ```
另一种方法是使用开发者提供的Locale和格式化参数来创建日期时间格式化对象。其中,格式化参数是可选的,完整的格式化参数列表见[DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions)。 另一种方法是使用开发者提供的Locale和格式化参数来创建日期时间格式化对象。其中,格式化参数是可选的,完整的格式化参数列表见[DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions)。
```js ```js
var options = {dateStyle: "full", timeStyle: "full"}; let options = {dateStyle: "full", timeStyle: "full"};
var dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options);
``` ```
3. 格式化日期时间。 3. 格式化日期时间。
...@@ -123,10 +123,10 @@ ...@@ -123,10 +123,10 @@
使用DateTimeFormat的format方法对一个Date对象进行格式化,该方法会返回一个字符串作为格式化的结果。 使用DateTimeFormat的format方法对一个Date对象进行格式化,该方法会返回一个字符串作为格式化的结果。
```js ```js
var options = {dateStyle: "full", timeStyle: "full"}; let options = {dateStyle: "full", timeStyle: "full"};
var dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options);
var date = new Date(2022, 12, 12, 12, 12, 12); let date = new Date(2022, 12, 12, 12, 12, 12);
var formatResult = dateTimeFormat.format(date); // formatResult = "2023年1月12日星期四 中国标准时间 下午12:12:12" let formatResult = dateTimeFormat.format(date); // formatResult = "2023年1月12日星期四 中国标准时间 下午12:12:12"
``` ```
4. 格式化时间段。 4. 格式化时间段。
...@@ -134,10 +134,10 @@ ...@@ -134,10 +134,10 @@
使用DateTimeFormat的formatRange方法对一个时间段进行格式化。该方法需要传入两个Date对象,分别表示时间段的起止日期,返回一个字符串作为格式化的结果。 使用DateTimeFormat的formatRange方法对一个时间段进行格式化。该方法需要传入两个Date对象,分别表示时间段的起止日期,返回一个字符串作为格式化的结果。
```js ```js
var startDate = new Date(2021, 11, 17, 3, 24, 0); let startDate = new Date(2021, 11, 17, 3, 24, 0);
var endDate = new Date(2021, 11, 18, 3, 24, 0); let endDate = new Date(2021, 11, 18, 3, 24, 0);
var datefmt = new Intl.DateTimeFormat("en-GB"); let datefmt = new Intl.DateTimeFormat("en-GB");
var formatRangeResult = datefmt.formatRange(startDate, endDate); // formatRangeResult = "17/12/2021-18/12/2021" let formatRangeResult = datefmt.formatRange(startDate, endDate); // formatRangeResult = "17/12/2021-18/12/2021"
``` ```
5. 访问日期时间格式化对象的相关属性。 5. 访问日期时间格式化对象的相关属性。
...@@ -145,9 +145,9 @@ ...@@ -145,9 +145,9 @@
DateTimeFormat的resolvedOptions方法会返回一个对象,该对象包含了DateTimeFormat对象的所有相关属性及其值。 DateTimeFormat的resolvedOptions方法会返回一个对象,该对象包含了DateTimeFormat对象的所有相关属性及其值。
```js ```js
var options = {dateStyle: "full", timeStyle: "full"}; let options = {dateStyle: "full", timeStyle: "full"};
var dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options);
var resolvedOptions = dateTimeFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "calendar": "gregorian", "dateStyle":"full", "timeStyle":"full", "timeZone": "CST"} let resolvedOptions = dateTimeFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "calendar": "gregorian", "dateStyle":"full", "timeStyle":"full", "timeZone": "CST"}
``` ```
## 数字格式化 ## 数字格式化
...@@ -178,14 +178,14 @@ ...@@ -178,14 +178,14 @@
一种方法是使用NumberFormat提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。 一种方法是使用NumberFormat提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。
```js ```js
var numberFormat = new Intl.NumberFormat(); let numberFormat = new Intl.NumberFormat();
``` ```
另一种方法是使用开发者提供的Locale和格式化参数来创建数字格式化对象。其中,格式化参数是可选的,完整的格式化参数列表参见[NumberOptions](../reference/apis/js-apis-intl.md#numberoptions)。 另一种方法是使用开发者提供的Locale和格式化参数来创建数字格式化对象。其中,格式化参数是可选的,完整的格式化参数列表参见[NumberOptions](../reference/apis/js-apis-intl.md#numberoptions)。
```js ```js
var options = {compactDisplay: "short", notation: "compact"}; let options = {compactDisplay: "short", notation: "compact"};
var numberFormat = new Intl.NumberFormat("zh-CN", options); let numberFormat = new Intl.NumberFormat("zh-CN", options);
``` ```
3. 数字格式化。 3. 数字格式化。
...@@ -193,10 +193,10 @@ ...@@ -193,10 +193,10 @@
使用NumberFormat的format方法对传入的数字进行格式化。该方法返回一个字符串作为格式化的结果。 使用NumberFormat的format方法对传入的数字进行格式化。该方法返回一个字符串作为格式化的结果。
```js ```js
var options = {compactDisplay: "short", notation: "compact"}; let options = {compactDisplay: "short", notation: "compact"};
var numberFormat = new Intl.NumberFormat("zh-CN", options); let numberFormat = new Intl.NumberFormat("zh-CN", options);
var number = 1234.5678 let number = 1234.5678
var formatResult = numberFormat.format(number); // formatResult = "1235" let formatResult = numberFormat.format(number); // formatResult = "1235"
``` ```
4. 访问数字格式化对象的相关属性。 4. 访问数字格式化对象的相关属性。
...@@ -204,9 +204,9 @@ ...@@ -204,9 +204,9 @@
NumberFormat的resolvedOptions方法会返回一个对象,该对象包含了NumberFormat对象的所有相关属性及其值。 NumberFormat的resolvedOptions方法会返回一个对象,该对象包含了NumberFormat对象的所有相关属性及其值。
```js ```js
var options = {compactDisplay: "short", notation: "compact"}; let options = {compactDisplay: "short", notation: "compact"};
var numberFormat = new Intl.NumberFormat("zh-CN", options); let numberFormat = new Intl.NumberFormat("zh-CN", options);
var resolvedOptions = numberFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "compactDisplay": "short", "notation": "compact", "numberingSystem": "Latn"} let resolvedOptions = numberFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "compactDisplay": "short", "notation": "compact", "numberingSystem": "Latn"}
``` ```
## 字符串排序 ## 字符串排序
...@@ -237,14 +237,14 @@ ...@@ -237,14 +237,14 @@
一种方法是使用Collator提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。 一种方法是使用Collator提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。
```js ```js
var collator = new Intl.Collator(); let collator = new Intl.Collator();
``` ```
另一种方法是使用开发者提供的Locale和其他相关参数来创建Collator对象,完整的参数列表参见[CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9)。 另一种方法是使用开发者提供的Locale和其他相关参数来创建Collator对象,完整的参数列表参见[CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9)。
其中,sensitivity参数用于控制哪些级别的差异会被用于比较两个字符串。取值"base"表示,仅比较字符本身,不考虑重音符号、大小写差异。例如,'a' != 'b','a' == 'á','a' == 'A'。取值"accent"表示考虑重音符号,不考虑大小写的差异。例如,'a' != 'b','a' != 'á','a' == 'A'。取值"case"表示考虑大小写的差异,不考虑重音符号的差异。例如,'a' != 'b','a' == 'á','a' != 'A'。取值"variant"表示考虑重音符号、大小写等方面差异。例如'a' != 'b','a' != 'á','a' != 'A'。 其中,sensitivity参数用于控制哪些级别的差异会被用于比较两个字符串。取值"base"表示,仅比较字符本身,不考虑重音符号、大小写差异。例如,'a' != 'b','a' == 'á','a' == 'A'。取值"accent"表示考虑重音符号,不考虑大小写的差异。例如,'a' != 'b','a' != 'á','a' == 'A'。取值"case"表示考虑大小写的差异,不考虑重音符号的差异。例如,'a' != 'b','a' == 'á','a' != 'A'。取值"variant"表示考虑重音符号、大小写等方面差异。例如'a' != 'b','a' != 'á','a' != 'A'。
```js ```js
var collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"});
``` ```
3. 比较字符串。 3. 比较字符串。
...@@ -252,10 +252,10 @@ ...@@ -252,10 +252,10 @@
使用Collator的compare方法对传入的两个字符串进行比较。该方法返回一个数值作为比较的结果,返回-1表示第一个字符串小于第二个字符串,返回1表示第一个字符大于第二个字符串,返回0表示两个字符串相同。基于两个字符串的比较结果,开发者可以字符串集合进行排序。 使用Collator的compare方法对传入的两个字符串进行比较。该方法返回一个数值作为比较的结果,返回-1表示第一个字符串小于第二个字符串,返回1表示第一个字符大于第二个字符串,返回0表示两个字符串相同。基于两个字符串的比较结果,开发者可以字符串集合进行排序。
```js ```js
var collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"});
var str1 = "first string"; let str1 = "first string";
var str2 = "second string"; let str2 = "second string";
var compareResult = collator.compare(str1, str2); // compareResult = -1 let compareResult = collator.compare(str1, str2); // compareResult = -1
str1 = "first"; str1 = "first";
str2 = "First"; str2 = "First";
compareResult = collator.compare(str1, str2); // compareResult = -1 compareResult = collator.compare(str1, str2); // compareResult = -1
...@@ -266,8 +266,8 @@ ...@@ -266,8 +266,8 @@
Collator的resolvedOptions方法会返回一个对象,该对象包含了Collator对象的所有相关属性及其值。 Collator的resolvedOptions方法会返回一个对象,该对象包含了Collator对象的所有相关属性及其值。
```js ```js
var collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"});
var options = collator.resolvedOptions(); // options = {"localeMatcher": "best fit", "locale": "zh-CN", "usage": "sort", "sensitivity": "variant", "ignorePunctuation": "false", "numeric": false, "caseFirst": "false", "collation": "default"} let options = collator.resolvedOptions(); // options = {"localeMatcher": "best fit", "locale": "zh-CN", "usage": "sort", "sensitivity": "variant", "ignorePunctuation": "false", "numeric": false, "caseFirst": "false", "collation": "default"}
``` ```
## 判定单复数类别 ## 判定单复数类别
...@@ -298,13 +298,13 @@ ...@@ -298,13 +298,13 @@
一种方法是使用PluralRules提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。 一种方法是使用PluralRules提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。
```js ```js
var pluralRules = new Intl.PluralRules(); let pluralRules = new Intl.PluralRules();
``` ```
另一种方法是使用开发者提供的Locale和其他相关参数来创建单复数对象。完整的参数列表参见[PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9)。 另一种方法是使用开发者提供的Locale和其他相关参数来创建单复数对象。完整的参数列表参见[PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9)。
```js ```js
var pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
``` ```
3. 计算数字单复数类别。 3. 计算数字单复数类别。
...@@ -312,9 +312,9 @@ ...@@ -312,9 +312,9 @@
使用PluralRules的select方法计算传入数字的单复数类别。该方法返回一个字符串作为传入数字的类别,包括:"zero", "one", "two", "few", "many", "other"六个类别。 使用PluralRules的select方法计算传入数字的单复数类别。该方法返回一个字符串作为传入数字的类别,包括:"zero", "one", "two", "few", "many", "other"六个类别。
```js ```js
var pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
var number = 1234.5678 let number = 1234.5678
var categoryResult = pluralRules.select(number); // categoryResult = "other" let categoryResult = pluralRules.select(number); // categoryResult = "other"
``` ```
## 相对时间格式化 ## 相对时间格式化
...@@ -346,13 +346,13 @@ ...@@ -346,13 +346,13 @@
一种方法是使用RelativeTimeFormat提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。 一种方法是使用RelativeTimeFormat提供的默认构造函数,通过访问系统的语言和地区以获取系统默认Locale并进行设置(intl为导入的模块名)。
```js ```js
var relativeTimeFormat = new Intl.RelativeTimeFormat(); let relativeTimeFormat = new Intl.RelativeTimeFormat();
``` ```
另一种方法是使用开发者提供的Locale和格式化参数来创建相对时间格式化对象。其中,格式化参数是可选的,完整的参数列表参见[ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9)。 另一种方法是使用开发者提供的Locale和格式化参数来创建相对时间格式化对象。其中,格式化参数是可选的,完整的参数列表参见[ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9)。
```js ```js
var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
``` ```
3. 相对时间格式化。 3. 相对时间格式化。
...@@ -360,10 +360,10 @@ ...@@ -360,10 +360,10 @@
使用RelativeTimeFormat的format方法对相对时间进行格式化。方法接收一个表示相对时间长度的数值和表示单位的字符串,其中单位包括:"year", "quarter", "month", "week", "day", "hour", "minute", "second"。方法返回一个字符串作为格式化的结果。 使用RelativeTimeFormat的format方法对相对时间进行格式化。方法接收一个表示相对时间长度的数值和表示单位的字符串,其中单位包括:"year", "quarter", "month", "week", "day", "hour", "minute", "second"。方法返回一个字符串作为格式化的结果。
```js ```js
var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
var number = 2; let number = 2;
var unit = "year" let unit = "year"
var formatResult = relativeTimeFormat.format(number, unit); // 2年后 let formatResult = relativeTimeFormat.format(number, unit); // 2年后
``` ```
4. 获取相对时间格式化结果的各个部分。 4. 获取相对时间格式化结果的各个部分。
...@@ -371,10 +371,10 @@ ...@@ -371,10 +371,10 @@
获取相对时间格式化结果的各个部分,从而自定义格式化结果。 获取相对时间格式化结果的各个部分,从而自定义格式化结果。
```js ```js
var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
var number = 2; let number = 2;
var unit = "year" let unit = "year"
var formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "年后"}] let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "年后"}]
``` ```
5. 访问相对时间格式化对象的相关属性。 5. 访问相对时间格式化对象的相关属性。
...@@ -382,8 +382,8 @@ ...@@ -382,8 +382,8 @@
RelativeTimeFormat的resolvedOptions方法会返回一个对象,该对象包含了RelativeTimeFormat对象的所有相关属性及其值,完整的属性列表参见[ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8)。 RelativeTimeFormat的resolvedOptions方法会返回一个对象,该对象包含了RelativeTimeFormat对象的所有相关属性及其值,完整的属性列表参见[ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8)。
```js ```js
var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
var options = relativeTimeFormat.resolvedOptions(); // options = {"locale": "zh-CN", "style": "long", "numeric": "always", "numberingSystem": "latn"} let options = relativeTimeFormat.resolvedOptions(); // options = {"locale": "zh-CN", "style": "long", "numeric": "always", "numberingSystem": "latn"}
``` ```
## 相关实例 ## 相关实例
......
...@@ -14,7 +14,7 @@ import wantConstant from '@ohos.ability.wantConstant'; ...@@ -14,7 +14,7 @@ import wantConstant from '@ohos.ability.wantConstant';
## wantConstant.Action ## wantConstant.Action
want操作的常数。 want操作的常数。用于表示要执行的通用操作。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
...@@ -57,13 +57,13 @@ want操作的常数。 ...@@ -57,13 +57,13 @@ want操作的常数。
## wantConstant.Entity ## wantConstant.Entity
want实体的常数。 want实体的常数。用于表示目标Ability额外的类别信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ------------ | ------------------ | ---------------------- | | ------------ | ------------------ | ---------------------- |
| ENTITY_DEFAULT | entity.system.default | 指示默认实体,如果未指定实体,则使用该实体。 | | ENTITY_DEFAULT | entity.system.default | 指示默认实体,如果未指定实体,则使用该实体。 |
| ENTITY_HOME | entity.system.home | 指示主屏幕实体。 | | ENTITY_HOME | entity.system.home | 指示主屏幕实体。 |
| ENTITY_VOICE | entity.system.voice | 表示语音交互实体。 | | ENTITY_VOICE | entity.system.voice | 表示语音交互实体。 |
| ENTITY_BROWSABLE | entity.system.browsable | 指示浏览器类别。 | | ENTITY_BROWSABLE | entity.system.browsable | 指示浏览器类别。 |
...@@ -72,7 +72,7 @@ want实体的常数。 ...@@ -72,7 +72,7 @@ want实体的常数。
## wantConstant.Flags ## wantConstant.Flags
Flags说明。 Flags说明。用于表示处理Want的方式。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
......
...@@ -385,7 +385,6 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; ...@@ -385,7 +385,6 @@ import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId
let permissionFlag = 1;
try { try {
atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => {
console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`);
...@@ -459,11 +458,12 @@ on(type: 'permissionStateChange', tokenIDList: Array&lt;number&gt;, permissionNa ...@@ -459,11 +458,12 @@ on(type: 'permissionStateChange', tokenIDList: Array&lt;number&gt;, permissionNa
**示例:** **示例:**
```js ```js
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let tokenIDList: Array<number> = []; let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100);
let permissionNameList = []; let tokenIDList: Array<number> = [appInfo.accessTokenId];
let permissionNameList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
try { try {
atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => { atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => {
console.debug("receive permission state change, data:" + JSON.stringify(data)); console.debug("receive permission state change, data:" + JSON.stringify(data));
...@@ -508,11 +508,12 @@ off(type: 'permissionStateChange', tokenIDList: Array&lt;number&gt;, permissionN ...@@ -508,11 +508,12 @@ off(type: 'permissionStateChange', tokenIDList: Array&lt;number&gt;, permissionN
**示例:** **示例:**
```js ```js
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let tokenIDList: Array<number> = []; let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100);
let permissionNameList = []; let tokenIDList: Array<number> = [appInfo.accessTokenId];
let permissionNameList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
try { try {
atManager.off('permissionStateChange', tokenIDList, permissionNameList); atManager.off('permissionStateChange', tokenIDList, permissionNameList);
} catch(err) { } catch(err) {
......
...@@ -16,7 +16,7 @@ import Configuration from '@ohos.app.ability.Configuration' ...@@ -16,7 +16,7 @@ import Configuration from '@ohos.app.ability.Configuration'
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| language | string | 是 | 是 | 表示应用程序的当前语言。 | | language | string | 是 | 是 | 表示应用程序的当前语言。例如:zh。 |
| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | | colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 |
| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | | direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 |
| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | | screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 |
...@@ -40,7 +40,7 @@ import Configuration from '@ohos.app.ability.Configuration' ...@@ -40,7 +40,7 @@ import Configuration from '@ohos.app.ability.Configuration'
} }
}; };
try { try {
var callbackId = applicationContext.on("environment", envCallback); let callbackId = applicationContext.on("environment", envCallback);
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log("error: " + paramError.code + ", " + paramError.message);
} }
......
...@@ -18,23 +18,23 @@ import Want from '@ohos.app.ability.Want'; ...@@ -18,23 +18,23 @@ import Want from '@ohos.app.ability.Want';
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | 否 | 表示运行指定Ability的设备ID。 | | deviceId | string | 否 | 表示运行指定Ability的设备ID。如果未设置该字段,则表明指定本设备。 |
| bundleName | string | 否 | 表示包描述。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 | | bundleName | string | 否 | 表示Bundle名称。 |
| abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | | abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 |
| uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | | uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 |
| type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | | type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 |
| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-app-ability-wantConstant.md#wantConstant.Flags)。 | | flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-app-ability-wantConstant.md#wantConstant.Flags)。 |
| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。 | | action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md) |
| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | | parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 |
| entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 | | entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity)。 |
| moduleName | string | 否 | 表示待启动的Ability所属的模块(module)。 | | moduleName | string | 否 | 表示待启动的Ability所属的模块(module)。 |
**示例:** **示例:**
- 基础用法 - 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)
```ts ```ts
var want = { let want = {
"deviceId": "", // deviceId为空表示本设备 "deviceId": "", // deviceId为空表示本设备
"bundleName": "com.extreme.test", "bundleName": "com.extreme.test",
"abilityName": "MainAbility", "abilityName": "MainAbility",
...@@ -46,7 +46,7 @@ import Want from '@ohos.app.ability.Want'; ...@@ -46,7 +46,7 @@ import Want from '@ohos.app.ability.Want';
}) })
``` ```
- 通过自定字段传递数据, 以下为当前支持类型。 - 通过自定字段传递数据, 以下为当前支持类型。(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)
* 字符串(String) * 字符串(String)
```ts ```ts
...@@ -110,13 +110,13 @@ import Want from '@ohos.app.ability.Want'; ...@@ -110,13 +110,13 @@ import Want from '@ohos.app.ability.Want';
* 文件描述符(FD) * 文件描述符(FD)
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
var fd; let fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) { } catch(e) {
console.log("openSync fail:" + JSON.stringify(e)); console.log("openSync fail:" + JSON.stringify(e));
} }
var want = { let want = {
"deviceId": "", // deviceId为空表示本设备 "deviceId": "", // deviceId为空表示本设备
"bundleName": "com.extreme.test", "bundleName": "com.extreme.test",
"abilityName": "MainAbility", "abilityName": "MainAbility",
...@@ -131,6 +131,8 @@ import Want from '@ohos.app.ability.Want'; ...@@ -131,6 +131,8 @@ import Want from '@ohos.app.ability.Want';
}) })
``` ```
- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want
<!--no_check--> <!--no_check-->
...@@ -14,7 +14,7 @@ import wantConstant from '@ohos.app.ability.wantConstant'; ...@@ -14,7 +14,7 @@ import wantConstant from '@ohos.app.ability.wantConstant';
## wantConstant.Action ## wantConstant.Action
want操作的常数。 want操作的常数。用于表示要执行的通用操作。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
...@@ -56,7 +56,7 @@ want操作的常数。 ...@@ -56,7 +56,7 @@ want操作的常数。
## wantConstant.Entity ## wantConstant.Entity
want实体的常数。 want实体的常数。用于表示目标Ability额外的类别信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
...@@ -71,7 +71,7 @@ want实体的常数。 ...@@ -71,7 +71,7 @@ want实体的常数。
## wantConstant.Flags ## wantConstant.Flags
Flags说明。 Flags说明。用于表示处理Want的方式。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
......
...@@ -16,7 +16,7 @@ import Configuration from '@ohos.application.Configuration' ...@@ -16,7 +16,7 @@ import Configuration from '@ohos.application.Configuration'
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| language<sup>8+</sup> | string | 是 | 是 | 表示应用程序的当前语言。 | | language<sup>8+</sup> | string | 是 | 是 | 表示应用程序的当前语言。例如:zh。 |
| colorMode<sup>8+</sup> | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | | colorMode<sup>8+</sup> | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 |
| direction<sup>9+</sup> | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | | direction<sup>9+</sup> | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 |
| screenDensity<sup>9+</sup> | [ScreenDensity](js-apis-application-configurationConstant.md#configurationconstantscreendensity9) | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | | screenDensity<sup>9+</sup> | [ScreenDensity](js-apis-application-configurationConstant.md#configurationconstantscreendensity9) | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 |
......
...@@ -18,23 +18,23 @@ import Want from '@ohos.application.Want'; ...@@ -18,23 +18,23 @@ import Want from '@ohos.application.Want';
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | 否 | 表示运行指定Ability的设备ID。 | | deviceId | string | 否 | 表示运行指定Ability的设备ID。如果未设置该字段,则表明指定本设备。 |
| bundleName | string | 否 | 表示包描述。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 | | bundleName | string | 否 | 表示Bundle名称。 |
| abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | | abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 |
| uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | | uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 |
| type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | | type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 |
| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantConstant.Flags)。 | | flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantConstant.Flags)。 |
| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。 | | action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md) |
| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | | parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 |
| entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 | | entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity)。 |
| moduleName<sup>9+</sup> | string | 否 | 表示待启动的Ability所属的模块(module)。 | | moduleName<sup>9+</sup> | string | 否 | 表示待启动的Ability所属的模块(module)。 |
**示例:** **示例:**
- 基础用法 - 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)
```ts ```ts
var want = { let want = {
"deviceId": "", // deviceId为空表示本设备 "deviceId": "", // deviceId为空表示本设备
"bundleName": "com.extreme.test", "bundleName": "com.extreme.test",
"abilityName": "MainAbility", "abilityName": "MainAbility",
...@@ -46,7 +46,7 @@ import Want from '@ohos.application.Want'; ...@@ -46,7 +46,7 @@ import Want from '@ohos.application.Want';
}) })
``` ```
- 通过自定字段传递数据, 以下为当前支持类型。 - 通过自定字段传递数据, 以下为当前支持类型。(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)
* 字符串(String) * 字符串(String)
```ts ```ts
...@@ -110,13 +110,13 @@ import Want from '@ohos.application.Want'; ...@@ -110,13 +110,13 @@ import Want from '@ohos.application.Want';
* 文件描述符(FD) * 文件描述符(FD)
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
var fd; let fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) { } catch(e) {
console.log("openSync fail:" + JSON.stringify(e)); console.log("openSync fail:" + JSON.stringify(e));
} }
var want = { let want = {
"deviceId": "", // deviceId为空表示本设备 "deviceId": "", // deviceId为空表示本设备
"bundleName": "com.extreme.test", "bundleName": "com.extreme.test",
"abilityName": "MainAbility", "abilityName": "MainAbility",
...@@ -131,4 +131,6 @@ import Want from '@ohos.application.Want'; ...@@ -131,4 +131,6 @@ import Want from '@ohos.application.Want';
}) })
``` ```
- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want
<!--no_check--> <!--no_check-->
\ No newline at end of file
...@@ -18,8 +18,8 @@ Ability信息,未做特殊说明的属性,均通过[bundle.getAbilityInfo](j ...@@ -18,8 +18,8 @@ Ability信息,未做特殊说明的属性,均通过[bundle.getAbilityInfo](j
| label | string | 是 | 否 | Ability对用户显示的名称。 | | label | string | 是 | 否 | Ability对用户显示的名称。 |
| description | string | 是 | 否 | Ability的描述。 | | description | string | 是 | 否 | Ability的描述。 |
| icon | string | 是 | 否 | Ability的图标资源文件索引。 | | icon | string | 是 | 否 | Ability的图标资源文件索引。 |
| descriptionId | number | 是 | 否 | Ability的描述id。 | | descriptionId | number | 是 | 否 | Ability的描述的资源id值。 |
| iconId | number | 是 | 否 | Ability的图标id。 | | iconId | number | 是 | 否 | Ability的图标的资源id值。 |
| moduleName | string | 是 | 否 | Ability所属的HAP的名称。 | | moduleName | string | 是 | 否 | Ability所属的HAP的名称。 |
| process | string | 是 | 否 | Ability的进程,如果不设置,默认为包的名称。 | | process | string | 是 | 否 | Ability的进程,如果不设置,默认为包的名称。 |
| targetAbility | string | 是 | 否 | 当前Ability重用的目标Ability。<br />此属性仅可在FA模型下使用。 | | targetAbility | string | 是 | 否 | 当前Ability重用的目标Ability。<br />此属性仅可在FA模型下使用。 |
...@@ -36,7 +36,7 @@ Ability信息,未做特殊说明的属性,均通过[bundle.getAbilityInfo](j ...@@ -36,7 +36,7 @@ Ability信息,未做特殊说明的属性,均通过[bundle.getAbilityInfo](j
| writePermission | string | 是 | 否 | 向Ability写数据所需的权限。<br />此属性仅可在FA模型下使用。 | | writePermission | string | 是 | 否 | 向Ability写数据所需的权限。<br />此属性仅可在FA模型下使用。 |
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | 应用程序的配置信息。<br />通过调用[bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated)接口时,传入GET_ABILITY_INFO_WITH_APPLICATION获取。 | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | 应用程序的配置信息。<br />通过调用[bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated)接口时,传入GET_ABILITY_INFO_WITH_APPLICATION获取。 |
| uri | string | 是 | 否 | 获取Ability的统一资源标识符(URI)。<br />此属性仅可在FA模型下使用。 | | uri | string | 是 | 否 | 获取Ability的统一资源标识符(URI)。<br />此属性仅可在FA模型下使用。 |
| labelId | number | 是 | 否 | Ability的标签id。 | | labelId | number | 是 | 否 | Ability的标签的资源id值。 |
| subType | AbilitySubType | 是 | 否 | Ability中枚举使用的模板的子类型。<br />此属性仅可在FA模型下使用。 | | subType | AbilitySubType | 是 | 否 | Ability中枚举使用的模板的子类型。<br />此属性仅可在FA模型下使用。 |
| metadata<sup>8+</sup> | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | 是 | 否 | ability的元信息。<br />通过调用[bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated)接口时,传入GET_ABILITY_INFO_WITH_METADATA获取。 | | metadata<sup>8+</sup> | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | 是 | 否 | ability的元信息。<br />通过调用[bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated)接口时,传入GET_ABILITY_INFO_WITH_METADATA获取。 |
| enabled<sup>8+</sup> | boolean | 是 | 否 | ability是否可用。 | | enabled<sup>8+</sup> | boolean | 是 | 否 | ability是否可用。 |
...@@ -17,8 +17,8 @@ ElementName信息,标识Ability的基本信息,通过接口[Context.getEleme ...@@ -17,8 +17,8 @@ ElementName信息,标识Ability的基本信息,通过接口[Context.getEleme
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------------------- | ---------| ---- | ---- | ------------------------- | | ----------------------- | ---------| ---- | ---- | ------------------------- |
| deviceId | string | 是 | 是 | 设备id。 | | deviceId | string | 是 | 是 | 设备id。 |
| bundleName | string | 是 | 是 | 应用Bundle名称。 | | bundleName | string | 是 | 是 | 应用Bundle名称。 |
| abilityName | string | 是 | 是 | Ability名称。 | | abilityName | string | 是 | 是 | Ability名称。 |
| uri | string | 是 | 是 | 资源标识符。 | | uri | string | 是 | 是 | 资源标识符。 |
| shortName | string | 是 | 是 | Ability短名称。 | | shortName | string | 是 | 是 | Ability的短名称。 |
\ No newline at end of file \ No newline at end of file
...@@ -17,7 +17,7 @@ LauncherAbilityInfo信息,通过接口[innerBundleManager.getLauncherAbilityIn ...@@ -17,7 +17,7 @@ LauncherAbilityInfo信息,通过接口[innerBundleManager.getLauncherAbilityIn
| --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- | | --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- |
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | launcher ability的应用程序的配置信息。 | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | launcher ability的应用程序的配置信息。 |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 否 | launcher ability的ElementName信息。 | | elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 否 | launcher ability的ElementName信息。 |
| labelId | number | 是 | 否 | launcher ability的标签ID。 | | labelId | number | 是 | 否 | launcher ability的标签的资源id值。 |
| iconId | number | 是 | 否 | launcher ability的图标ID。 | | iconId | number | 是 | 否 | launcher ability的图标的资源id值。 |
| userId | number | 是 | 否 | launcher ability的用户ID。 | | userId | number | 是 | 否 | launcher ability的用户的资源id值。 |
| installTime | number | 是 | 否 | launcher ability的安装时间。 | | installTime | number | 是 | 否 | launcher ability的安装时间。 |
\ No newline at end of file
...@@ -13,17 +13,17 @@ HAP信息,系统应用可以通过[bundleManager.getBundleInfo](js-apis-bundle ...@@ -13,17 +13,17 @@ HAP信息,系统应用可以通过[bundleManager.getBundleInfo](js-apis-bundle
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- |
| name | string | 是 | 否 | 模块名称。 | | name | string | 是 | 否 | 模块名称。 |
| icon | string | 是 | 否 | 模块图标。 | | icon | string | 是 | 否 | 模块图标。 |
| iconId | number | 是 | 否 | 模块图标资源id。 | | iconId | number | 是 | 否 | 模块图标的资源id值。 |
| label | string | 是 | 否 | 模块标签。 | | label | string | 是 | 否 | 模块标签。 |
| labelId | number | 是 | 否 | 模块标签资源id。 | | labelId | number | 是 | 否 | 模块标签的资源id值。 |
| description | string | 是 | 否 | 模块描述信息。 | | description | string | 是 | 否 | 模块描述信息。 |
| descriptionId | number | 是 | 否 | 描述信息资源id。 | | descriptionId | number | 是 | 否 | 描述信息的资源id值。 |
| mainElementName | string | 是 | 否 | 入口ability信息。 | | mainElementName | string | 是 | 否 | 入口ability信息。 |
| abilitiesInfo | Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | 是 | 否 | Ability信息。 | | abilitiesInfo | Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | 是 | 否 | Ability信息。 |
| extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | 是 | 否 | ExtensionAbility信息。 | | extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | 是 | 否 | ExtensionAbility信息。 |
| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | 是 | 否 | Ability的元信息。 | | metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | 是 | 否 | Ability的元信息。 |
| deviceTypes | Array\<string> | 是 | 否 | 支持运行的设备类型。 | | deviceTypes | Array\<string> | 是 | 否 | 可以运行模块的设备类型。 |
| installationFree | boolean | 是 | 否 | 是否支持免安装。 | | installationFree | boolean | 是 | 否 | 模块是否支持免安装。 |
| hashValue | string | 是 | 否 | Module的Hash值。 | | hashValue | string | 是 | 否 | 模块的Hash值。 |
| moduleSourceDir | string | 是 | 否 | Module的路径。| | moduleSourceDir | string | 是 | 否 | 模块的路径。|
...@@ -81,7 +81,7 @@ off(type: BundleChangedEvent, callback?: callback\<BundleChangedInfo>): void; ...@@ -81,7 +81,7 @@ off(type: BundleChangedEvent, callback?: callback\<BundleChangedInfo>): void;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------------------------- | -------- | ---- | ---------------------------------------------------------- | | ---------------------------- | -------- | ---- | ---------------------------------------------------------- |
| type| BundleChangedEvent| 是 | 注销监听的事件类型。 | | type| BundleChangedEvent| 是 | 注销监听的事件类型。 |
| callback | callback\<BundleChangedInfo>| | 注销监听的回调函数,当为空时表示注销当前事件的所有callback。 | | callback | callback\<BundleChangedInfo>| | 注销监听的回调函数,当为空时表示注销当前事件的所有callback。 |
**示例:** **示例:**
......
...@@ -67,13 +67,13 @@ try { ...@@ -67,13 +67,13 @@ try {
abilityName: 'MainAbility' abilityName: 'MainAbility'
}, (err, data) => { }, (err, data) => {
if (err) { if (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} else { } else {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
} }
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -124,10 +124,10 @@ try { ...@@ -124,10 +124,10 @@ try {
}).then(data => { }).then(data => {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -179,13 +179,13 @@ try { ...@@ -179,13 +179,13 @@ try {
} }
], (err, data) => { ], (err, data) => {
if (err) { if (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} else { } else {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
} }
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -243,10 +243,10 @@ try { ...@@ -243,10 +243,10 @@ try {
]).then(data => { ]).then(data => {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -292,13 +292,13 @@ try { ...@@ -292,13 +292,13 @@ try {
abilityName: 'MainAbility' abilityName: 'MainAbility'
}, 'zh-Hans-CN', (err, data) => { }, 'zh-Hans-CN', (err, data) => {
if (err) { if (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} else { } else {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
} }
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -350,10 +350,10 @@ try { ...@@ -350,10 +350,10 @@ try {
}, 'zh-Hans-CN').then(data => { }, 'zh-Hans-CN').then(data => {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -406,13 +406,13 @@ try { ...@@ -406,13 +406,13 @@ try {
} }
], 'zh-Hans-CN', (err, data) => { ], 'zh-Hans-CN', (err, data) => {
if (err) { if (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} else { } else {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
} }
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -471,9 +471,9 @@ try { ...@@ -471,9 +471,9 @@ try {
], 'zh-Hans-CN').then(data => { ], 'zh-Hans-CN').then(data => {
console.info('Operation succeed:' + JSON.stringify(data)); console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => { }).catch(err => {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
}); });
} catch (err) { } catch (err) {
console.error('Operation failed: error code is ' + err.code + 'and error message is ' + err.message); console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`);
} }
``` ```
...@@ -70,7 +70,7 @@ createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;) : FileAccessH ...@@ -70,7 +70,7 @@ createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;) : FileAccessH
```js ```js
createFileAccessHelper() { createFileAccessHelper() {
let fileAccesssHelper = null; let fileAccessHelper = null;
// wantInfos 从getFileAccessAbilityInfo()获取 // wantInfos 从getFileAccessAbilityInfo()获取
// 创建只连接媒体库服务的helper对象 // 创建只连接媒体库服务的helper对象
let wantInfos = [ let wantInfos = [
...@@ -81,8 +81,8 @@ createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;) : FileAccessH ...@@ -81,8 +81,8 @@ createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;) : FileAccessH
] ]
try { try {
// this.context 是MainAbility 传过来的context // this.context 是MainAbility 传过来的context
fileAccesssHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos);
if (!fileAccesssHelper) if (!fileAccessHelper)
console.error("createFileAccessHelper interface returns an undefined object"); console.error("createFileAccessHelper interface returns an undefined object");
} catch (error) { } catch (error) {
console.error("createFileAccessHelper failed, error " + error); console.error("createFileAccessHelper failed, error " + error);
...@@ -154,6 +154,7 @@ getRoots( ) : Promise&lt;RootIterator&gt; ...@@ -154,6 +154,7 @@ getRoots( ) : Promise&lt;RootIterator&gt;
let rootinfos = []; let rootinfos = [];
let isDone = false; let isDone = false;
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
rootIterator = await fileAccessHelper.getRoots(); rootIterator = await fileAccessHelper.getRoots();
if (!rootIterator) { if (!rootIterator) {
console.error("getRoots interface returns an undefined object"); console.error("getRoots interface returns an undefined object");
...@@ -248,9 +249,9 @@ scanFile(filter?: Filter) : FileIterator ...@@ -248,9 +249,9 @@ scanFile(filter?: Filter) : FileIterator
**示例:** **示例:**
```js ```js
// rootinfos 从 getRoots()获取 // rootInfos 从 getRoots()获取
// let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
let rootInfo = rootinfos[0]; let rootInfo = rootInfos[0];
let fileInfos = []; let fileInfos = [];
let isDone = false; let isDone = false;
try { try {
...@@ -364,7 +365,7 @@ scanFile(filter?: Filter) : FileIterator; ...@@ -364,7 +365,7 @@ scanFile(filter?: Filter) : FileIterator;
} }
while (!isDone) { while (!isDone) {
let result = fileIterator.next(); let result = fileIterator.next();
console.error("next result = " + JSON.stringify(result)); console.log("next result = " + JSON.stringify(result));
isDone = result.done; isDone = result.done;
if (!isDone) if (!isDone)
subfileInfos.push(result.value); subfileInfos.push(result.value);
...@@ -407,6 +408,7 @@ createFile(uri: string, displayName: string) : Promise&lt;string&gt; ...@@ -407,6 +408,7 @@ createFile(uri: string, displayName: string) : Promise&lt;string&gt;
let displayName = "file1" let displayName = "file1"
let fileUri = null; let fileUri = null;
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
fileUri = await fileAccessHelper.createFile(sourceUri, displayName) fileUri = await fileAccessHelper.createFile(sourceUri, displayName)
if (!fileUri) { if (!fileUri) {
console.error("createFile return undefined object"); console.error("createFile return undefined object");
...@@ -451,6 +453,7 @@ mkDir(parentUri: string, displayName: string) : Promise&lt;string&gt; ...@@ -451,6 +453,7 @@ mkDir(parentUri: string, displayName: string) : Promise&lt;string&gt;
let dirName = "dirTest" let dirName = "dirTest"
let dirUri = null; let dirUri = null;
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
dirUri = await fileAccessHelper.mkDir(sourceUri, dirName) dirUri = await fileAccessHelper.mkDir(sourceUri, dirName)
if (!dirUri) { if (!dirUri) {
console.error("mkDir return undefined object"); console.error("mkDir return undefined object");
...@@ -483,7 +486,7 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt; ...@@ -483,7 +486,7 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
| 类型 | 说明 | | 类型 | 说明 |
| --- | -- | | --- | -- |
| Promise&lt;number&gt | 文件句柄 | | Promise&lt;number&gt; | 文件句柄 |
**示例:** **示例:**
...@@ -493,7 +496,8 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt; ...@@ -493,7 +496,8 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
// 开发者应根据自己实际获取的uri进行开发 // 开发者应根据自己实际获取的uri进行开发
let targetUri = "datashare:///media/file/100"; let targetUri = "datashare:///media/file/100";
try { try {
let fd = await fileAccessHelper.openFile(targetUri, OPENFLAGS.READ); // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ);
} catch (error) { } catch (error) {
console.error("openFile failed, error " + error); console.error("openFile failed, error " + error);
}; };
...@@ -529,6 +533,7 @@ delete(uri: string) : Promise&lt;number&gt; ...@@ -529,6 +533,7 @@ delete(uri: string) : Promise&lt;number&gt;
// 开发者应根据自己实际获取的uri进行开发 // 开发者应根据自己实际获取的uri进行开发
let targetUri = "datashare:///media/file/100"; let targetUri = "datashare:///media/file/100";
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
let code = await fileAccessHelper.delete(targetUri); let code = await fileAccessHelper.delete(targetUri);
if (code != 0) if (code != 0)
console.error("delete failed, code " + code); console.error("delete failed, code " + code);
...@@ -569,6 +574,7 @@ move(sourceFile: string, destFile: string) : Promise&lt;string&gt; ...@@ -569,6 +574,7 @@ move(sourceFile: string, destFile: string) : Promise&lt;string&gt;
let sourceFile = "datashare:///media/file/102"; let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101"; let destFile = "datashare:///media/file/101";
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
let fileUri = await fileAccessHelper.move(sourceFile, destFile); let fileUri = await fileAccessHelper.move(sourceFile, destFile);
console.log("move sucess, fileUri: " + JSON.stringify(fileUri)); console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
} catch (error) { } catch (error) {
...@@ -607,6 +613,7 @@ rename(uri: string, displayName: string) : Promise&lt;string&gt; ...@@ -607,6 +613,7 @@ rename(uri: string, displayName: string) : Promise&lt;string&gt;
// 开发者应根据自己实际获取的uri进行开发 // 开发者应根据自己实际获取的uri进行开发
let sourceDir = "datashare:///media/file/100"; let sourceDir = "datashare:///media/file/100";
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
let DestDir = await fileAccessHelper.rename(sourceDir, "testDir"); let DestDir = await fileAccessHelper.rename(sourceDir, "testDir");
console.log("rename sucess, DestDir: " + JSON.stringify(DestDir)); console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
} catch (error) { } catch (error) {
...@@ -644,6 +651,7 @@ access(sourceFileUri: string) : Promise&lt;boolean&gt; ...@@ -644,6 +651,7 @@ access(sourceFileUri: string) : Promise&lt;boolean&gt;
// 开发者应根据自己实际获取的uri进行开发 // 开发者应根据自己实际获取的uri进行开发
let sourceDir = "datashare:///media/file/100"; let sourceDir = "datashare:///media/file/100";
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
let existJudgment = await fileAccessHelper.access(sourceDir); let existJudgment = await fileAccessHelper.access(sourceDir);
if (existJudgment) if (existJudgment)
console.log("sourceDir exists"); console.log("sourceDir exists");
......
...@@ -39,8 +39,8 @@ import fileExtensionInfo from '@ohos.fileExtensionInfo'; ...@@ -39,8 +39,8 @@ import fileExtensionInfo from '@ohos.fileExtensionInfo';
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ------ | ------ | ---- | ---- | -------- | | ------ | ------ | ---- | ---- | -------- |
| SUPPORTS_READ | number | 是 | 否 | 支持读 | | SUPPORTS_READ | number | 是 | 否 | 此设备支持读 |
| SUPPORTS_WRITE | number | 是 | 否 | 支持写 | | SUPPORTS_WRITE | number | 是 | 否 | 此设备支持写 |
## fileExtensionInfo.DocumentFlag ## fileExtensionInfo.DocumentFlag
...@@ -54,5 +54,5 @@ import fileExtensionInfo from '@ohos.fileExtensionInfo'; ...@@ -54,5 +54,5 @@ import fileExtensionInfo from '@ohos.fileExtensionInfo';
| ------ | ------ | ---- | ---- | -------- | | ------ | ------ | ---- | ---- | -------- |
| REPRESENTS_FILE | number | 是 | 否 | 代表文件 | | REPRESENTS_FILE | number | 是 | 否 | 代表文件 |
| REPRESENTS_DIR | number | 是 | 否 | 代表目录 | | REPRESENTS_DIR | number | 是 | 否 | 代表目录 |
| SUPPORTS_READ | number | 是 | 否 | 支持读 | | SUPPORTS_READ | number | 是 | 否 | 此文件支持读 |
| SUPPORTS_WRITE | number | 是 | 否 | 支持写 | | SUPPORTS_WRITE | number | 是 | 否 | 此文件支持写 |
...@@ -51,7 +51,7 @@ static getDisplayCountry(country: string, locale: string, sentenceCase?: boolean ...@@ -51,7 +51,7 @@ static getDisplayCountry(country: string, locale: string, sentenceCase?: boolean
**示例:** **示例:**
```js ```js
try { try {
var displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China" let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China"
} catch(error) { } catch(error) {
console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -90,7 +90,7 @@ static getDisplayLanguage(language: string, locale: string, sentenceCase?: boole ...@@ -90,7 +90,7 @@ static getDisplayLanguage(language: string, locale: string, sentenceCase?: boole
**示例:** **示例:**
```js ```js
try { try {
var displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese
} catch(error) { } catch(error) {
console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -121,7 +121,7 @@ static getSystemLanguages(): Array&lt;string&gt; ...@@ -121,7 +121,7 @@ static getSystemLanguages(): Array&lt;string&gt;
**示例:** **示例:**
```js ```js
try { try {
var systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ] let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ]
} catch(error) { } catch(error) {
console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -158,7 +158,7 @@ static getSystemCountries(language: string): Array&lt;string&gt; ...@@ -158,7 +158,7 @@ static getSystemCountries(language: string): Array&lt;string&gt;
**示例:** **示例:**
```js ```js
try { try {
var systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ],共计240个国家或地区 let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ],共计240个国家或地区
} catch(error) { } catch(error) {
console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -196,7 +196,7 @@ static isSuggested(language: string, region?: string): boolean ...@@ -196,7 +196,7 @@ static isSuggested(language: string, region?: string): boolean
**示例:** **示例:**
```js ```js
try { try {
var res = I18n.System.isSuggested('zh', 'CN'); // res = true let res = I18n.System.isSuggested('zh', 'CN'); // res = true
} catch(error) { } catch(error) {
console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -227,7 +227,7 @@ static getSystemLanguage(): string ...@@ -227,7 +227,7 @@ static getSystemLanguage(): string
**示例:** **示例:**
```js ```js
try { try {
var systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage为当前系统语言 let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage为当前系统语言
} catch(error) { } catch(error) {
console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -293,7 +293,7 @@ static getSystemRegion(): string ...@@ -293,7 +293,7 @@ static getSystemRegion(): string
**示例:** **示例:**
```js ```js
try { try {
var systemRegion = I18n.System.getSystemRegion(); // 获取系统当前地区设置 let systemRegion = I18n.System.getSystemRegion(); // 获取系统当前地区设置
} catch(error) { } catch(error) {
console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -359,7 +359,7 @@ static getSystemLocale(): string ...@@ -359,7 +359,7 @@ static getSystemLocale(): string
**示例:** **示例:**
```js ```js
try { try {
var systemLocale = I18n.System.getSystemLocale(); // 获取系统当前Locale let systemLocale = I18n.System.getSystemLocale(); // 获取系统当前Locale
} catch(error) { } catch(error) {
console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -425,7 +425,7 @@ static is24HourClock(): boolean ...@@ -425,7 +425,7 @@ static is24HourClock(): boolean
**示例:** **示例:**
```js ```js
try { try {
var is24HourClock = I18n.System.is24HourClock(); // 系统24小时开关是否开启 let is24HourClock = I18n.System.is24HourClock(); // 系统24小时开关是否开启
} catch(error) { } catch(error) {
console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -497,8 +497,8 @@ static addPreferredLanguage(language: string, index?: number): void ...@@ -497,8 +497,8 @@ static addPreferredLanguage(language: string, index?: number): void
**示例:** **示例:**
```js ```js
// 将语言zh-CN添加到系统偏好语言列表中 // 将语言zh-CN添加到系统偏好语言列表中
var language = 'zh-CN'; let language = 'zh-CN';
var index = 0; let index = 0;
try { try {
I18n.System.addPreferredLanguage(language, index); // 将zh-CN添加到系统偏好语言列表的第1位 I18n.System.addPreferredLanguage(language, index); // 将zh-CN添加到系统偏好语言列表的第1位
} catch(error) { } catch(error) {
...@@ -535,7 +535,7 @@ static removePreferredLanguage(index: number): void ...@@ -535,7 +535,7 @@ static removePreferredLanguage(index: number): void
**示例:** **示例:**
```js ```js
// 删除系统偏好语言列表中的第一个偏好语言 // 删除系统偏好语言列表中的第一个偏好语言
var index = 0; let index = 0;
try { try {
I18n.System.removePreferredLanguage(index); I18n.System.removePreferredLanguage(index);
} catch(error) { } catch(error) {
...@@ -568,7 +568,7 @@ static getPreferredLanguageList(): Array&lt;string&gt; ...@@ -568,7 +568,7 @@ static getPreferredLanguageList(): Array&lt;string&gt;
**示例:** **示例:**
```js ```js
try { try {
var preferredLanguageList = I18n.System.getPreferredLanguageList(); // 获取系统当前偏好语言列表 let preferredLanguageList = I18n.System.getPreferredLanguageList(); // 获取系统当前偏好语言列表
} catch(error) { } catch(error) {
console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -599,7 +599,7 @@ static getFirstPreferredLanguage(): string ...@@ -599,7 +599,7 @@ static getFirstPreferredLanguage(): string
**示例:** **示例:**
```js ```js
try { try {
var firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // 获取系统当前偏好语言列表中的第一个偏好语言 let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // 获取系统当前偏好语言列表中的第一个偏好语言
} catch(error) { } catch(error) {
console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -630,7 +630,7 @@ static getAppPreferredLanguage(): string ...@@ -630,7 +630,7 @@ static getAppPreferredLanguage(): string
**示例:** **示例:**
```js ```js
try { try {
var appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // 获取应用偏好语言 let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // 获取应用偏好语言
} catch(error) { } catch(error) {
console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -696,7 +696,7 @@ static getUsingLocalDigit(): boolean ...@@ -696,7 +696,7 @@ static getUsingLocalDigit(): boolean
**示例:** **示例:**
```ts ```ts
try { try {
var status = I18n.System.getUsingLocalDigit(); // 判断本地化数字开关是否打开 let status = I18n.System.getUsingLocalDigit(); // 判断本地化数字开关是否打开
} catch(error) { } catch(error) {
console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`)
} }
...@@ -776,8 +776,8 @@ setTime(date: Date): void ...@@ -776,8 +776,8 @@ setTime(date: Date): void
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("en-US", "gregory"); let calendar = I18n.getCalendar("en-US", "gregory");
var date = new Date(2021, 10, 7, 8, 0, 0, 0); let date = new Date(2021, 10, 7, 8, 0, 0, 0);
calendar.setTime(date); calendar.setTime(date);
``` ```
...@@ -798,7 +798,7 @@ setTime(time: number): void ...@@ -798,7 +798,7 @@ setTime(time: number): void
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("en-US", "gregory"); let calendar = I18n.getCalendar("en-US", "gregory");
calendar.setTime(10540800000); calendar.setTime(10540800000);
``` ```
...@@ -824,7 +824,7 @@ set(year: number, month: number, date:number, hour?: number, minute?: number, se ...@@ -824,7 +824,7 @@ set(year: number, month: number, date:number, hour?: number, minute?: number, se
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00
``` ```
...@@ -845,7 +845,7 @@ setTimeZone(timezone: string): void ...@@ -845,7 +845,7 @@ setTimeZone(timezone: string): void
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
calendar.setTimeZone("Asia/Shanghai"); calendar.setTimeZone("Asia/Shanghai");
``` ```
...@@ -866,9 +866,9 @@ getTimeZone(): string ...@@ -866,9 +866,9 @@ getTimeZone(): string
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
calendar.setTimeZone("Asia/Shanghai"); calendar.setTimeZone("Asia/Shanghai");
var timezone = calendar.getTimeZone(); // timezone = "Asia/Shanghai" let timezone = calendar.getTimeZone(); // timezone = "Asia/Shanghai"
``` ```
...@@ -888,8 +888,8 @@ getFirstDayOfWeek(): number ...@@ -888,8 +888,8 @@ getFirstDayOfWeek(): number
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("en-US", "gregory"); let calendar = I18n.getCalendar("en-US", "gregory");
var firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1
``` ```
...@@ -909,9 +909,9 @@ setFirstDayOfWeek(value: number): void ...@@ -909,9 +909,9 @@ setFirstDayOfWeek(value: number): void
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
calendar.setFirstDayOfWeek(3); calendar.setFirstDayOfWeek(3);
var firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3 let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3
``` ```
...@@ -931,8 +931,8 @@ getMinimalDaysInFirstWeek(): number ...@@ -931,8 +931,8 @@ getMinimalDaysInFirstWeek(): number
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1 let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1
``` ```
...@@ -952,9 +952,9 @@ setMinimalDaysInFirstWeek(value: number): void ...@@ -952,9 +952,9 @@ setMinimalDaysInFirstWeek(value: number): void
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
calendar.setMinimalDaysInFirstWeek(3); calendar.setMinimalDaysInFirstWeek(3);
var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3
``` ```
...@@ -980,9 +980,9 @@ get(field: string): number ...@@ -980,9 +980,9 @@ get(field: string): number
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00
hourOfDay = calendar.get("hour_of_day"); // hourOfDay = 8 let hourOfDay = calendar.get("hour_of_day"); // hourOfDay = 8
``` ```
...@@ -1008,8 +1008,8 @@ getDisplayName(locale: string): string ...@@ -1008,8 +1008,8 @@ getDisplayName(locale: string): string
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("en-US", "buddhist"); let calendar = I18n.getCalendar("en-US", "buddhist");
var calendarName = calendar.getDisplayName("zh"); // calendarName = "佛历" let calendarName = calendar.getDisplayName("zh"); // calendarName = "佛历"
``` ```
...@@ -1035,10 +1035,10 @@ isWeekend(date?: Date): boolean ...@@ -1035,10 +1035,10 @@ isWeekend(date?: Date): boolean
**示例:** **示例:**
```js ```js
var calendar = I18n.getCalendar("zh-Hans"); let calendar = I18n.getCalendar("zh-Hans");
calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00
calendar.isWeekend(); // false calendar.isWeekend(); // false
var date = new Date(2011, 11, 6, 9, 0, 0); let date = new Date(2011, 11, 6, 9, 0, 0);
calendar.isWeekend(date); // true calendar.isWeekend(date); // true
``` ```
...@@ -1063,7 +1063,7 @@ constructor(country: string, options?: PhoneNumberFormatOptions) ...@@ -1063,7 +1063,7 @@ constructor(country: string, options?: PhoneNumberFormatOptions)
**示例:** **示例:**
```js ```js
var phoneNumberFormat= new I18n.PhoneNumberFormat("CN", {"type": "E164"}); let phoneNumberFormat= new I18n.PhoneNumberFormat("CN", {"type": "E164"});
``` ```
...@@ -1089,8 +1089,8 @@ isValidNumber(number: string): boolean ...@@ -1089,8 +1089,8 @@ isValidNumber(number: string): boolean
**示例:** **示例:**
```js ```js
var phonenumberfmt = new I18n.PhoneNumberFormat("CN"); let phonenumberfmt = new I18n.PhoneNumberFormat("CN");
var isValidNumber = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true let isValidNumber = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true
``` ```
...@@ -1116,8 +1116,8 @@ format(number: string): string ...@@ -1116,8 +1116,8 @@ format(number: string): string
**示例:** **示例:**
```js ```js
var phonenumberfmt = new I18n.PhoneNumberFormat("CN"); let phonenumberfmt = new I18n.PhoneNumberFormat("CN");
var formattedPhoneNumber = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312" let formattedPhoneNumber = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312"
``` ```
...@@ -1144,8 +1144,8 @@ getLocationName(number: string, locale: string): string ...@@ -1144,8 +1144,8 @@ getLocationName(number: string, locale: string): string
**示例:** **示例:**
```js ```js
var phonenumberfmt = new I18n.PhoneNumberFormat("CN"); let phonenumberfmt = new I18n.PhoneNumberFormat("CN");
var locationName = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "广东省湛江市" let locationName = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "广东省湛江市"
``` ```
...@@ -1194,7 +1194,7 @@ getInstance(locale?:string): IndexUtil ...@@ -1194,7 +1194,7 @@ getInstance(locale?:string): IndexUtil
**示例:** **示例:**
```js ```js
var indexUtil= I18n.getInstance("zh-CN"); let indexUtil= I18n.getInstance("zh-CN");
``` ```
...@@ -1217,10 +1217,10 @@ getIndexList(): Array&lt;string&gt; ...@@ -1217,10 +1217,10 @@ getIndexList(): Array&lt;string&gt;
**示例:** **示例:**
```js ```js
var indexUtil = I18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
// indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", // indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
// "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ] // "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ]
var indexList = indexUtil.getIndexList(); let indexList = indexUtil.getIndexList();
``` ```
...@@ -1240,7 +1240,7 @@ addLocale(locale: string): void ...@@ -1240,7 +1240,7 @@ addLocale(locale: string): void
**示例:** **示例:**
```js ```js
var indexUtil = I18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
indexUtil.addLocale("en-US"); indexUtil.addLocale("en-US");
``` ```
...@@ -1267,8 +1267,8 @@ getIndex(text: string): string ...@@ -1267,8 +1267,8 @@ getIndex(text: string): string
**示例:** **示例:**
```js ```js
var indexUtil= I18n.getInstance("zh-CN"); let indexUtil= I18n.getInstance("zh-CN");
var index = indexUtil.getIndex("hi"); // index = "H" let index = indexUtil.getIndex("hi"); // index = "H"
``` ```
...@@ -1294,7 +1294,7 @@ getLineInstance(locale: string): BreakIterator ...@@ -1294,7 +1294,7 @@ getLineInstance(locale: string): BreakIterator
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
``` ```
...@@ -1317,7 +1317,7 @@ setLineBreakText(text: string): void ...@@ -1317,7 +1317,7 @@ setLineBreakText(text: string): void
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); // 设置短句文本 iterator.setLineBreakText("Apple is my favorite fruit."); // 设置短句文本
``` ```
...@@ -1338,9 +1338,9 @@ getLineBreakText(): string ...@@ -1338,9 +1338,9 @@ getLineBreakText(): string
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var breakText = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit." let breakText = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit."
``` ```
...@@ -1360,9 +1360,9 @@ current(): number ...@@ -1360,9 +1360,9 @@ current(): number
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var currentPos = iterator.current(); // currentPos = 0 let currentPos = iterator.current(); // currentPos = 0
``` ```
...@@ -1382,9 +1382,9 @@ first(): number ...@@ -1382,9 +1382,9 @@ first(): number
**示例:** **示例:**
```js ```js
var iterator = i18n.getLineInstance("en"); let iterator = i18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var firstPos = iterator.first(); // firstPos = 0 let firstPos = iterator.first(); // firstPos = 0
``` ```
...@@ -1404,9 +1404,9 @@ last(): number ...@@ -1404,9 +1404,9 @@ last(): number
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var lastPos = iterator.last(); // lastPos = 27 let lastPos = iterator.last(); // lastPos = 27
``` ```
...@@ -1432,9 +1432,9 @@ next(index?: number): number ...@@ -1432,9 +1432,9 @@ next(index?: number): number
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var pos = iterator.first(); // pos = 0 let pos = iterator.first(); // pos = 0
pos = iterator.next(); // pos = 6 pos = iterator.next(); // pos = 6
pos = iterator.next(10); // pos = -1 pos = iterator.next(10); // pos = -1
``` ```
...@@ -1456,9 +1456,9 @@ previous(): number ...@@ -1456,9 +1456,9 @@ previous(): number
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var pos = iterator.first(); // pos = 0 let pos = iterator.first(); // pos = 0
pos = iterator.next(3); // pos = 12 pos = iterator.next(3); // pos = 12
pos = iterator.previous(); // pos = 9 pos = iterator.previous(); // pos = 9
``` ```
...@@ -1486,9 +1486,9 @@ following(offset: number): number ...@@ -1486,9 +1486,9 @@ following(offset: number): number
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var pos = iterator.following(0); // pos = 6 let pos = iterator.following(0); // pos = 6
pos = iterator.following(100); // pos = -1 pos = iterator.following(100); // pos = -1
pos = iterator.current(); // pos = 27 pos = iterator.current(); // pos = 27
``` ```
...@@ -1516,9 +1516,9 @@ isBoundary(offset: number): boolean ...@@ -1516,9 +1516,9 @@ isBoundary(offset: number): boolean
**示例:** **示例:**
```js ```js
var iterator = I18n.getLineInstance("en"); let iterator = I18n.getLineInstance("en");
iterator.setLineBreakText("Apple is my favorite fruit."); iterator.setLineBreakText("Apple is my favorite fruit.");
var isBoundary = iterator.isBoundary(0); // isBoundary = true; let isBoundary = iterator.isBoundary(0); // isBoundary = true;
isBoundary = iterator.isBoundary(5); // isBoundary = false; isBoundary = iterator.isBoundary(5); // isBoundary = false;
``` ```
...@@ -1545,7 +1545,7 @@ getTimeZone(zoneID?: string): TimeZone ...@@ -1545,7 +1545,7 @@ getTimeZone(zoneID?: string): TimeZone
**示例:** **示例:**
```js ```js
var timezone = I18n.getTimeZone(); let timezone = I18n.getTimeZone();
``` ```
...@@ -1568,8 +1568,8 @@ getID(): string ...@@ -1568,8 +1568,8 @@ getID(): string
**示例:** **示例:**
```js ```js
var timezone = I18n.getTimeZone(); let timezone = I18n.getTimeZone();
var timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai"
``` ```
...@@ -1596,8 +1596,8 @@ getDisplayName(locale?: string, isDST?: boolean): string ...@@ -1596,8 +1596,8 @@ getDisplayName(locale?: string, isDST?: boolean): string
**示例:** **示例:**
```js ```js
var timezone = I18n.getTimeZone(); let timezone = I18n.getTimeZone();
var timezoneName = timezone.getDisplayName("zh-CN", false); // timezoneName = "中国标准时间" let timezoneName = timezone.getDisplayName("zh-CN", false); // timezoneName = "中国标准时间"
``` ```
...@@ -1617,8 +1617,8 @@ getRawOffset(): number ...@@ -1617,8 +1617,8 @@ getRawOffset(): number
**示例:** **示例:**
```js ```js
var timezone = I18n.getTimeZone(); let timezone = I18n.getTimeZone();
var offset = timezone.getRawOffset(); // offset = 28800000 let offset = timezone.getRawOffset(); // offset = 28800000
``` ```
...@@ -1638,8 +1638,8 @@ getOffset(date?: number): number ...@@ -1638,8 +1638,8 @@ getOffset(date?: number): number
**示例:** **示例:**
```js ```js
var timezone = I18n.getTimeZone(); let timezone = I18n.getTimeZone();
var offset = timezone.getOffset(1234567890); // offset = 28800000 let offset = timezone.getOffset(1234567890); // offset = 28800000
``` ```
...@@ -1660,7 +1660,7 @@ static getAvailableIDs(): Array&lt;string&gt; ...@@ -1660,7 +1660,7 @@ static getAvailableIDs(): Array&lt;string&gt;
**示例:** **示例:**
```ts ```ts
// ids = ["America/Adak", "America/Anchorage", "America/Bogota", "America/Denver", "America/Los_Angeles", "America/Montevideo", "America/Santiago", "America/Sao_Paulo", "Asia/Ashgabat", "Asia/Hovd", "Asia/Jerusalem", "Asia/Magadan", "Asia/Omsk", "Asia/Shanghai", "Asia/Tokyo", "Asia/Yerevan", "Atlantic/Cape_Verde", "Australia/Lord_Howe", "Europe/Dublin", "Europe/London", "Europe/Moscow", "Pacific/Auckland", "Pacific/Easter", "Pacific/Pago-Pago"], 当前共支持24个时区 // ids = ["America/Adak", "America/Anchorage", "America/Bogota", "America/Denver", "America/Los_Angeles", "America/Montevideo", "America/Santiago", "America/Sao_Paulo", "Asia/Ashgabat", "Asia/Hovd", "Asia/Jerusalem", "Asia/Magadan", "Asia/Omsk", "Asia/Shanghai", "Asia/Tokyo", "Asia/Yerevan", "Atlantic/Cape_Verde", "Australia/Lord_Howe", "Europe/Dublin", "Europe/London", "Europe/Moscow", "Pacific/Auckland", "Pacific/Easter", "Pacific/Pago-Pago"], 当前共支持24个时区
var ids = I18n.TimeZone.getAvailableIDs(); let ids = I18n.TimeZone.getAvailableIDs();
``` ```
...@@ -1681,7 +1681,7 @@ static getAvailableZoneCityIDs(): Array&lt;string&gt; ...@@ -1681,7 +1681,7 @@ static getAvailableZoneCityIDs(): Array&lt;string&gt;
**示例:** **示例:**
```ts ```ts
// cityIDs = ["Auckland", "Magadan", "Lord Howe Island", "Tokyo", "Shanghai", "Hovd", "Omsk", "Ashgabat", "Yerevan", "Moscow", "Tel Aviv", "Dublin", "London", "Praia", "Montevideo", "Brasília", "Santiago", "Bogotá", "Easter Island", "Salt Lake City", "Los Angeles", "Anchorage", "Adak", "Pago Pago"],当前共支持24个时区城市 // cityIDs = ["Auckland", "Magadan", "Lord Howe Island", "Tokyo", "Shanghai", "Hovd", "Omsk", "Ashgabat", "Yerevan", "Moscow", "Tel Aviv", "Dublin", "London", "Praia", "Montevideo", "Brasília", "Santiago", "Bogotá", "Easter Island", "Salt Lake City", "Los Angeles", "Anchorage", "Adak", "Pago Pago"],当前共支持24个时区城市
var cityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); let cityIDs = I18n.TimeZone.getAvailableZoneCityIDs();
``` ```
...@@ -1708,7 +1708,7 @@ static getCityDisplayName(cityID: string, locale: string): string ...@@ -1708,7 +1708,7 @@ static getCityDisplayName(cityID: string, locale: string): string
**示例:** **示例:**
```ts ```ts
var displayName = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "上海(中国)" let displayName = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "上海(中国)"
``` ```
...@@ -1734,7 +1734,7 @@ static getTimezoneFromCity(cityID: string): TimeZone ...@@ -1734,7 +1734,7 @@ static getTimezoneFromCity(cityID: string): TimeZone
**示例:** **示例:**
```ts ```ts
var timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai"); let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai");
``` ```
...@@ -1759,7 +1759,7 @@ static getAvailableIDs(): string[] ...@@ -1759,7 +1759,7 @@ static getAvailableIDs(): string[]
```ts ```ts
// ids = ["ASCII-Latin", "Accents-Any", "Amharic-Latin/BGN", ...],共支持671个id // ids = ["ASCII-Latin", "Accents-Any", "Amharic-Latin/BGN", ...],共支持671个id
// 每一个id由使用中划线分割的两部分组成,格式为 source-destination // 每一个id由使用中划线分割的两部分组成,格式为 source-destination
var ids = I18n.Transliterator.getAvailableIDs(); let ids = I18n.Transliterator.getAvailableIDs();
``` ```
...@@ -1785,7 +1785,7 @@ static getInstance(id: string): Transliterator ...@@ -1785,7 +1785,7 @@ static getInstance(id: string): Transliterator
**示例:** **示例:**
```ts ```ts
var transliterator = I18n.Transliterator.getInstance("Any-Latn"); let transliterator = I18n.Transliterator.getInstance("Any-Latn");
``` ```
...@@ -1811,8 +1811,8 @@ transform(text: string): string ...@@ -1811,8 +1811,8 @@ transform(text: string): string
**示例:** **示例:**
```ts ```ts
var transliterator = I18n.Transliterator.getInstance("Any-Latn"); let transliterator = I18n.Transliterator.getInstance("Any-Latn");
var res = transliterator.transform("中国"); // res = "zhōng guó" let res = transliterator.transform("中国"); // res = "zhōng guó"
``` ```
...@@ -1841,7 +1841,7 @@ static isDigit(char: string): boolean ...@@ -1841,7 +1841,7 @@ static isDigit(char: string): boolean
**示例:** **示例:**
```js ```js
var isdigit = I18n.Unicode.isDigit("1"); // isdigit = true let isdigit = I18n.Unicode.isDigit("1"); // isdigit = true
``` ```
...@@ -1867,7 +1867,7 @@ static isSpaceChar(char: string): boolean ...@@ -1867,7 +1867,7 @@ static isSpaceChar(char: string): boolean
**示例:** **示例:**
```js ```js
var isspacechar = I18n.Unicode.isSpaceChar("a"); // isspacechar = false let isspacechar = I18n.Unicode.isSpaceChar("a"); // isspacechar = false
``` ```
...@@ -1893,7 +1893,7 @@ static isWhitespace(char: string): boolean ...@@ -1893,7 +1893,7 @@ static isWhitespace(char: string): boolean
**示例:** **示例:**
```js ```js
var iswhitespace = I18n.Unicode.isWhitespace("a"); // iswhitespace = false let iswhitespace = I18n.Unicode.isWhitespace("a"); // iswhitespace = false
``` ```
...@@ -1919,7 +1919,7 @@ static isRTL(char: string): boolean ...@@ -1919,7 +1919,7 @@ static isRTL(char: string): boolean
**示例:** **示例:**
```js ```js
var isrtl = I18n.Unicode.isRTL("a"); // isrtl = false let isrtl = I18n.Unicode.isRTL("a"); // isrtl = false
``` ```
...@@ -1945,7 +1945,7 @@ static isIdeograph(char: string): boolean ...@@ -1945,7 +1945,7 @@ static isIdeograph(char: string): boolean
**示例:** **示例:**
```js ```js
var isideograph = I18n.Unicode.isIdeograph("a"); // isideograph = false let isideograph = I18n.Unicode.isIdeograph("a"); // isideograph = false
``` ```
...@@ -1971,7 +1971,7 @@ static isLetter(char: string): boolean ...@@ -1971,7 +1971,7 @@ static isLetter(char: string): boolean
**示例:** **示例:**
```js ```js
var isletter = I18n.Unicode.isLetter("a"); // isletter = true let isletter = I18n.Unicode.isLetter("a"); // isletter = true
``` ```
...@@ -1997,7 +1997,7 @@ static isLowerCase(char: string): boolean ...@@ -1997,7 +1997,7 @@ static isLowerCase(char: string): boolean
**示例:** **示例:**
```js ```js
var islowercase = I18n.Unicode.isLowerCase("a"); // islowercase = true let islowercase = I18n.Unicode.isLowerCase("a"); // islowercase = true
``` ```
...@@ -2023,7 +2023,7 @@ static isUpperCase(char: string): boolean ...@@ -2023,7 +2023,7 @@ static isUpperCase(char: string): boolean
**示例:** **示例:**
```js ```js
var isuppercase = I18n.Unicode.isUpperCase("a"); // isuppercase = false let isuppercase = I18n.Unicode.isUpperCase("a"); // isuppercase = false
``` ```
...@@ -2049,7 +2049,7 @@ static getType(char: string): string ...@@ -2049,7 +2049,7 @@ static getType(char: string): string
**示例:** **示例:**
```js ```js
var type = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER" let type = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER"
``` ```
...@@ -2082,7 +2082,7 @@ static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: ...@@ -2082,7 +2082,7 @@ static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale:
**示例:** **示例:**
```js ```js
var res = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters let res = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters
``` ```
...@@ -2108,7 +2108,7 @@ static getDateOrder(locale: string): string ...@@ -2108,7 +2108,7 @@ static getDateOrder(locale: string): string
**示例:** **示例:**
```js ```js
var order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d"
``` ```
...@@ -2138,7 +2138,7 @@ getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): stri ...@@ -2138,7 +2138,7 @@ getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): stri
**示例:** **示例:**
```js ```js
var countryName = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true let countryName = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true
countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true
``` ```
...@@ -2169,7 +2169,7 @@ getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): st ...@@ -2169,7 +2169,7 @@ getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): st
**示例:** **示例:**
```js ```js
var languageName = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese" let languageName = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese"
languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese" languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese"
``` ```
...@@ -2192,7 +2192,7 @@ getSystemLanguage(): string ...@@ -2192,7 +2192,7 @@ getSystemLanguage(): string
**示例:** **示例:**
```js ```js
var systemLanguage = I18n.getSystemLanguage(); // 返回当前系统语言 let systemLanguage = I18n.getSystemLanguage(); // 返回当前系统语言
``` ```
...@@ -2214,7 +2214,7 @@ getSystemRegion(): string ...@@ -2214,7 +2214,7 @@ getSystemRegion(): string
**示例:** **示例:**
```js ```js
var region = I18n.getSystemRegion(); // 返回当前系统地区 let region = I18n.getSystemRegion(); // 返回当前系统地区
``` ```
...@@ -2236,7 +2236,7 @@ getSystemLocale(): string ...@@ -2236,7 +2236,7 @@ getSystemLocale(): string
**示例:** **示例:**
```js ```js
var locale = I18n.getSystemLocale(); // 返回系统Locale let locale = I18n.getSystemLocale(); // 返回系统Locale
``` ```
...@@ -2258,7 +2258,7 @@ is24HourClock(): boolean ...@@ -2258,7 +2258,7 @@ is24HourClock(): boolean
**示例:** **示例:**
```js ```js
var is24HourClock = I18n.is24HourClock(); let is24HourClock = I18n.is24HourClock();
``` ```
...@@ -2289,7 +2289,7 @@ set24HourClock(option: boolean): boolean ...@@ -2289,7 +2289,7 @@ set24HourClock(option: boolean): boolean
**示例:** **示例:**
```js ```js
// 将系统时间设置为24小时制 // 将系统时间设置为24小时制
var success = I18n.set24HourClock(true); let success = I18n.set24HourClock(true);
``` ```
...@@ -2321,9 +2321,9 @@ addPreferredLanguage(language: string, index?: number): boolean ...@@ -2321,9 +2321,9 @@ addPreferredLanguage(language: string, index?: number): boolean
**示例:** **示例:**
```js ```js
// 将语言zh-CN添加到系统偏好语言列表中 // 将语言zh-CN添加到系统偏好语言列表中
var language = 'zh-CN'; let language = 'zh-CN';
var index = 0; let index = 0;
var success = I18n.addPreferredLanguage(language, index); let success = I18n.addPreferredLanguage(language, index);
``` ```
...@@ -2354,8 +2354,8 @@ removePreferredLanguage(index: number): boolean ...@@ -2354,8 +2354,8 @@ removePreferredLanguage(index: number): boolean
**示例:** **示例:**
```js ```js
// 删除系统偏好语言列表中的第一个偏好语言 // 删除系统偏好语言列表中的第一个偏好语言
var index = 0; let index = 0;
var success = I18n.removePreferredLanguage(index); let success = I18n.removePreferredLanguage(index);
``` ```
...@@ -2377,7 +2377,7 @@ getPreferredLanguageList(): Array&lt;string&gt; ...@@ -2377,7 +2377,7 @@ getPreferredLanguageList(): Array&lt;string&gt;
**示例:** **示例:**
```js ```js
var preferredLanguageList = I18n.getPreferredLanguageList(); // 获取系统偏好语言列表 let preferredLanguageList = I18n.getPreferredLanguageList(); // 获取系统偏好语言列表
``` ```
...@@ -2399,7 +2399,7 @@ getFirstPreferredLanguage(): string ...@@ -2399,7 +2399,7 @@ getFirstPreferredLanguage(): string
**示例:** **示例:**
```js ```js
var firstPreferredLanguage = I18n.getFirstPreferredLanguage(); let firstPreferredLanguage = I18n.getFirstPreferredLanguage();
``` ```
......
...@@ -10,15 +10,15 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传 ...@@ -10,15 +10,15 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | 否 | 表示运行指定Ability的设备ID。 | | deviceId | string | 否 | 表示运行指定Ability的设备ID。如果未设置该字段,则表明指定本设备。 |
| bundleName | string | 否 | 表示Bundle名称。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 | | bundleName | string | 否 | 表示Bundle名称。 |
| abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | | abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 |
| uri | string | 否 | 表示Uri。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | | uri | string | 否 | 表示Uri。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 |
| type | string | 否 | 表示MIME type类型,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | | type | string | 否 | 表示MIME type类型,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 |
| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantConstant.Flags)。 | | flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantConstant.Flags)。 |
| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。 | | action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md) |
| parameters | {[key: string]: any} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | | parameters | {[key: string]: any} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 |
| entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 | | entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity) |
| moduleName<sup>9+</sup> | string | 否 | 表示待启动的Ability所属的模块(module)。 | | moduleName<sup>9+</sup> | string | 否 | 表示待启动的Ability所属的模块(module)。 |
**示例:** **示例:**
......
...@@ -48,9 +48,9 @@ constructor() ...@@ -48,9 +48,9 @@ constructor()
**示例:** **示例:**
```js ```js
// 默认构造函数使用系统当前locale创建Locale对象 // 默认构造函数使用系统当前locale创建Locale对象
var locale = new Intl.Locale() let locale = new Intl.Locale()
// 返回系统当前localel // 返回系统当前localel
var localeID = locale.toString() let localeID = locale.toString()
``` ```
...@@ -72,8 +72,8 @@ constructor(locale: string, options?: LocaleOptions) ...@@ -72,8 +72,8 @@ constructor(locale: string, options?: LocaleOptions)
**示例:** **示例:**
```js ```js
// 创建 "zh-CN" Locale对象 // 创建 "zh-CN" Locale对象
var locale = new Intl.Locale("zh-CN") let locale = new Intl.Locale("zh-CN")
var localeID = locale.toString() // localeID = "zh-CN" let localeID = locale.toString() // localeID = "zh-CN"
``` ```
...@@ -94,8 +94,8 @@ toString(): string ...@@ -94,8 +94,8 @@ toString(): string
**示例:** **示例:**
```js ```js
// 创建 "en-GB" Locale对象 // 创建 "en-GB" Locale对象
var locale = new Intl.Locale("en-GB"); let locale = new Intl.Locale("en-GB");
var localeID = locale.toString(); // localeID = "en-GB" let localeID = locale.toString(); // localeID = "en-GB"
``` ```
...@@ -116,16 +116,16 @@ maximize(): Locale ...@@ -116,16 +116,16 @@ maximize(): Locale
**示例:** **示例:**
```js ```js
// 创建 "zh" Locale对象 // 创建 "zh" Locale对象
var locale = new Intl.Locale("zh"); let locale = new Intl.Locale("zh");
// 补齐Locale对象的脚本和地区 // 补齐Locale对象的脚本和地区
locale.maximize(); let maximizedLocale = locale.maximize();
var localeID = locale.toString(); // localeID = "zh-Hans-CN" let localeID = maximizedLocale.toString(); // localeID = "zh-Hans-CN"
// 创建 "en-US" Locale对象 // 创建 "en-US" Locale对象
locale = new Intl.Locale("en-US"); locale = new Intl.Locale("en-US");
// 补齐Locale对象的脚本 // 补齐Locale对象的脚本
locale.maximize(); maximizedLocale = locale.maximize();
localeID = locale.toString(); // localeID = "en-Latn-US" localeID = maximizedLocale.toString(); // localeID = "en-Latn-US"
``` ```
...@@ -146,16 +146,16 @@ minimize(): Locale ...@@ -146,16 +146,16 @@ minimize(): Locale
**示例:** **示例:**
```js ```js
// 创建 "zh-Hans-CN" Locale对象 // 创建 "zh-Hans-CN" Locale对象
var locale = new Intl.Locale("zh-Hans-CN"); let locale = new Intl.Locale("zh-Hans-CN");
// 去除Locale对象的脚本和地区 // 去除Locale对象的脚本和地区
locale.minimize(); let minimizedLocale = locale.minimize();
var localeID = locale.toString(); // localeID = "zh" let localeID = minimizedLocale.toString(); // localeID = "zh"
// 创建 "en-US" Locale对象 // 创建 "en-US" Locale对象
locale = new Intl.Locale("en-US"); locale = new Intl.Locale("en-US");
// 去除Locale对象的地区 // 去除Locale对象的地区
locale.minimize(); minimizedLocale = locale.minimize();
localeID = locale.toString(); // localeID = "en" localeID = minimizedLocale.toString(); // localeID = "en"
``` ```
...@@ -189,7 +189,7 @@ constructor() ...@@ -189,7 +189,7 @@ constructor()
**示例:** **示例:**
```js ```js
// 使用系统当前locale创建DateTimeFormat对象 // 使用系统当前locale创建DateTimeFormat对象
var datefmt= new Intl.DateTimeFormat(); let datefmt= new Intl.DateTimeFormat();
``` ```
...@@ -211,14 +211,14 @@ constructor(locale: string | Array&lt;string&gt;, options?: DateTimeOptions) ...@@ -211,14 +211,14 @@ constructor(locale: string | Array&lt;string&gt;, options?: DateTimeOptions)
**示例:** **示例:**
```js ```js
// 使用 "zh-CN" locale创建DateTimeFormat对象,日期风格为full,时间风格为medium // 使用 "zh-CN" locale创建DateTimeFormat对象,日期风格为full,时间风格为medium
var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); let datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' });
``` ```
**示例:** **示例:**
```js ```js
// 使用 ["ban", "zh"] locale列表创建DateTimeFormat对象,因为ban为非法LocaleID,因此使用zh Locale创建DateTimeFormat对象 // 使用 ["ban", "zh"] locale列表创建DateTimeFormat对象,因为ban为非法LocaleID,因此使用zh Locale创建DateTimeFormat对象
var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); let datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' });
``` ```
...@@ -244,10 +244,10 @@ format(date: Date): string ...@@ -244,10 +244,10 @@ format(date: Date): string
**示例:** **示例:**
```js ```js
var date = new Date(2021, 11, 17, 3, 24, 0); let date = new Date(2021, 11, 17, 3, 24, 0);
// 使用 en-GB locale创建DateTimeFormat对象 // 使用 en-GB locale创建DateTimeFormat对象
var datefmt = new Intl.DateTimeFormat("en-GB"); let datefmt = new Intl.DateTimeFormat("en-GB");
var formattedDate = datefmt.format(date); // formattedDate "17/12/2021" let formattedDate = datefmt.format(date); // formattedDate "17/12/2021"
// 使用 en-GB locale创建DateTimeFormat对象,dateStyle设置为full,timeStyle设置为medium // 使用 en-GB locale创建DateTimeFormat对象,dateStyle设置为full,timeStyle设置为medium
datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' });
...@@ -278,11 +278,11 @@ formatRange(startDate: Date, endDate: Date): string ...@@ -278,11 +278,11 @@ formatRange(startDate: Date, endDate: Date): string
**示例:** **示例:**
```js ```js
var startDate = new Date(2021, 11, 17, 3, 24, 0); let startDate = new Date(2021, 11, 17, 3, 24, 0);
var endDate = new Date(2021, 11, 18, 3, 24, 0); let endDate = new Date(2021, 11, 18, 3, 24, 0);
// 使用 en-GB locale创建DateTimeFormat对象 // 使用 en-GB locale创建DateTimeFormat对象
var datefmt = new Intl.DateTimeFormat("en-GB"); let datefmt = new Intl.DateTimeFormat("en-GB");
var formattedDateRange = datefmt.formatRange(startDate, endDate); // formattedDateRange = "17/12/2021-18/12/2021" let formattedDateRange = datefmt.formatRange(startDate, endDate); // formattedDateRange = "17/12/2021-18/12/2021"
``` ```
...@@ -302,11 +302,11 @@ resolvedOptions(): DateTimeOptions ...@@ -302,11 +302,11 @@ resolvedOptions(): DateTimeOptions
**示例:** **示例:**
```js ```js
var datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); let datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' });
// 返回DateTimeFormat对象的配置项 // 返回DateTimeFormat对象的配置项
var options = datefmt.resolvedOptions(); let options = datefmt.resolvedOptions();
var dateStyle = options.dateStyle; // dateStyle = "full" let dateStyle = options.dateStyle; // dateStyle = "full"
var timeStyle = options.timeStyle; // timeStyle = "medium" let timeStyle = options.timeStyle; // timeStyle = "medium"
``` ```
...@@ -353,7 +353,7 @@ constructor() ...@@ -353,7 +353,7 @@ constructor()
**示例:** **示例:**
```js ```js
// 使用系统当前locale创建NumberFormat对象 // 使用系统当前locale创建NumberFormat对象
var numfmt = new Intl.NumberFormat(); let numfmt = new Intl.NumberFormat();
``` ```
...@@ -375,7 +375,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: NumberOptions) ...@@ -375,7 +375,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: NumberOptions)
**示例:** **示例:**
```js ```js
// 使用 en-GB locale创建NumberFormat对象,style设置为decimal,notation设置为scientific // 使用 en-GB locale创建NumberFormat对象,style设置为decimal,notation设置为scientific
var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); let numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"});
``` ```
...@@ -403,8 +403,8 @@ format(number: number): string; ...@@ -403,8 +403,8 @@ format(number: number): string;
**示例:** **示例:**
```js ```js
// 使用 ["en-GB", "zh"] locale列表创建NumberFormat对象,因为en-GB为合法LocaleID,因此使用en-GB创建NumberFormat对象 // 使用 ["en-GB", "zh"] locale列表创建NumberFormat对象,因为en-GB为合法LocaleID,因此使用en-GB创建NumberFormat对象
var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"});
var formattedNumber = numfmt.format(1223); // formattedNumber = 1.223E3 let formattedNumber = numfmt.format(1223); // formattedNumber = 1.223E3
``` ```
...@@ -425,11 +425,11 @@ resolvedOptions(): NumberOptions ...@@ -425,11 +425,11 @@ resolvedOptions(): NumberOptions
**示例:** **示例:**
```js ```js
var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"});
// 获取NumberFormat对象配置项 // 获取NumberFormat对象配置项
var options = numfmt.resolvedOptions(); let options = numfmt.resolvedOptions();
var style = options.style; // style = decimal let style = options.style; // style = decimal
var notation = options.notation // notation = scientific let notation = options.notation // notation = scientific
``` ```
...@@ -476,7 +476,7 @@ constructor() ...@@ -476,7 +476,7 @@ constructor()
**示例:** **示例:**
```js ```js
// 使用系统locale创建Collator对象 // 使用系统locale创建Collator对象
var collator = new Intl.Collator(); let collator = new Intl.Collator();
``` ```
...@@ -498,7 +498,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: CollatorOptions) ...@@ -498,7 +498,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: CollatorOptions)
**示例:** **示例:**
```js ```js
// 使用 zh-CN locale创建Collator对象,localeMatcher设置为lookup,usage设置为sort // 使用 zh-CN locale创建Collator对象,localeMatcher设置为lookup,usage设置为sort
var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); let collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"});
``` ```
...@@ -526,9 +526,9 @@ compare(first: string, second: string): number ...@@ -526,9 +526,9 @@ compare(first: string, second: string): number
**示例:** **示例:**
```js ```js
// 使用en-GB locale创建Collator对象 // 使用en-GB locale创建Collator对象
var collator = new Intl.Collator("en-GB"); let collator = new Intl.Collator("en-GB");
// 比较 "first" 和 "second" 的先后顺序 // 比较 "first" 和 "second" 的先后顺序
var compareResult = collator.compare("first", "second"); // compareResult = -1 let compareResult = collator.compare("first", "second"); // compareResult = -1
``` ```
...@@ -548,11 +548,11 @@ resolvedOptions(): CollatorOptions ...@@ -548,11 +548,11 @@ resolvedOptions(): CollatorOptions
**示例:** **示例:**
```js ```js
var collator = new Intl.Collator("zh-Hans", { usage: 'sort', ignorePunctuation: 'true' }); let collator = new Intl.Collator("zh-Hans", { usage: 'sort', ignorePunctuation: true });
// 获取Collator对象的配置项 // 获取Collator对象的配置项
var options = collator.resolvedOptions(); let options = collator.resolvedOptions();
var usage = options.usage; // usage = "sort" let usage = options.usage; // usage = "sort"
var ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true
``` ```
...@@ -566,7 +566,7 @@ resolvedOptions(): CollatorOptions ...@@ -566,7 +566,7 @@ resolvedOptions(): CollatorOptions
| ----------------- | ------- | ---- | ---- | ---------------------------------------- | | ----------------- | ------- | ---- | ---- | ---------------------------------------- |
| localeMatcher | string | 是 | 是 | locale匹配算法,取值范围:"best&nbsp;fit",&nbsp;"lookup"。 | | localeMatcher | string | 是 | 是 | locale匹配算法,取值范围:"best&nbsp;fit",&nbsp;"lookup"。 |
| usage | string | 是 | 是 | 比较的用途,取值范围:"sort",&nbsp;"search"。 | | usage | string | 是 | 是 | 比较的用途,取值范围:"sort",&nbsp;"search"。 |
| sensitivity | string | 是 | 是 | 表示字符串中的哪些差异会导致非零结果值,取值范围:"base",&nbsp;"accent",&nbsp;"case",&nbsp;"variant"。 | | sensitivity | string | 是 | 是 | 表示字符串中的哪些差异会导致非零结果值,取值范围:"base",&nbsp;"accent",&nbsp;"case",&nbsp;"letiant"。 |
| ignorePunctuation | boolean | 是 | 是 | 表示是否忽略标点符号,取值范围:true,&nbsp;false。 | | ignorePunctuation | boolean | 是 | 是 | 表示是否忽略标点符号,取值范围:true,&nbsp;false。 |
| collation | string | 是 | 是 | 排序规则,取值范围:"big5han",&nbsp;"compat",&nbsp;"dict",&nbsp;"direct",&nbsp;"ducet",&nbsp;"eor",&nbsp;"gb2312",&nbsp;"phonebk",&nbsp;"phonetic",&nbsp;"pinyin",&nbsp;"reformed",&nbsp;"searchjl",&nbsp;"stroke",&nbsp;"trad",&nbsp;"unihan",&nbsp;"zhuyin"。 | | collation | string | 是 | 是 | 排序规则,取值范围:"big5han",&nbsp;"compat",&nbsp;"dict",&nbsp;"direct",&nbsp;"ducet",&nbsp;"eor",&nbsp;"gb2312",&nbsp;"phonebk",&nbsp;"phonetic",&nbsp;"pinyin",&nbsp;"reformed",&nbsp;"searchjl",&nbsp;"stroke",&nbsp;"trad",&nbsp;"unihan",&nbsp;"zhuyin"。 |
| numeric | boolean | 是 | 是 | 是否使用数字排序,取值范围:true,&nbsp;false。 | | numeric | boolean | 是 | 是 | 是否使用数字排序,取值范围:true,&nbsp;false。 |
...@@ -580,14 +580,14 @@ resolvedOptions(): CollatorOptions ...@@ -580,14 +580,14 @@ resolvedOptions(): CollatorOptions
constructor() constructor()
创建PluralRules对象 创建单复数对象来计算数字的单复数类别
**系统能力**:SystemCapability.Global.I18n **系统能力**:SystemCapability.Global.I18n
**示例:** **示例:**
```js ```js
// 使用系统locale创建PluralRules对象 // 使用系统locale创建PluralRules对象
var pluralRules = new Intl.PluralRules(); let pluralRules = new Intl.PluralRules();
``` ```
...@@ -595,7 +595,7 @@ constructor() ...@@ -595,7 +595,7 @@ constructor()
constructor(locale: string | Array&lt;string&gt;, options?: PluralRulesOptions) constructor(locale: string | Array&lt;string&gt;, options?: PluralRulesOptions)
创建PluralRules对象 创建单复数对象来计算数字的单复数类别
**系统能力**:SystemCapability.Global.I18n **系统能力**:SystemCapability.Global.I18n
...@@ -609,7 +609,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: PluralRulesOptions) ...@@ -609,7 +609,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: PluralRulesOptions)
**示例:** **示例:**
```js ```js
// 使用 zh-CN locale创建PluralRules对象,localeMatcher设置为lookup,type设置为cardinal // 使用 zh-CN locale创建PluralRules对象,localeMatcher设置为lookup,type设置为cardinal
var pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); let pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"});
``` ```
...@@ -636,9 +636,14 @@ select(n: number): string ...@@ -636,9 +636,14 @@ select(n: number): string
**示例:** **示例:**
```js ```js
// 使用 zh-Hans locale创建PluralRules对象 // 使用 zh-Hans locale创建PluralRules对象
var pluralRules = new Intl.PluralRules("zh-Hans"); let zhPluralRules = new Intl.PluralRules("zh-Hans");
// 计算 zh-Hans locale中数字1对应的单复数类别 // 计算 zh-Hans locale中数字1对应的单复数类别
var plural = pluralRules.select(1); // plural = other let plural = zhPluralRules.select(1); // plural = other
// 使用 en-US locale创建PluralRules对象
let enPluralRules = new Intl.PluralRules("en-US");
// 计算 en-US locale中数字1对应的单复数类别
plural = enPluralRules.select(1); // plural = one
``` ```
...@@ -673,7 +678,7 @@ constructor() ...@@ -673,7 +678,7 @@ constructor()
**示例:** **示例:**
```js ```js
// 使用系统locale创建RelativeTimeFormat对象 // 使用系统locale创建RelativeTimeFormat对象
var relativetimefmt = new Intl.RelativeTimeFormat(); let relativetimefmt = new Intl.RelativeTimeFormat();
``` ```
...@@ -695,7 +700,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: RelativeTimeFormatIn ...@@ -695,7 +700,7 @@ constructor(locale: string | Array&lt;string&gt;, options?: RelativeTimeFormatIn
**示例:** **示例:**
```js ```js
// 使用 zh-CN locale创建RelativeTimeFormat对象,localeMatcher设置为lookup,numeric设置为always,style设置为long // 使用 zh-CN locale创建RelativeTimeFormat对象,localeMatcher设置为lookup,numeric设置为always,style设置为long
var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"});
``` ```
...@@ -723,9 +728,9 @@ format(value: number, unit: string): string ...@@ -723,9 +728,9 @@ format(value: number, unit: string): string
**示例:** **示例:**
```js ```js
// 使用 zh-CN locale创建RelativeTimeFormat对象 // 使用 zh-CN locale创建RelativeTimeFormat对象
var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); let relativetimefmt = new Intl.RelativeTimeFormat("zh-CN");
// 计算 zh-CN locale中数字3,单位quarter的本地化表示 // 计算 zh-CN locale中数字3,单位quarter的本地化表示
var formatResult = relativetimefmt.format(3, "quarter") // formatResult = "3个季度后" let formatResult = relativetimefmt.format(3, "quarter"); // formatResult = "3个季度后"
``` ```
...@@ -753,8 +758,8 @@ formatToParts(value: number, unit: string): Array&lt;object&gt; ...@@ -753,8 +758,8 @@ formatToParts(value: number, unit: string): Array&lt;object&gt;
**示例:** **示例:**
```js ```js
// 使用 en locale创建RelativeTimeFormat对象,numeric设置为auto // 使用 en locale创建RelativeTimeFormat对象,numeric设置为auto
var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); let relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"});
var parts = relativetimefmt.formatToParts(10, "seconds"); // parts = [ {type: "literal", value: "in"}, {type: "integer", value: 10, unit: "second"}, {type: "literal", value: "seconds"} ] let parts = relativetimefmt.formatToParts(10, "seconds"); // parts = [ {type: "literal", value: "in"}, {type: "integer", value: 10, unit: "second"}, {type: "literal", value: "seconds"} ]
``` ```
...@@ -775,10 +780,10 @@ resolvedOptions(): RelativeTimeFormatResolvedOptions ...@@ -775,10 +780,10 @@ resolvedOptions(): RelativeTimeFormatResolvedOptions
**示例:** **示例:**
```js ```js
// 使用 en-GB locale创建RelativeTimeFormat对象 // 使用 en-GB locale创建RelativeTimeFormat对象
var relativetimefmt= new Intl.RelativeTimeFormat("en-GB", { style: "short" }); let relativetimefmt= new Intl.RelativeTimeFormat("en-GB", { style: "short" });
// 获取RelativeTimeFormat对象配置项 // 获取RelativeTimeFormat对象配置项
var options = relativetimefmt.resolvedOptions(); let options = relativetimefmt.resolvedOptions();
var style = options.style; // style = "short" let style = options.style; // style = "short"
``` ```
......
...@@ -10,8 +10,8 @@ ...@@ -10,8 +10,8 @@
## 导入模块 ## 导入模块
``` ```ts
import configuration from '@system.configuration'; import Configuration from '@system.configuration';
``` ```
......
...@@ -2343,7 +2343,7 @@ async function example() { ...@@ -2343,7 +2343,7 @@ async function example() {
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 类型 | 可读 | 可写 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ----- | ---- | ---- | ---- | ---- | | ----- | ---- | ---- | ---- | ---- |
| deviceChange | string | 是 | 是 | 设备 | | deviceChange | string | 是 | 是 | 设备 |
| albumChange | string | 是 | 是 | 相册 | | albumChange | string | 是 | 是 | 相册 |
......
...@@ -6,12 +6,17 @@ ...@@ -6,12 +6,17 @@
libuv是一个跨平台库,基于事件驱动来实现异步I/O,主要作为Node.js的多平台支持库。 [libuv](http://libuv.org/)是一个跨平台库,基于事件驱动来实现异步I/O,主要作为Node.js的多平台支持库。
## 支持的能力 ## 支持的能力
libuv实现了跨平台的基于事件驱动的异步I/O。 [libuv](http://libuv.org/)实现了跨平台的基于事件驱动的异步I/O。
支持标准库接口。 支持标准库接口。
## 接口列表
[libuv支持的API文档](http://docs.libuv.org/en/v1.x/api.html)
...@@ -58,7 +58,7 @@ OsMuxInit ...@@ -58,7 +58,7 @@ OsMuxInit
## 注释 ## 注释
一般的,尽量通过清晰的软件架构,良好的符号命名来提高代码可读性;然后在需要的时候,才辅以注释说明。 一般的,尽量通过清晰的软件架构,良好的符号命名来提高代码可读性;在需要的时候,辅以注释说明。
注释是为了帮助阅读者快速读懂代码,所以要从读者的角度出发,按需注释。 注释是为了帮助阅读者快速读懂代码,所以要从读者的角度出发,按需注释。
......
...@@ -84,7 +84,7 @@ typedef struct tagEvent { ...@@ -84,7 +84,7 @@ typedef struct tagEvent {
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 进行事件读写操作时,事件的第25位为保留位,不可以进行位设置。 > - 进行事件读写操作时,事件的第25bit(`0x02U << 24`)为保留bit位,不可以进行位设置。
> >
> - 对同一事件反复写入,算作一次写入。 > - 对同一事件反复写入,算作一次写入。
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。 任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。
可以通过调整读队列和写队列的超时时间来调整读写接口的阻塞模式,如果将读队列和写队列的超时时间设置为0,就不会挂起任务,接口会直接返回,这就是非阻塞模式。反之,如果将队列和写队列的超时时间设置为大于0的时间,就会以阻塞模式运行。 可以通过调整读队列和写队列的超时时间来调整读写接口的阻塞模式,如果将读队列和写队列的超时时间设置为0,就不会挂起任务,接口会直接返回,这就是非阻塞模式。反之,如果将队列和写队列的超时时间设置为大于0的时间,就会以阻塞模式运行。
消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性: 消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性:
......
...@@ -12,7 +12,7 @@ Perf为性能分析工具,依赖PMU(Performance Monitoring Unit)对采样 ...@@ -12,7 +12,7 @@ Perf为性能分析工具,依赖PMU(Performance Monitoring Unit)对采样
Perf提供2种工作模式,计数模式和采样模式。 Perf提供2种工作模式,计数模式和采样模式。
计数模式仅统计事件发生的次数和耗时,采样模式会收集上下文数据到环形buffer中,需要IDE进行数据解析生成热点函数与热点路径 计数模式仅统计事件发生的次数和耗时,采样模式会收集上下文数据到环形buffer中,需要IDE进行数据解析生成热点函数与热点路径
## 接口说明 ## 接口说明
...@@ -26,19 +26,19 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细 ...@@ -26,19 +26,19 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 开启/停止Perf采样 | LOS_PerfStart:开启采样<br/>LOS_PerfStop:停止采样 | | 开启/停止Perf采样 | LOS_PerfInit : 初始化Perf<br/>LOS_PerfStart:开启采样<br/>LOS_PerfStop:停止采样 |
| 配置Perf采样事件 | LOS_PerfConfig:配置采样事件的类型、周期等 | | 配置Perf采样事件 | LOS_PerfConfig:配置采样事件的类型、周期等 |
| 读取采样数据 | LOS_PerfDataRead:读取采样数据到指定地址 | | 读取采样数据 | LOS_PerfDataRead:读取采样数据到指定地址 |
| 注册采样数据缓冲区的钩子函数 | LOS_PerfNotifyHookReg:注册缓冲区水线到达的处理钩子<br/>LOS_PerfFlushHookReg:注册缓冲区刷cache的钩子 | | 注册采样数据缓冲区的钩子函数 | LOS_PerfNotifyHookReg:注册缓冲区水线到达的处理钩子<br/>LOS_PerfFlushHookReg:注册缓冲区刷cache的钩子 |
1. Perf采样事件的结构体为PerfConfigAttr,详细字段含义及取值详见kernel\include\los_perf.h 1. Perf采样事件的结构体为PerfConfigAttr,详细字段含义及取值详见 [kernel\include\los_perf.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h)
2. 采样数据缓冲区为环形buffer,buffer中读过的区域可以覆盖写,未被读过的区域不能被覆盖写。 2. 采样数据缓冲区为环形buffer,buffer中读过的区域可以覆盖写,未被读过的区域不能被覆盖写。
3. 缓冲区有限,用户可通过注册水线到达的钩子进行buffer溢出提醒或buffer读操作。默认水线值为buffer总大小的1/2。 示例如下: 3. 缓冲区有限,用户可通过注册水线到达的钩子进行buffer溢出提醒或buffer读操作。默认水线值为buffer总大小的1/2。 示例如下:
``` ```c
VOID Example_PerfNotifyHook(VOID) VOID Example_PerfNotifyHook(VOID)
{ {
CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0}; CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0};
...@@ -52,7 +52,7 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细 ...@@ -52,7 +52,7 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细
4. 若perf采样的buffer涉及到CPU跨cache,则用户可通过注册刷cache的钩子,进行cache同步。 示例如下: 4. 若perf采样的buffer涉及到CPU跨cache,则用户可通过注册刷cache的钩子,进行cache同步。 示例如下:
``` ```c
VOID Example_PerfFlushHook(VOID *addr, UINT32 size) VOID Example_PerfFlushHook(VOID *addr, UINT32 size)
{ {
OsCacheFlush(addr, size); /* platform interface */ OsCacheFlush(addr, size); /* platform interface */
...@@ -75,7 +75,7 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细 ...@@ -75,7 +75,7 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细
- ioctl: 用户态Perf控制操作,包括 - ioctl: 用户态Perf控制操作,包括
``` ```c
#define PERF_IOC_MAGIC 'T' #define PERF_IOC_MAGIC 'T'
#define PERF_START _IO(PERF_IOC_MAGIC, 1) #define PERF_START _IO(PERF_IOC_MAGIC, 1)
#define PERF_STOP _IO(PERF_IOC_MAGIC, 2) #define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
...@@ -142,9 +142,11 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细 ...@@ -142,9 +142,11 @@ OpenHarmony LiteOS-A内核的Perf模块提供下面几种功能,接口详细
前提条件:在menuconfig菜单中完成perf模块的配置。 前提条件:在menuconfig菜单中完成perf模块的配置。
该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。
实例代码如下: 实例代码如下:
``` ```c
#include "los_perf.h" #include "los_perf.h"
STATIC VOID OsPrintBuff(const CHAR *buf, UINT32 num) STATIC VOID OsPrintBuff(const CHAR *buf, UINT32 num)
{ {
...@@ -192,7 +194,7 @@ STATIC VOID perfTestHwEvent(VOID) ...@@ -192,7 +194,7 @@ STATIC VOID perfTestHwEvent(VOID)
PRINTK("--------sample mode------ \n"); PRINTK("--------sample mode------ \n");
attr.needSample = 1; attr.needSample = 1;
LOS_PerfConfig(&attr); LOS_PerfConfig(&attr);
LOS_PerfStart(2); LOS_PerfStart(2); // 2: set the section id to 2.
test(); /* this is any test function*/ test(); /* this is any test function*/
LOS_PerfStop(); LOS_PerfStop();
buf = LOS_MemAlloc(m_aucSysMem1, LOSCFG_PERF_BUFFER_SIZE); buf = LOS_MemAlloc(m_aucSysMem1, LOSCFG_PERF_BUFFER_SIZE);
...@@ -205,18 +207,19 @@ STATIC VOID perfTestHwEvent(VOID) ...@@ -205,18 +207,19 @@ STATIC VOID perfTestHwEvent(VOID)
OsPrintBuff(buf, len); /* print data */ OsPrintBuff(buf, len); /* print data */
(VOID)LOS_MemFree(m_aucSysMem1, buf); (VOID)LOS_MemFree(m_aucSysMem1, buf);
} }
UINT32 Example_Perf_test(VOID){ UINT32 Example_Perf_test(VOID)
{
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S perfTestTask; TSK_INIT_PARAM_S perfTestTask;
/* 创建用于perf测试的任务 */ /* 创建用于perf测试的任务 */
memset(&perfTestTask, 0, sizeof(TSK_INIT_PARAM_S)); memset(&perfTestTask, 0, sizeof(TSK_INIT_PARAM_S));
perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent; perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent;
perfTestTask.pcName = "TestPerfTsk"; /* 测试任务名称 */ perfTestTask.pcName = "TestPerfTsk"; /* 测试任务名称 */
perfTestTask.uwStackSize = 0x800; perfTestTask.uwStackSize = 0x800; // 0x8000: perf test task stack size
perfTestTask.usTaskPrio = 5; perfTestTask.usTaskPrio = 5; // 5: perf test task priority
perfTestTask.uwResved = LOS_TASK_STATUS_DETACHED; perfTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
ret = LOS_TaskCreate(&g_perfTestTaskId, &perfTestTask); ret = LOS_TaskCreate(&g_perfTestTaskId, &perfTestTask);
if(ret != LOS_OK){ if (ret != LOS_OK) {
PRINT_ERR("PerfTestTask create failed.\n"); PRINT_ERR("PerfTestTask create failed.\n");
return LOS_NOK; return LOS_NOK;
} }
...@@ -268,11 +271,11 @@ hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 ...@@ -268,11 +271,11 @@ hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08
- option可选如下: - option可选如下:
- -e,配置采样事件。可使用./perf list 中罗列的同类型事件。 - -e,配置采样事件。可使用./perf list 中罗列的同类型事件。
- -p,配置事件采样周期。 - -p,配置事件采样周期。
- -o, 指定perf采样数据结果保存的文件路径。 - -o指定perf采样数据结果保存的文件路径。
- -t,任务Id过滤(白名单),只采取指定任务中的上下文。如果不指定改参数,则默认采集所有的任务。 - -t,任务Id过滤(白名单),只采取指定任务中的上下文。如果不指定改参数,则默认采集所有的任务。
- -s, 配置采样的具体上下文类型,可查阅los_perf.h中定义的PerfSampleType。 - -s配置采样的具体上下文类型,可查阅los_perf.h中定义的PerfSampleType。
- -P, 进程Id过滤(白名单),只采取指定进程中的上下文。如果不指定改参数,则默认采集所有进程。 - -P进程Id过滤(白名单),只采取指定进程中的上下文。如果不指定改参数,则默认采集所有进程。
- -d, 是否进行分频(事件每发生64次累计+1),该选项仅在硬件cycle事件上生效。 - -d是否进行分频(事件每发生64次累计+1),该选项仅在硬件cycle事件上生效。
- command 为待统计的子程序。 - command 为待统计的子程序。
用户态命令行的典型使用方法如下: 用户态命令行的典型使用方法如下:
...@@ -355,7 +358,7 @@ save perf data success at /storage/data/perf.data ...@@ -355,7 +358,7 @@ save perf data success at /storage/data/perf.data
实例代码如下: 实例代码如下:
``` ```c
#include "fcntl.h" #include "fcntl.h"
#include "user_copy.h" #include "user_copy.h"
#include "sys/ioctl.h" #include "sys/ioctl.h"
...@@ -367,6 +370,7 @@ save perf data success at /storage/data/perf.data ...@@ -367,6 +370,7 @@ save perf data success at /storage/data/perf.data
#define PERF_IOC_MAGIC 'T' #define PERF_IOC_MAGIC 'T'
#define PERF_START _IO(PERF_IOC_MAGIC, 1) #define PERF_START _IO(PERF_IOC_MAGIC, 1)
#define PERF_STOP _IO(PERF_IOC_MAGIC, 2) #define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
char *buf = NULL; char *buf = NULL;
......
...@@ -14,9 +14,9 @@ ...@@ -14,9 +14,9 @@
| **功能分类** | **接口描述** | | **功能分类** | **接口描述** |
| -------- | -------- | | -------- | -------- |
| 置1/清0标志位 | -&nbsp;LOS_BitmapSet:对状态字的某一标志位进行置1操作<br/>-&nbsp;LOS_BitmapClr:对状态字的某一标志位进行清0操作 | | 置1/清0标志位 | -&nbsp;LOS_BitmapSet:对状态字的某一标志位进行置1操作<br/>-&nbsp;LOS_BitmapClr:对状态字的某一标志位进行清0操作 |
| 获取标志位为1的bit位 | -&nbsp;LOS_HighBitGet:获取状态字中为1的最高位<br/>-&nbsp;LOS_LowBitGet:获取状态字中为1的最低位 | | 获取标志位为1的bit位 | -&nbsp;LOS_HighBitGet:获取状态字中为1的最高位<br/>-&nbsp;LOS_LowBitGet:获取状态字中为1的最低位 |
| 连续bit位操作 | -&nbsp;LOS_BitmapSetNBits:对状态字的连续标志位进行置1操作<br/>-&nbsp;LOS_BitmapClrNBits:对状态字的连续标志位进行清0操作<br/>-&nbsp;LOS_BitmapFfz:获取从最低有效位开始的第一个0的bit位 | | 连续bit位操作 | -&nbsp;LOS_BitmapSetNBits:对状态字的连续标志位进行置1操作<br/>-&nbsp;LOS_BitmapClrNBits:对状态字的连续标志位进行清0操作<br/>-&nbsp;LOS_BitmapFfz:获取从最低有效位开始的第一个0的bit位 |
## 编程实例 ## 编程实例
...@@ -34,6 +34,9 @@ ...@@ -34,6 +34,9 @@
4. 获取标志位为1的最低bit位。 4. 获取标志位为1的最低bit位。
### 编程示例
本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数BitSample。
``` ```
#include "los_bitmap.h" #include "los_bitmap.h"
......
...@@ -17,10 +17,10 @@ ...@@ -17,10 +17,10 @@
| 增加节点 | -&nbsp;LOS_ListAdd:将指定节点插入到双向链表头端<br/>-&nbsp;LOS_ListHeadInsert:将指定节点插入到双向链表头端,同LOS_ListAdd<br/>-&nbsp;LOS_ListTailInsert:将指定节点插入到双向链表尾端 | | 增加节点 | -&nbsp;LOS_ListAdd:将指定节点插入到双向链表头端<br/>-&nbsp;LOS_ListHeadInsert:将指定节点插入到双向链表头端,同LOS_ListAdd<br/>-&nbsp;LOS_ListTailInsert:将指定节点插入到双向链表尾端 |
| 增加链表 | -&nbsp;LOS_ListAddList:将指定链表的头端插入到双向链表头端<br/>-&nbsp;LOS_ListHeadInsertList:将指定链表的头端插入到双向链表头端<br/>-&nbsp;LOS_ListTailInsertList:将指定链表的尾端插入到双向链表头端 | | 增加链表 | -&nbsp;LOS_ListAddList:将指定链表的头端插入到双向链表头端<br/>-&nbsp;LOS_ListHeadInsertList:将指定链表的头端插入到双向链表头端<br/>-&nbsp;LOS_ListTailInsertList:将指定链表的尾端插入到双向链表头端 |
| 删除节点 | -&nbsp;LOS_ListDelete:将指定节点从链表中删除<br/>-&nbsp;LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 | | 删除节点 | -&nbsp;LOS_ListDelete:将指定节点从链表中删除<br/>-&nbsp;LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 |
| 判断双向链表 | -&nbsp;LOS_ListEmpty:判断链表是否为空<br/>-&nbsp;LOS_DL_LIST_IS_END:判断指定链表节点是否为链表尾端LOS_DL_LIST_IS_ON_QUEUE:判断链表节点是否在双向链表里 | | 判断双向链表 | -&nbsp;LOS_ListEmpty:判断链表是否为空<br/>-&nbsp;LOS_DL_LIST_IS_END:判断指定链表节点是否为链表尾端<br/>-&nbsp;LOS_DL_LIST_IS_ON_QUEUE:判断链表节点是否在双向链表里 |
| 获取结构体信息 | -&nbsp;LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量<br/>-&nbsp;LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称<br/>-&nbsp;LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。<br/>-&nbsp;LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。<br/>-&nbsp;LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。| | 获取结构体信息 | -&nbsp;LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量<br/>-&nbsp;LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称<br/>-&nbsp;LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。<br/>-&nbsp;LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。<br/>-&nbsp;LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。|
| 遍历双向链表 | -&nbsp;LOS_DL_LIST_FOR_EACH:遍历双向链表<br/>-&nbsp;LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 | | 遍历双向链表 | -&nbsp;LOS_DL_LIST_FOR_EACH:遍历双向链表<br/>-&nbsp;LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 |
| 遍历包含双向链表的结构体 | -&nbsp;LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址<br/>-&nbsp;LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 | | 遍历包含双向链表的结构体 | -&nbsp;LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址<br/>-&nbsp;LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 |
## 开发流程 ## 开发流程
...@@ -48,10 +48,10 @@ ...@@ -48,10 +48,10 @@
> - 如果链表节点的内存是动态申请的,删除节点时,要注意释放内存。 > - 如果链表节点的内存是动态申请的,删除节点时,要注意释放内存。
**编程实例** ## 编程实例
**实例描述**
### 实例描述
本实例实现如下功能: 本实例实现如下功能:
...@@ -64,7 +64,11 @@ ...@@ -64,7 +64,11 @@
4. 测试操作是否成功。 4. 测试操作是否成功。
### 编程示例
本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数ListSample
示例代码如下:
``` ```
#include "stdio.h" #include "stdio.h"
......
...@@ -15,10 +15,18 @@ musl libc库支持POSIX标准,涉及的系统调用相关接口由OpenHarmony ...@@ -15,10 +15,18 @@ musl libc库支持POSIX标准,涉及的系统调用相关接口由OpenHarmony
标准库支持接口的详细情况请参考C库的API文档,其中也涵盖了与POSIX标准之间的差异说明。 标准库支持接口的详细情况请参考C库的API文档,其中也涵盖了与POSIX标准之间的差异说明。
## 操作实例 ### 编程实例
#### 实例描述
在本示例中,主线程创建了THREAD_NUM个子线程,每个子线程启动后等待被主线程唤醒,主线程成功唤醒所有子线程后,子线程继续执行直至生命周期结束,同时主线程通过pthread_join方法等待所有线程执行结束。 在本示例中,主线程创建了THREAD_NUM个子线程,每个子线程启动后等待被主线程唤醒,主线程成功唤醒所有子线程后,子线程继续执行直至生命周期结束,同时主线程通过pthread_join方法等待所有线程执行结束。
#### 编程示例
本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数testcase 或新建文件由主函数调用
示例代码如下:
``` ```
#include <stdio.h> #include <stdio.h>
......
...@@ -16,13 +16,11 @@ OpenHarmony系统通过对ARMv6架构中的LDREX和STREX进行封装,向用户 ...@@ -16,13 +16,11 @@ OpenHarmony系统通过对ARMv6架构中的LDREX和STREX进行封装,向用户
- LDREX Rx, [Ry] - LDREX Rx, [Ry]
读取内存中的值,并标记对该段内存的独占访问: 读取内存中的值,并标记对该段内存的独占访问:
- 读取寄存器Ry指向的4字节内存数据,保存到Rx寄存器中。 - 读取寄存器Ry指向的4字节内存数据,保存到Rx寄存器中。
- 对Ry指向的内存区域添加独占访问标记。 - 对Ry指向的内存区域添加独占访问标记。
- STREX Rf, Rx, [Ry] - STREX Rf, Rx, [Ry]
检查内存是否有独占访问标记,如果有则更新内存值并清空标记,否则不更新内存: 检查内存是否有独占访问标记,如果有则更新内存值并清空标记,否则不更新内存:
- 有独占访问标记 - 有独占访问标记
- 将寄存器Rx中的值更新到寄存器Ry指向的内存。 - 将寄存器Rx中的值更新到寄存器Ry指向的内存。
- 标志寄存器Rf置为0。 - 标志寄存器Rf置为0。
...@@ -40,12 +38,12 @@ OpenHarmony系统通过对ARMv6架构中的LDREX和STREX进行封装,向用户 ...@@ -40,12 +38,12 @@ OpenHarmony系统通过对ARMv6架构中的LDREX和STREX进行封装,向用户
### 接口说明 ### 接口说明
OpenHarmony LiteOS-A内核的原子操作模块提供下面几种功能,接口详细信息可以查看API参考 OpenHarmony LiteOS-A内核的原子操作模块提供以下几种功能
**表1** 原子操作接口说明 **表1** 原子操作接口说明
| 功能分类 | 接口**名称** | 描述 | | 功能分类 | 接口**名称** | 描述 |
| -------- | -------- | -------- | | ------------ | ----------------------- | --------------------------- |
| 读 | LOS_AtomicRead | 读取32bit原子数据 | | 读 | LOS_AtomicRead | 读取32bit原子数据 |
| 读 | LOS_Atomic64Read | 读取64bit原子数据 | | 读 | LOS_Atomic64Read | 读取64bit原子数据 |
| 写 | LOS_AtomicSet | 设置32bit原子数据 | | 写 | LOS_AtomicSet | 设置32bit原子数据 |
......
...@@ -3,16 +3,28 @@ ...@@ -3,16 +3,28 @@
## 基本概念 ## 基本概念
中断是指出现需要时,CPU暂停执行当前程序,转而执行新程序的过程。即在程序运行过程中,出现了一个必须由CPU立即处理的事务。此时,CPU暂时中止当前程序的执行转而处理这个事务,这个过程就叫做中断。通过中断机制,可以使CPU避免把大量时间耗费在等待、查询外设状态的操作上,大大提高系统实时性以及执行效率。 中断是指出现需要时,CPU暂停执行当前程序,转而执行新程序的过程。即在程序运行过程中,出现了一个必须由CPU立即处理的事务,此时CPU暂时中止当前程序的执行转而处理这个事务,这个过程就叫做中断。通过中断机制,可以使CPU避免把大量时间耗费在等待、查询外设状态的操作上,大大提高系统实时性以及执行效率。
目前的中断支持有
+ 中断初始化
+ 中断创建
+ 开/关中断
+ 恢复中断
+ 删除中断
异常处理是操作系统对运行期间发生的异常情况(芯片硬件异常)进行处理的一系列动作,例如虚拟内存缺页异常、打印异常发生时函数的调用栈信息、CPU现场信息、任务的堆栈情况等。 异常处理是操作系统对运行期间发生的异常情况(芯片硬件异常)进行处理的一系列动作,例如虚拟内存缺页异常、打印异常发生时函数的调用栈信息、CPU现场信息、任务的堆栈情况等。
## 运行机制 ## 运行机制
外设可以在没有CPU介入的情况下完成一定的工作,但某些情况下也需要CPU为其执行一定的工作。通过中断机制,在外设不需要CPU介入时,CPU可以执行其它任务,而当外设需要CPU时,产生一个中断信号,该信号连接至中断控制器。中断控制器是一方面接收其它外设中断引脚的输入,另一方面它会发出中断信号给CPU。可以通过对中断控制器编程来打开和关闭中断源、设置中断源的优先级和触发方式。常用的中断控制器有VIC(Vector Interrupt Controller)和GIC(General Interrupt Controller)。在ARM Cortex-A7中使用的中断控制器是GIC。CPU收到中断控制器发送的中断信号后,中断当前任务来响应中断请求。 外设可以在没有CPU介入的情况下完成一定的工作,但某些情况下也需要CPU为其执行一定的工作。通过中断机制,在外设不需要CPU介入时,CPU可以执行其它任务,而当外设需要CPU时,产生一个中断信号,该信号连接至中断控制器。
中断控制器一方面接收其它外设中断引脚的输入,另一方面会发出中断信号给CPU。可以通过对中断控制器编程来打开和关闭中断源、设置中断源的优先级和触发方式。常用的中断控制器有VIC(Vector Interrupt Controller)和GIC(General Interrupt Controller)。在ARM Cortex-A7中使用的中断控制器是GIC。
CPU收到中断控制器发送的中断信号后,中断当前任务来响应中断请求。
异常处理就是可以打断CPU正常运行流程的一些事情,如未定义指令异常、试图修改只读的数据异常、不对齐的地址访问异常等。当异常发生时,CPU暂停当前的程序,先处理异常事件,然后再继续执行被异常打断的程序。 异常可以打断CPU正常运行流程的一些事情,如未定义指令异常、试图修改只读的数据异常、不对齐的地址访问异常等。当异常发生时,CPU暂停当前的程序,先处理异常事件,然后再继续执行被异常打断的程序。
以ARMv7-a架构为例,中断和异常处理的入口为中断向量表,中断向量表包含各个中断和异常处理的入口函数。 以ARMv7-a架构为例,中断和异常处理的入口为中断向量表,中断向量表包含各个中断和异常处理的入口函数。
...@@ -28,11 +40,27 @@ ...@@ -28,11 +40,27 @@
异常处理为内部机制,不对外提供接口,中断模块提供对外接口如下: 异常处理为内部机制,不对外提供接口,中断模块提供对外接口如下:
| 功能分类 | 接口描述 | ##### 创建删除中断
| -------- | -------- |
| 创建和删除中断 | -&nbsp;LOS_HwiCreate:中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序<br/>-&nbsp;LOS_HwiDelete:删除中断 | | 接口名 | 接口描述 |
| 打开和关闭所有中断 | -&nbsp;LOS_IntUnLock:打开当前处理器所有中断响应<br/>-&nbsp;LOS_IntLock:关闭当前处理器所有中断响应<br/>-&nbsp;LOS_IntRestore:恢复到使用LOS_IntLock关闭所有中断之前的状态 | | :------------ | :----------------------------------------------------------- |
| 获取系统支持的最大中断数 | LOS_GetSystemHwiMaximum:获取系统支持的最大中断数 | | LOS_HwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序 |
| LOS_HwiDelete | 根据所提供的中断号删除中断 |
##### 开/关中断
| 接口名 | 接口描述 |
| -------------- | ------------------------------------------- |
| LOS_IntUnlock | 打开当前处理器所有中断响应 |
| LOS_IntLock | 关闭当前处理器所有中断响应 |
| LOS_IntRestore | 与LOS_IntLock配套使用,恢复到使用LOS_IntLock关闭所有中断之前的状态 |
##### 获取系统中断信息
| 接口名 | 接口描述 |
| ----------------------- | ------------------------ |
| LOS_GetSystemHwiMaximum | 获取系统支持的最大中断数 |
### 开发流程 ### 开发流程
...@@ -53,32 +81,30 @@ ...@@ -53,32 +81,30 @@
2. 删除中断。 2. 删除中断。
代码实现如下,演示如何创建中断和删除中断,当指定的中断号HWI_NUM_TEST产生中断时,会调用中断处理函数: 代码实现如下,演示如何创建中断和删除中断,当指定的中断号HWI_NUM_TEST产生中断时,会调用中断处理函数(该示例代码的测试函数可以加在kernel/liteos_a/testsuites/kernel/src/osTest.c中的TestTaskEntry中进行测试):
```c
```
#include "los_hwi.h" #include "los_hwi.h"
/*中断处理函数*/ /*中断处理函数*/
STATIC VOID HwiUsrIrq(VOID) STATIC VOID HwiUsrIrq(VOID)
{ {
printf("in the func HwiUsrIrq \n"); PRINK("in the func HwiUsrIrq \n");
} }
static UINT32 Example_Interrupt(VOID) static UINT32 Example_Interrupt(VOID)
{ {
UINT32 ret; UINT32 ret;
HWI_HANDLE_T hwiNum = 7; HWI_HANDLE_T hwiNum = 7; // 7: 使用的中断号
HWI_PRIOR_T hwiPrio = 3; HWI_PRIOR_T hwiPrio = 3; // 3: 中断优先级
HWI_MODE_T mode = 0; HWI_MODE_T mode = 0;
HWI_ARG_T arg = 0; HWI_ARG_T arg = 0;
/*创建中断*/ /*创建中断*/
ret = LOS_HwiCreate(hwiNum, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, (HwiIrqParam *)arg); ret = LOS_HwiCreate(hwiNum, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, (HwiIrqParam *)arg);
if(ret == LOS_OK){ if (ret == LOS_OK) {
printf("Hwi create success!\n"); PRINK("Hwi create success!\n");
} else { } else {
printf("Hwi create failed!\n"); PRINK("Hwi create failed!\n");
return LOS_NOK; return LOS_NOK;
} }
...@@ -87,10 +113,10 @@ static UINT32 Example_Interrupt(VOID) ...@@ -87,10 +113,10 @@ static UINT32 Example_Interrupt(VOID)
/*删除中断*/ /*删除中断*/
ret = LOS_HwiDelete(hwiNum, (HwiIrqParam *)arg); ret = LOS_HwiDelete(hwiNum, (HwiIrqParam *)arg);
if(ret == LOS_OK){ if (ret == LOS_OK) {
printf("Hwi delete success!\n"); PRINK("Hwi delete success!\n");
} else { } else {
printf("Hwi delete failed!\n"); PRINK("Hwi delete failed!\n");
return LOS_NOK; return LOS_NOK;
} }
return LOS_OK; return LOS_OK;
...@@ -102,7 +128,6 @@ static UINT32 Example_Interrupt(VOID) ...@@ -102,7 +128,6 @@ static UINT32 Example_Interrupt(VOID)
编译运行得到的结果为: 编译运行得到的结果为:
``` ```
Hwi create success! Hwi create success!
Hwi delete success! Hwi delete success!
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 基本概念 ## 基本概念
进程是系统资源管理的最小单元。OpenHarmony LiteOS-A内核提供的进程模块主要用于实现用户态进程的隔离,内核态被视为一个进程空间,不存在其它进程(KIdle除外,KIdle进程是系统提供的空闲进程,和KProcess共享一个进程空间)。 进程是系统资源管理的最小单元。OpenHarmony LiteOS-A 内核提供的进程模块主要用于实现用户态进程的隔离,内核态被视为一个进程空间,不存在其它进程(KIdle除外,KIdle进程是系统提供的空闲进程,和KProcess共享一个进程空间。KProcess 是内核态进程的根进程,KIdle 是其子进程)。
- 进程模块主要为用户提供多个进程,实现了进程之间的切换和通信,帮助用户管理业务程序流程。 - 进程模块主要为用户提供多个进程,实现了进程之间的切换和通信,帮助用户管理业务程序流程。
...@@ -36,10 +36,10 @@ ...@@ -36,10 +36,10 @@
**进程状态迁移说明:** **进程状态迁移说明:**
- Init→Ready: - Init→Ready:
进程创建或fork时,拿到该进程控制块后进入Init状态,处于进程初始化阶段,当进程初始化完成将进程插入调度队列,此时进程进入就绪状态。 进程创建或 fork 时,拿到对应进程控制块后进入 Init 状态,即进程初始化阶段,当该阶段完成后进程将被插入调度队列,此时进程进入就绪状态。
- Ready→Running: - Ready→Running:
进程创建后进入就绪态,发生进程切换时,就绪列表中最高优先级的进程被执行,从而进入运行态。若此时该进程中已无其它线程处于就绪态,则进程从就绪列表删除,只处于运行态;若此时该进程中还有其它线程处于就绪态,则该进程依旧在就绪队列,此时进程的就绪态和运行态共存,但对外呈现的进程状态为运行态。 进程创建后进入就绪态,发生进程切换时,就绪列表中优先级最高且获得时间片的进程被执行,从而进入运行态。若此时该进程中已无其它线程处于就绪态,则进程从就绪列表删除,只处于运行态;若此时该进程中还有其它线程处于就绪态,则该进程依旧在就绪队列,此时进程的就绪态和运行态共存,但对外呈现的进程状态为运行态。
- Running→Pending: - Running→Pending:
进程在最后一个线程转为阻塞态时, 进程内所有的线程均处于阻塞态,此时进程同步进入阻塞态,然后发生进程切换。 进程在最后一个线程转为阻塞态时, 进程内所有的线程均处于阻塞态,此时进程同步进入阻塞态,然后发生进程切换。
...@@ -54,7 +54,7 @@ ...@@ -54,7 +54,7 @@
进程由运行态转为就绪态的情况有以下两种: 进程由运行态转为就绪态的情况有以下两种:
1. 有更高优先级的进程创建或者恢复后,会发生进程调度,此刻就绪列表中最高优先级进程变为运行态,那么原先运行的进程由运行态变为就绪态。 1. 有更高优先级的进程创建或者恢复后,会发生进程调度,此刻就绪列表中最高优先级进程变为运行态,那么原先运行的进程由运行态变为就绪态。
2. 若进程的调度策略为LOS_SCHED_RR,且存在同一优先级的另一个进程处于就绪态,则该进程的时间片消耗光之后,该进程由运行态转为就绪态,另一个同优先级的进程由就绪态转为运行态。 2. 若进程的调度策略为 LOS_SCHED_RR(时间片轮转),且存在同一优先级的另一个进程处于就绪态,则该进程的时间片消耗光之后,该进程由运行态转为就绪态,另一个同优先级的进程由就绪态转为运行态。
- Running→Zombies: - Running→Zombies:
当进程的主线程或所有线程运行结束后,进程由运行态转为僵尸态,等待父进程回收资源。 当进程的主线程或所有线程运行结束后,进程由运行态转为僵尸态,等待父进程回收资源。
...@@ -78,16 +78,47 @@ OpenHarmony 提供的进程模块主要用于实现用户态进程的隔离, ...@@ -78,16 +78,47 @@ OpenHarmony 提供的进程模块主要用于实现用户态进程的隔离,
### 接口说明 ### 接口说明
**表1** 进程管理模块接口 ##### 表1 进程及进程组
| 接口名 | 接口描述 |
| ------------------------- | ---------------------- |
| LOS_GetCurrProcessID | 获取当前进程的进程ID |
| LOS_GetProcessGroupID | 获取指定进程的进程组ID |
| LOS_GetCurrProcessGroupID | 获取当前进程的进程组ID |
##### 表2 用户及用户组
| 接口名 | 接口描述 |
| ----------------- | ---------------------------------------- |
| LOS_GetUserID | 获取当前进程的用户ID |
| LOS_GetGroupID | 获取当前进程的用户组ID |
| LOS_CheckInGroups | 检查指定用户组ID是否在当前进程的用户组内 |
##### 表3 进程调度控制
| 接口名 | 接口 |
| ----------------------- | -------------------------------------------- |
| LOS_GetProcessScheduler | 获取指定进程的调度策略 |
| LOS_SetProcessScheduler | 设置指定进程的调度参数,包括优先级和调度策略 |
| LOS_SetProcessPriority | 设置进程优先级 |
| LOS_GetProcessPriority | 获取进程优先级 |
##### 表4 系统进程信息获取
| 接口名 | 接口描述 |
| --------------------------- | -------------------------- |
| LOS_GetSystemProcessMaximum | 获取系统支持的最大进程数目 |
| LOS_GetUsedPIDList | 获得已使用的进程ID列表 |
##### 表5 进程创建与结束
| 接口名 | 接口描述 |
| ---------- | -------------------------- |
| LOS_Fork | 创建子进程 |
| LOS_Wait | 等待子进程结束并回收子进程 |
| LOS_Waitid | 等待相应ID的进程结束 |
| LOS_Exit | 退出进程 |
| 功能分类 | 接口描述 |
| -------- | -------- |
| 进程调度参数控制 | -&nbsp;LOS_GetProcessScheduler:获取指定进程的调度策略<br/>-&nbsp;LOS_SetProcessScheduler:设置指定进程的调度参数,包括优先级和调度策略 |
| 等待回收子进程 | LOS_Wait:等待子进程结束并回收子进程 |
| 进程组 | -&nbsp;LOS_GetProcessGroupID:获取指定进程的进程组ID<br/>-&nbsp;LOS_GetCurrProcessGroupID:获取当前进程的进程组ID |
| 获取进程ID | LOS_GetCurrProcessID:获取当前进程的进程ID |
| 用户及用户组 | -&nbsp;LOS_GetUserID:获取当前进程的用户ID<br/>-&nbsp;LOS_GetGroupID:获取当前进程的用户组ID<br/>-&nbsp;LOS_CheckInGroups:检查指定用户组ID是否在当前进程的用户组内 |
| 系统支持的最大进程数 | LOS_GetSystemProcessMaximum:获取系统支持的最大进程数目 |
### 开发流程 ### 开发流程
......
...@@ -3,18 +3,18 @@ ...@@ -3,18 +3,18 @@
## 基本概念 ## 基本概念
OpenHarmony LiteOS-A内核 了高优先级优先+同优先级时间片轮转的抢占式调度机制,系统从启动开始基于real time的时间轴向前运行,使得该调度算法具有很好的实时性。 OpenHarmony LiteOS-A内核采用了高优先级优先 + 同优先级时间片轮转的抢占式调度机制,系统从启动开始基于real time的时间轴向前运行,使得该调度算法具有很好的实时性。
OpenHarmony 的调度算法将tickless机制天然嵌入到调度算法中,一方面使得系统具有更低的功耗,另一方面也使得tick中断按需响应,减少无用的tick中断响应,进一步提高系统的实时性。 OpenHarmony 的调度算法将 tickless 机制天然嵌入到调度算法中,一方面使得系统具有更低的功耗,另一方面也使得 tick 中断按需响应,减少无用的 tick 中断响应,进一步提高系统的实时性。
OpenHarmony 的进程调度策略支持SCHED_RR,线程调度策略支持SCHED_RR和SCHED_FIFO OpenHarmony 的进程调度策略支持 SCHED_RR(时间片轮转),线程调度策略支持 SCHED_RR 和 SCHED_FIFO(先进先出)
OpenHarmony 调度的最小单元为线程。 OpenHarmony 调度的最小单元为线程。
## 运行机制 ## 运行机制
OpenHarmony 采用进程优先级队列+线程优先级队列的方式,进程优先级范围为0-31,共有32个进程优先级桶队列,每个桶队列对应一个线程优先级桶队列;线程优先级范围也为0-31,一个线程优先级桶队列也有32个优先级队列。 OpenHarmony 采用进程优先级队列 + 线程优先级队列的方式,进程优先级范围为0-31,共有32个进程优先级桶队列,每个桶队列对应一个线程优先级桶队列;线程优先级范围也为0-31,一个线程优先级桶队列也有32个优先级队列。
**图1** 调度优先级桶队列示意图 **图1** 调度优先级桶队列示意图
...@@ -31,9 +31,13 @@ OpenHarmony 在系统启动内核初始化之后开始调度,运行过程中 ...@@ -31,9 +31,13 @@ OpenHarmony 在系统启动内核初始化之后开始调度,运行过程中
### 接口说明 ### 接口说明
| 功能分类 | 接口**名称** | 描述 | | 接口**名称** | 描述 |
| -------- | -------- | -------- | | -------- | -------- |
| 触发系统调度 | LOS_Schedule | 触发系统调度 | | LOS_Schedule | 触发系统调度 |
| LOS_GetTaskScheduler | 获取指定任务的调度策略 |
| LOS_SetTaskScheduler | 设置指定任务的调度策略 |
| LOS_GetProcessScheduler | 获取指定进程的调度策略 |
| LOS_SetProcessScheduler | 设置指定进程的调度参数,包括优先级和调度策略 |
### 开发流程 ### 开发流程
......
...@@ -52,7 +52,7 @@ OpenHarmony 内核的任务一共有32个优先级(0-31),最高优先级为0 ...@@ -52,7 +52,7 @@ OpenHarmony 内核的任务一共有32个优先级(0-31),最高优先级为0
有更高优先级任务创建或者恢复后,会发生任务调度,此刻就绪列表中最高优先级任务变为运行态,那么原先运行的任务由运行态变为就绪态,并加入就绪列表中。 有更高优先级任务创建或者恢复后,会发生任务调度,此刻就绪列表中最高优先级任务变为运行态,那么原先运行的任务由运行态变为就绪态,并加入就绪列表中。
- Running→Exit: - Running→Exit:
运行中的任务运行结束,任务状态由运行态变为退出态。若为设置了分离属性(LOS_TASK_STATUS_DETACHED)的任务,运行结束后将直接销毁。 运行中的任务运行结束,任务状态由运行态变为退出态。若为设置了分离属性( 由头文件 los_task.h 中的宏定义 LOS_TASK_STATUS_DETACHED 设置)的任务,运行结束后将直接销毁。
## 运行机制 ## 运行机制
...@@ -67,16 +67,58 @@ OpenHarmony 任务管理模块提供任务创建、任务延时、任务挂起 ...@@ -67,16 +67,58 @@ OpenHarmony 任务管理模块提供任务创建、任务延时、任务挂起
### 接口说明 ### 接口说明
| 功能分类 | 接口描述 | ##### 表1 任务的创建和删除
| -------- | -------- |
| 任务的创建和删除 | -&nbsp;LOS_TaskCreate:创建任务,并使该任务进入Init状态,不执行任务调度<br/>-&nbsp;LOS_TaskDelete:创建任务,并使该任务进入Ready状态,并调度<br/>-&nbsp;LOS_TaskDelete:删除指定的任务 | | 接口名 | 接口描述 |
| 任务状态控制 | -&nbsp;LOS_TaskResume:恢复挂起的任务<br/>-&nbsp;LOS_TaskSuspend:挂起指定的任务<br/>-&nbsp;LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源<br/>-&nbsp;LOS_TaskDetach:修改任务的joinable属性为detach属性,detach属性的任务运行结束会自动回收任务控制块资源<br/>-&nbsp;LOS_TaskDelay:任务延时等待<br/>-&nbsp;LOS_TaskYield:显式放权,调整调用任务优先级的任务调度顺序 | | ------------------ | ------------------------------------------------------------ |
| 任务调度的控制 | -&nbsp;LOS_TaskLock:锁任务调度<br/>-&nbsp;LOS_TaskUnlock:解锁任务调度 | | LOS_TaskCreate | 创建任务,若所创建任务的优先级比当前的运行的任务优先级高且任务调度没有锁定,<br/>则该任务将被调度进入运行态 |
| 任务优先级的控制 | -&nbsp;LOS_CurTaskPriSet:设置当前任务的优先级<br/>-&nbsp;LOS_TaskPriSet:设置指定任务的优先级<br/>-&nbsp;LOS_TaskPriGet:获取指定任务的优先级 | | LOS_TaskCreateOnly | 创建任务并阻塞,任务恢复前不会将其加入就绪队列中 |
| 任务信息获取 | -&nbsp;LOS_CurTaskIDGet:获取当前任务的ID<br/>-&nbsp;LOS_TaskInfoGet:获取指定任务的信息 | | LOS_TaskDelete | 删除指定的任务,回收其任务控制块和任务栈所消耗的资源 |
| 任务绑核操作 | -&nbsp;LOS_TaskCpuAffiSet:绑定指定任务到指定CPU上运行,仅在多核下使用<br/>-&nbsp;LOS_TaskCpuAffiGet:获取指定任务的绑核信息,仅在多核下使用 |
| 任务调度参数的控制 | -&nbsp;LOS_GetTaskScheduler:获取指定任务的调度策略<br/>-&nbsp;LOS_SetTaskScheduler:设置指定任务的调度参数,包括优先级和调度策略 | ##### 表2 任务的状态控制
| 系统支持的最大任务数 | LOS_GetSystemTaskMaximum |
| 接口名 | 接口描述 |
| --------------- | ------------------------------------------------------------ |
| LOS_TaskResume | 恢复挂起的任务 |
| LOS_TaskSuspend | 挂起指定的任务,该任务将从就绪任务队列中移除 |
| LOS_TaskJoin | 阻塞当前任务,等待指定任务运行结束并回收其资源 |
| LOS_TaskDetach | 修改任务的 joinable 属性为 detach 属性,detach 属性的任务运行结束会自动回收任务控制块资源 |
| LOS_TaskDelay | 延迟当前任务的执行,在延后指定的时间(tick数)后可以被调度 |
| LOS_TaskYield | 将当前任务从具有相同优先级的任务队列,移动到就绪任务队列的末尾 |
##### 表3 任务调度
| 接口名 | 接口描述 |
| -------------------- | ------------------------------------------------------------ |
| LOS_TaskLock | 锁定任务调度,阻止任务切换 |
| LOS_TaskUnlock | 解锁任务调度。通过该接口可以使任务锁数量减1,若任务多次加锁,那么<br/>任务调度在锁数量减为0时才会完全解锁 |
| LOS_GetTaskScheduler | 获取指定任务的调度策略 |
| LOS_SetTaskScheduler | 设置指定任务的调度参数,包括优先级和调度策略 |
| LOS_Schedule | 触发主动的任务调度 |
##### 表4 任务相关信息获取
| 接口名 | 接口描述 |
| ------------------------ | ------------------------ |
| LOS_CurTaskIDGet | 获取当前任务的ID |
| LOS_TaskInfoGet | 获取指定任务的信息 |
| LOS_GetSystemTaskMaximum | 获取系统支持的最大任务数 |
##### 表5 任务优先级
| 接口名 | 接口描述 |
| ----------------- | ------------------------------ |
| LOS_CurTaskPriSet | 设置当前正在运行的任务的优先级 |
| LOS_TaskPriSet | 设置指定任务的优先级 |
| LOS_TaskPriGet | 获取指定任务的优先级 |
##### 表6 任务绑核操作
| 接口名 | 接口描述 |
| ------------------ | ------------------------------------------- |
| LOS_TaskCpuAffiSet | 绑定指定任务到指定CPU上运行,仅在多核下使用 |
| LOS_TaskCpuAffiGet | 获取指定任务的绑核信息,仅在多核下使用 |
### 开发流程 ### 开发流程
...@@ -93,7 +135,7 @@ OpenHarmony 任务管理模块提供任务创建、任务延时、任务挂起 ...@@ -93,7 +135,7 @@ OpenHarmony 任务管理模块提供任务创建、任务延时、任务挂起
2. 任务参与调度运行,执行用户指定的业务代码。 2. 任务参与调度运行,执行用户指定的业务代码。
3. 任务执行结束,如果设置了LOS_TASK_STATUS_DETACHED属性,则自动回收任务资源,如果任务设置了LOS_TASK_ATTR_JOINABLE属性,则需要调用LOS_TaskJoin回收任务资源,默认为LOS_TASK_STATUS_DETACHED属性。 3. 任务执行结束,如果设置了 LOS_TASK_STATUS_DETACHED 属性,则自动回收任务资源,如果任务设置了 LOS_TASK_ATTR_JOINABLE 属性,则需要调用LOS_TaskJoin 回收任务资源,默认为 LOS_TASK_STATUS_DETACHED 属性。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 内核态具有最高权限,可以操作任意进程内的任务。 > - 内核态具有最高权限,可以操作任意进程内的任务。
...@@ -103,10 +145,10 @@ OpenHarmony 任务管理模块提供任务创建、任务延时、任务挂起 ...@@ -103,10 +145,10 @@ OpenHarmony 任务管理模块提供任务创建、任务延时、任务挂起
### 编程实例 ### 编程实例
代码实现如下: 代码实现如下(该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。)
``` ```c
UINT32 g_taskLoID; UINT32 g_taskLoID;
UINT32 g_taskHiID; UINT32 g_taskHiID;
#define TSK_PRIOR_HI 4 #define TSK_PRIOR_HI 4
...@@ -163,6 +205,7 @@ UINT32 ExampleTaskCaseEntry(VOID) ...@@ -163,6 +205,7 @@ UINT32 ExampleTaskCaseEntry(VOID)
/* 锁任务调度 */ /* 锁任务调度 */
LOS_TaskLock(); LOS_TaskLock();
PRINTK("LOS_TaskLock() Success!\n"); PRINTK("LOS_TaskLock() Success!\n");
/* 高优先级任务的初始化参数,其资源回收需要其他任务调用 LOS_TaskJoin */
initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi; initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi;
initParam.usTaskPrio = TSK_PRIOR_HI; initParam.usTaskPrio = TSK_PRIOR_HI;
initParam.pcName = "HIGH_NAME"; initParam.pcName = "HIGH_NAME";
...@@ -178,6 +221,7 @@ UINT32 ExampleTaskCaseEntry(VOID) ...@@ -178,6 +221,7 @@ UINT32 ExampleTaskCaseEntry(VOID)
} }
PRINTK("ExampleTaskHi create Success!\n"); PRINTK("ExampleTaskHi create Success!\n");
/* 低优先级任务的初始化参数,任务结束后会自行结束销毁 */
initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo; initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo;
initParam.usTaskPrio = TSK_PRIOR_LO; initParam.usTaskPrio = TSK_PRIOR_LO;
initParam.pcName = "LOW_NAME"; initParam.pcName = "LOW_NAME";
......
...@@ -3,9 +3,13 @@ ...@@ -3,9 +3,13 @@
## 基本概念 ## 基本概念
软件定时器,是基于系统Tick时钟中断且由软件来模拟的定时器,当经过设定的Tick时钟计数值后会触发用户定义的回调函数。定时精度与系统Tick时钟的周期有关。硬件定时器受硬件的限制,数量上不足以满足用户的实际需求,因此为了满足用户需求,提供更多的定时器,OpenHarmony LiteOS-A内核提供软件定时器功能。软件定时器扩展了定时器的数量,允许创建更多的定时业务。 软件定时器,是基于系统Tick时钟中断且由软件来模拟的定时器,当经过设定的Tick时钟计数值后会触发用户定义的回调函数。定时精度与系统Tick时钟的周期有关。
软件定时器功能上支持: 硬件定时器受硬件的限制,数量上不足以满足用户的实际需求,因此为了满足用户需求,提供更多的定时器,OpenHarmony LiteOS-A内核提供软件定时器功能。
软件定时器扩展了定时器的数量,允许创建更多的定时业务。
**软件定时器支持以下功能:**
- 静态裁剪:能通过宏关闭软件定时器功能。 - 静态裁剪:能通过宏关闭软件定时器功能。
...@@ -22,13 +26,17 @@ ...@@ -22,13 +26,17 @@
## 运行机制 ## 运行机制
软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置。软件定时器使用了系统的一个队列和一个任务资源,软件定时器的触发遵循队列规则,先进先出。同一时刻设置的定时时间短的定时器总是比定时时间长的靠近队列头,满足优先被触发的准则。软件定时器以Tick为基本计时单位,当用户创建并启动一个软件定时器时,OpenHarmony系统会根据当前系统Tick时间及用户设置的定时间隔确定该定时器的到期Tick时间,并将该定时器控制结构挂入计时全局链表。 软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置。
软件定时器使用了系统的一个队列和一个任务资源,软件定时器的触发遵循队列规则,先进先出。同一时刻设置的定时时间短的定时器总是比定时时间长的靠近队列头,满足优先被触发的准则。
软件定时器以Tick为基本计时单位,当用户创建并启动一个软件定时器时,OpenHarmony系统会根据当前系统Tick时间及用户设置的定时间隔确定该定时器的到期Tick时间,并将该定时器控制结构挂入计时全局链表。
当Tick中断到来时,在Tick中断处理函数中扫描软件定时器的计时全局链表,看是否有定时器超时,若有则将超时的定时器记录下来。 当Tick中断到来时,在Tick中断处理函数中扫描软件定时器的计时全局链表,看是否有定时器超时,若有则将超时的定时器记录下来。
Tick中断处理函数结束后,软件定时器任务(优先级为最高)被唤醒,在该任务中调用之前记录下来的定时器的超时回调函数。 Tick中断处理函数结束后,软件定时器任务(优先级为最高)被唤醒,在该任务中调用之前记录下来的定时器的超时回调函数。
定时器状态 **定时器状态:**
- OS_SWTMR_STATUS_UNUSED(未使用) - OS_SWTMR_STATUS_UNUSED(未使用)
系统在定时器模块初始化的时候将系统中所有定时器资源初始化成该状态。 系统在定时器模块初始化的时候将系统中所有定时器资源初始化成该状态。
...@@ -39,9 +47,7 @@ Tick中断处理函数结束后,软件定时器任务(优先级为最高) ...@@ -39,9 +47,7 @@ Tick中断处理函数结束后,软件定时器任务(优先级为最高)
- OS_SWTMR_STATUS_TICKING(计数) - OS_SWTMR_STATUS_TICKING(计数)
在定时器创建后调用LOS_SwtmrStart接口,定时器将变成该状态,表示定时器运行时的状态。 在定时器创建后调用LOS_SwtmrStart接口,定时器将变成该状态,表示定时器运行时的状态。
定时器模式 **定时器模式:**
OpenHarmony系统的软件定时器提供三类定时器机制:
- 第一类是单次触发定时器,这类定时器在启动后只会触发一次定时器事件,然后定时器自动删除。 - 第一类是单次触发定时器,这类定时器在启动后只会触发一次定时器事件,然后定时器自动删除。
...@@ -55,12 +61,12 @@ OpenHarmony系统的软件定时器提供三类定时器机制: ...@@ -55,12 +61,12 @@ OpenHarmony系统的软件定时器提供三类定时器机制:
### 接口说明 ### 接口说明
OpenHarmony LiteOS-A内核的软件定时器模块提供下面几种功能,接口详细信息可以查看API参考 OpenHarmony LiteOS-A内核的软件定时器模块提供以下几种功能
**表1** 软件定时器接口说明 **表1** 软件定时器接口说明
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | ---------------------- | ------------------------------------------------------------ |
| 创建、删除定时器 | LOS_SwtmrCreate:创建软件定时器<br/>LOS_SwtmrDelete:删除软件定时器 | | 创建、删除定时器 | LOS_SwtmrCreate:创建软件定时器<br/>LOS_SwtmrDelete:删除软件定时器 |
| 启动、停止定时器 | LOS_SwtmrStart:启动软件定时器<br/>LOS_SwtmrStop:停止软件定时器 | | 启动、停止定时器 | LOS_SwtmrStart:启动软件定时器<br/>LOS_SwtmrStop:停止软件定时器 |
| 获得软件定时剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数 | | 获得软件定时剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数 |
...@@ -68,7 +74,7 @@ OpenHarmony LiteOS-A内核的软件定时器模块提供下面几种功能,接 ...@@ -68,7 +74,7 @@ OpenHarmony LiteOS-A内核的软件定时器模块提供下面几种功能,接
### 开发流程 ### 开发流程
软件定时器的典型开发流程: **软件定时器的典型开发流程:**
1. 配置软件定时器。 1. 配置软件定时器。
- 确认配置项LOSCFG_BASE_CORE_SWTMR和LOSCFG_BASE_IPC_QUEUE为打开状态; - 确认配置项LOSCFG_BASE_CORE_SWTMR和LOSCFG_BASE_IPC_QUEUE为打开状态;
...@@ -88,6 +94,7 @@ OpenHarmony LiteOS-A内核的软件定时器模块提供下面几种功能,接 ...@@ -88,6 +94,7 @@ OpenHarmony LiteOS-A内核的软件定时器模块提供下面几种功能,接
6. 删除定时器LOS_SwtmrDelete。 6. 删除定时器LOS_SwtmrDelete。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
>
> - 软件定时器的回调函数中不要做过多操作,不要使用可能引起任务挂起或者阻塞的接口或操作。 > - 软件定时器的回调函数中不要做过多操作,不要使用可能引起任务挂起或者阻塞的接口或操作。
> >
> - 软件定时器使用了系统的一个队列和一个任务资源,软件定时器任务的优先级设定为0,且不允许修改 。 > - 软件定时器使用了系统的一个队列和一个任务资源,软件定时器任务的优先级设定为0,且不允许修改 。
......
...@@ -3,9 +3,11 @@ ...@@ -3,9 +3,11 @@
## 基本概念 ## 基本概念
时间管理以系统时钟为基础。时间管理提供给应用程序所有和时间有关的服务。系统时钟是由定时/计数器产生的输出脉冲触发中断而产生的,一般定义为整数或长整数。输出脉冲的周期叫做一个“时钟滴答”。系统时钟也称为时标或者Tick。一个Tick的时长可以静态配置。用户是以秒、毫秒为单位计时,而操作系统时钟计时是以Tick为单位的,当用户需要对系统操作时,例如任务挂起、延时等,输入秒为单位的数值,此时需要时间管理模块对二者进行转换。 时间管理以系统时钟为基础。时间管理提供给应用程序所有和时间有关的服务。系统时钟是由定时/计数器产生的输出脉冲触发中断而产生的,一般定义为整数或长整数。输出脉冲的周期叫做一个“时钟滴答”。
Tick与秒之间的对应关系可以配置。 系统时钟也称为时标或者Tick。一个Tick的时长可以静态配置。用户是以秒、毫秒为单位计时,而操作系统时钟计时是以Tick为单位的,当用户需要对系统操作时,例如任务挂起、延时等,输入秒为单位的数值,此时需要时间管理模块对二者进行转换。
**Tick与秒之间的对应关系可以配置。**
- **Cycle** - **Cycle**
系统最小的计时单位。Cycle的时长由系统主频决定,系统主频就是每秒钟的Cycle数。 系统最小的计时单位。Cycle的时长由系统主频决定,系统主频就是每秒钟的Cycle数。
...@@ -13,22 +15,22 @@ Tick与秒之间的对应关系可以配置。 ...@@ -13,22 +15,22 @@ Tick与秒之间的对应关系可以配置。
- **Tick** - **Tick**
Tick是操作系统的基本时间单位,对应的时长由系统主频及每秒Tick数决定,由用户配置。 Tick是操作系统的基本时间单位,对应的时长由系统主频及每秒Tick数决定,由用户配置。
OpenHarmony系统的时间管理模块提供时间转换、统计、延迟功能以满足用户对时间相关需求的实现。 **OpenHarmony系统的时间管理模块提供时间转换、统计、延迟功能以满足用户对时间相关需求的实现。**
## 开发指导 ## 开发指导
用户需要了解当前系统运行的时间以及Tick与秒、毫秒之间的转换关系时,需要使用到时间管理模块的接口。 用户需要了解当前系统运行的时间以及Tick与秒、毫秒之间的转换关系,以及需要使用到时间管理模块的接口。
### 接口说明 ### 接口说明
OpenHarmony LiteOS-A内核的时间管理提供下面几种功能,接口详细信息可以查看API参考。 OpenHarmony LiteOS-A内核的时间管理提供以下几种功能,接口详细信息可查看API参考。
**表1** 时间管理相关接口说明 **表1** 时间管理相关接口说明
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | ------------------------------------------------------------ |
| 时间转换 | LOS_MS2Tick:毫秒转换成Tick<br/>LOS_Tick2MS:Tick转换成毫秒 | | 时间转换 | LOS_MS2Tick:毫秒转换成Tick<br/>LOS_Tick2MS:Tick转换成毫秒 |
| 时间统计 | LOS_TickCountGet:获取当前Tick数<br/>LOS_CyclePerTickGet:每个Tick的cycle数 | | 时间统计 | LOS_TickCountGet:获取当前Tick数<br/>LOS_CyclePerTickGet:每个Tick的cycle数 |
...@@ -40,6 +42,7 @@ OpenHarmony LiteOS-A内核的时间管理提供下面几种功能,接口详细 ...@@ -40,6 +42,7 @@ OpenHarmony LiteOS-A内核的时间管理提供下面几种功能,接口详细
2. 获取系统Tick数完成时间统计等。 2. 获取系统Tick数完成时间统计等。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
>
> - 获取系统Tick数需要在系统时钟使能之后。 > - 获取系统Tick数需要在系统时钟使能之后。
> >
> - 时间管理不是单独的功能模块,依赖于los_config.h中的OS_SYS_CLOCK和LOSCFG_BASE_CORE_TICK_PER_SECOND两个配置选项。 > - 时间管理不是单独的功能模块,依赖于los_config.h中的OS_SYS_CLOCK和LOSCFG_BASE_CORE_TICK_PER_SECOND两个配置选项。
...@@ -51,7 +54,7 @@ OpenHarmony LiteOS-A内核的时间管理提供下面几种功能,接口详细 ...@@ -51,7 +54,7 @@ OpenHarmony LiteOS-A内核的时间管理提供下面几种功能,接口详细
前置条件: 前置条件:
- 配置好LOSCFG_BASE_CORE_TICK_PER_SECOND,即系统每秒的Tick数,范围(0, 1000] - 配置好LOSCFG_BASE_CORE_TICK_PER_SECOND,即系统每秒的Tick数,范围(0, 1000
- 配置好OS_SYS_CLOCK 系统时钟频率,单位:Hz。 - 配置好OS_SYS_CLOCK 系统时钟频率,单位:Hz。
...@@ -117,6 +120,6 @@ uwMs = 100 ...@@ -117,6 +120,6 @@ uwMs = 100
``` ```
LOS_CyclePerTickGet = 49500 LOS_CyclePerTickGet = 49500
LOS_TickCountGet = 5042 LOS_TickCountGet = 347931
LOS_TickCountGet after delay = 5242 LOS_TickCountGet after delay = 348134
``` ```
\ No newline at end of file
...@@ -15,7 +15,7 @@ OpenHarmony LiteOS-A的事件模块提供的事件,具有如下特点: ...@@ -15,7 +15,7 @@ OpenHarmony LiteOS-A的事件模块提供的事件,具有如下特点:
- 任务通过创建事件控制块来触发事件或等待事件。 - 任务通过创建事件控制块来触发事件或等待事件。
- 事件间相互独立,内部实现为一个32位无符号整型,每一位标识一种事件类型。第25位不可用,因此最多可支持31种事件类型。 - 事件间相互独立,内部实现为一个32位无符号整型,每一位标识一种事件类型。(0表示该时间类型未发生,1表示该事件类型已经发生,一共31种事件类型,第25bit位(`0x02U << 24`)系统保留)
- 事件仅用于任务间的同步,不提供数据传输功能。 - 事件仅用于任务间的同步,不提供数据传输功能。
...@@ -80,10 +80,10 @@ OpenHarmony LiteOS-A内核的事件模块提供下面几种功能。 ...@@ -80,10 +80,10 @@ OpenHarmony LiteOS-A内核的事件模块提供下面几种功能。
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 初始化事件 | LOS_EventInit:初始化一个事件控制块 | | 初始化事件 | LOS_EventInit:初始化一个事件控制块 |
| 读/写事件 | -&nbsp;LOS_EventRead:读取指定事件类型,超时时间为相对时间:单位为Tick<br/>-&nbsp;LOS_EventWrite:写指定的事件类型 | | 读/写事件 | -&nbsp;LOS_EventRead:读取指定事件类型,超时时间为相对时间:单位为Tick<br/>-&nbsp;LOS_EventWrite写指定的事件类型 |
| 清除事件 | LOS_EventClear:清除指定的事件类型 | | 清除事件 | LOS_EventClear:清除指定的事件类型 |
| 校验事件掩码 | -&nbsp;LOS_EventPoll:根据用户传入的事件ID、事件掩码及读取模式,返回用户传入的事件是否符合预期<br/>-&nbsp;LOS_EventDestroy:销毁指定的事件控制块 | | 校验事件掩码 | -&nbsp;LOS_EventPoll根据用户传入的事件ID、事件掩码及读取模式,返回用户传入的事件是否符合预期<br/>-&nbsp;LOS_EventDestroy:销毁指定的事件控制块 |
| 销毁事件 | LOS_EventDestroy:销毁指定的事件控制块 | | 销毁事件 | LOS_EventDestroy销毁指定的事件控制块 |
### 开发流程 ### 开发流程
...@@ -103,7 +103,7 @@ OpenHarmony LiteOS-A内核的事件模块提供下面几种功能。 ...@@ -103,7 +103,7 @@ OpenHarmony LiteOS-A内核的事件模块提供下面几种功能。
6. 事件控制块销毁 6. 事件控制块销毁
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 进行事件读写操作时,事件的第25位为保留位,不可以进行位设置。 > - 进行事件读写操作时,事件的第25bit(`0x02U << 24`)为保留bit位,不可以进行位设置。
> >
> - 对同一事件反复写入,算作一次写入。 > - 对同一事件反复写入,算作一次写入。
...@@ -128,8 +128,9 @@ OpenHarmony LiteOS-A内核的事件模块提供下面几种功能。 ...@@ -128,8 +128,9 @@ OpenHarmony LiteOS-A内核的事件模块提供下面几种功能。
### 编程示例 ### 编程示例
示例代码如下: 本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数Example_EventEntry。
示例代码如下:
``` ```
#include "los_event.h" #include "los_event.h"
......
...@@ -87,7 +87,7 @@ ...@@ -87,7 +87,7 @@
### 编程实例 ### 编程实例
**实例描述** #### 实例描述
本实例实现如下流程: 本实例实现如下流程:
...@@ -99,10 +99,11 @@ ...@@ -99,10 +99,11 @@
4. 100Tick休眠时间到达后,Example_MutexTask2被唤醒, 释放互斥锁,唤醒Example_MutexTask1。Example_MutexTask1成功获取到互斥锁后,释放,删除互斥锁。 4. 100Tick休眠时间到达后,Example_MutexTask2被唤醒, 释放互斥锁,唤醒Example_MutexTask1。Example_MutexTask1成功获取到互斥锁后,释放,删除互斥锁。
**示例代码** #### 编程示例
示例代码如下: 本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数Example_MutexEntry。
示例代码如下:
``` ```
#include <string.h> #include <string.h>
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。 任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。
可以通过调整读队列和写队列的超时时间来调整读写接口的阻塞模式,如果将读队列和写队列的超时时间设置为0,就不会挂起任务,接口会直接返回,这就是非阻塞模式。反之,如果将队列和写队列的超时时间设置为大于0的时间,就会以阻塞模式运行。 可以通过调整读队列和写队列的超时时间来调整读写接口的阻塞模式,如果将读队列和写队列的超时时间设置为0,就不会挂起任务,接口会直接返回,这就是非阻塞模式。反之,如果将队列和写队列的超时时间设置为大于0的时间,就会以阻塞模式运行。
消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性: 消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性:
...@@ -137,8 +137,9 @@ typedef struct { ...@@ -137,8 +137,9 @@ typedef struct {
### 编程示例 ### 编程示例
示例代码如下: 本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数ExampleQueue。
示例代码如下:
``` ```
#include "los_task.h" #include "los_task.h"
......
...@@ -116,8 +116,9 @@ typedef struct { ...@@ -116,8 +116,9 @@ typedef struct {
### 编程示例 ### 编程示例
示例代码如下: 本演示代码在./kernel/liteos_a/testsuites/kernel/src/osTest.c中编译验证,在TestTaskEntry中调用验证入口函数ExampleSem。
示例代码如下:
``` ```
#include "los_sem.h" #include "los_sem.h"
......
...@@ -10,23 +10,26 @@ Futex(Fast userspace mutex,用户态快速互斥锁)是内核提供的一种 ...@@ -10,23 +10,26 @@ Futex(Fast userspace mutex,用户态快速互斥锁)是内核提供的一种
当用户态线程释放锁时,先在用户态进行锁状态的判断维护,若此时没有其他线程被该锁阻塞,则直接在用户态进行解锁返回;反之,则需要进行阻塞线程的唤醒操作,通过Futex系统调用请求内核介入来唤醒阻塞队列中的线程。 当用户态线程释放锁时,先在用户态进行锁状态的判断维护,若此时没有其他线程被该锁阻塞,则直接在用户态进行解锁返回;反之,则需要进行阻塞线程的唤醒操作,通过Futex系统调用请求内核介入来唤醒阻塞队列中的线程。
## 运行机制 ## 运行机制
当用户态产生锁的竞争或释放需要进行相关线程的调度操作时,会触发Futex系统调用进入内核,此时会将用户态锁的地址传入内核,并在内核的Futex中以锁地址来区分用户态的每一把锁,因为用户态可用虚拟地址空间为1GiB,为了便于查找、管理,内核Futex采用哈希桶来存放用户态传入的锁。 当用户态产生锁的竞争或释放需要进行相关线程的调度操作时,会触发Futex系统调用进入内核,此时会将用户态锁的地址传入内核,并在内核的Futex中以锁地址来区分用户态的每一把锁,因为用户态可用虚拟地址空间为1GiB,为了便于查找、管理,内核Futex采用哈希桶来存放用户态传入的锁。
当前哈希桶共有80个,0~63号桶用于存放私有锁(以虚拟地址进行哈希),64~79号桶用于存放共享锁(以物理地址进行哈希),私有/共享属性通过用户态锁的初始化以及Futex系统调用入参确定。 当前哈希桶共有80个,~~0-63号桶用于存放私有锁(以虚拟地址进行哈希),64-79~~号桶用于存放共享锁(以物理地址进行哈希),私有/共享属性通过用户态锁的初始化以及Futex系统调用入参确定。
## Futex设计图
**图1** Futex设计图 **图1**
![zh-cn_image_0000001127535690](figures/zh-cn_image_0000001127535690.jpg) ![zh-cn_image_0000001127535690](figures/zh-cn_image_0000001127535690.jpg)
如图1,每个futex哈希桶中存放被futex_list串联起来的哈希值相同的futex node,每个futex node对应一个被挂起的task,node中key值唯一标识一把用户态锁,具有相同key值的node被queue_list串联起来表示被同一把锁阻塞的task队列。 如图1,每个futex哈希桶中存放被futex_list串联起来的哈希值相同的futex node,每个futex node对应一个被挂起的task,node中key值唯一标识一把用户态锁,具有相同key值的node被queue_list串联起来表示被同一把锁阻塞的task队列。
Futex有以下三种操作: ## Futex有以下三种操作:
**表1** Futex模块接口 **Futex模块接口**
| 功能分类 | 接口**名称** | 描述 | | 功能分类 | 接口**名称** | 描述 |
| -------- | -------- | -------- | | -------------- | -------------- | ------------------------------------- |
| 设置线程等待 | OsFutexWait | 向Futex表中插入代表被阻塞的线程的node | | 设置线程等待 | OsFutexWait | 向Futex表中插入代表被阻塞的线程的node |
| 唤醒被阻塞线程 | OsFutexWake | 唤醒一个被指定锁阻塞的线程 | | 唤醒被阻塞线程 | OsFutexWake | 唤醒一个被指定锁阻塞的线程 |
| 调整锁的地址 | OsFutexRequeue | 调整指定锁在Futex表中的位置 | | 调整锁的地址 | OsFutexRequeue | 调整指定锁在Futex表中的位置 |
......
...@@ -13,8 +13,8 @@ ...@@ -13,8 +13,8 @@
**表1** 信号的运作流程及相关接口(用户态接口) **表1** 信号的运作流程及相关接口(用户态接口)
| 功能分类 | 接口**名称** | 描述 | | 功能分类 | 接口**名称** | 描述 |
| -------- | -------- | -------- | | ---------------- | --------------------------------------------------- | ------------------------------------------------------------ |
| 注册信号回调函数 | signal: | 注册信号总入口及注册和去注册某信号的回调函数。 | | 注册信号回调函数 | signal | 注册信号总入口及注册和去注册某信号的回调函数。 |
| 注册信号回调函数 | sigaction | 功能同signal,但增加了信号发送相关的配置选项,目前仅支持SIGINFO结构体中的部分参数。 | | 注册信号回调函数 | sigaction | 功能同signal,但增加了信号发送相关的配置选项,目前仅支持SIGINFO结构体中的部分参数。 |
| 发送信号 | kill<br/>pthread_kill<br/>raise<br/>alarm<br/>abort | 发送信号给某个进程或进程内发送消息给某线程,为某进程下的线程设置信号标志位。 | | 发送信号 | kill<br/>pthread_kill<br/>raise<br/>alarm<br/>abort | 发送信号给某个进程或进程内发送消息给某线程,为某进程下的线程设置信号标志位。 |
| 触发回调 | 无 | 由系统调用与中断触发,内核态与用户态切换前会先进入用户态指定函数并处理完相应回调函数,再回到原用户态程序继续运行。 | | 触发回调 | 无 | 由系统调用与中断触发,内核态与用户态切换前会先进入用户态指定函数并处理完相应回调函数,再回到原用户态程序继续运行。 |
...@@ -22,18 +22,20 @@ ...@@ -22,18 +22,20 @@
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 信号机制为提供给用户态程序进程间通信的能力,故推荐使用上表1列出的用户态POSIX相关接口。 > 信号机制为提供给用户态程序进程间通信的能力,故推荐使用上表1列出的用户态POSIX相关接口。
> >
> 注册回调函数: > **注册回调函数:**
> >
> >
> ``` > ```
> void *signal(int sig, void (*func)(int))(int); > void *signal(int sig, void (*func)(int))(int);
> ``` > ```
> >
> a. 31 号信号,该信号用来注册该进程的回调函数处理入口,不可重复注册。 > - 31 号信号,该信号用来注册该进程的回调函数处理入口,不可重复注册。
> >
> b. 0-30 号信号,该信号段用来注册与去注册回调函数。
> >
> 注册回调函数: > - 0-30 号信号,该信号段用来注册与去注册回调函数。
>
>
> **注册回调函数:**
> >
> >
> ``` > ```
...@@ -42,16 +44,21 @@ ...@@ -42,16 +44,21 @@
> >
> 支持信号注册的配置修改和配置获取,目前仅支持SIGINFO的选项,SIGINFO内容见sigtimedwait接口内描述。 > 支持信号注册的配置修改和配置获取,目前仅支持SIGINFO的选项,SIGINFO内容见sigtimedwait接口内描述。
> >
> 发送信号: > **发送信号:**
>
> - 进程接收信号存在默认行为,单不支持POSIX标准所给出的STOP及CONTINUE、COREDUMP功能。
>
>
> - 进程无法屏蔽SIGSTOP、SIGKILL、SIGCONT信号。
>
>
> - 某进程后被杀死后,若其父进程不回收该进程,其转为僵尸进程。
> >
> a. 进程接收信号存在默认行为,单不支持POSIX标准所给出的STOP及CONTINUE、COREDUMP功能。
> >
> b. 进程无法屏蔽SIGSTOP、SIGKILL、SIGCONT信号 > - 进程接收到某信号后,直到该进程被调度后才会执行信号回调
> >
> c. 某进程后被杀死后,若其父进程不回收该进程,其转为僵尸进程。
> >
> d. 进程接收到某信号后,直到该进程被调度后才会执行信号回调 > - 进程结束后会发送SIGCHLD信号给父进程,该发送动作无法取消
> >
> e. 进程结束后会发送SIGCHLD信号给父进程,该发送动作无法取消。
> >
> f. 无法通过信号唤醒处于DELAY状态的进程。 > - 无法通过信号唤醒处于DELAY状态的进程。
\ No newline at end of file
...@@ -5,12 +5,20 @@ ...@@ -5,12 +5,20 @@
LiteIPC是OpenHarmony LiteOS-A内核提供的一种新型IPC(Inter-Process Communication,即进程间通信)机制,不同于传统的System V IPC机制,LiteIPC主要是为RPC(Remote Procedure Call,即远程过程调用)而设计的,而且是通过设备文件的方式对上层提供接口的,而非传统的API函数方式。 LiteIPC是OpenHarmony LiteOS-A内核提供的一种新型IPC(Inter-Process Communication,即进程间通信)机制,不同于传统的System V IPC机制,LiteIPC主要是为RPC(Remote Procedure Call,即远程过程调用)而设计的,而且是通过设备文件的方式对上层提供接口的,而非传统的API函数方式。
LiteIPC中有两个主要概念,一个是ServiceManager,另一个是Service。整个系统只能有一个ServiceManager,而Service可以有多个。ServiceManager有两个主要功能:一是负责Service的注册和注销,二是负责管理Service的访问权限(只有有权限的任务(Task)可以向对应的Service发送IPC消息)。 LiteIPC中有两个主要概念,一个是ServiceManager,另一个是Service。整个系统只能有一个ServiceManager,而Service可以有多个。
**ServiceManager有两个主要功能:**
- 一是负责Service的注册和注销,
- 二是负责管理Service的访问权限(只有有权限的任务(Task)可以向对应的Service发送IPC消息)。
## 运行机制 ## 运行机制
首先将需要接收IPC消息的任务通过ServiceManager注册成为一个Service,然后通过ServiceManager为该Service任务配置访问权限,即指定哪些任务可以向该Service任务发送IPC消息。LiteIPC的核心思想就是在内核态为每个Service任务维护一个IPC消息队列,该消息队列通过LiteIPC设备文件向上层用户态程序分别提供代表收取IPC消息的读操作和代表发送IPC消息的写操作。 首先将需要接收IPC消息的任务通过ServiceManager注册成为一个Service,然后通过ServiceManager为该Service任务配置访问权限,即指定哪些任务可以向该Service任务发送IPC消息。
LiteIPC的核心思想就是在内核态为每个Service任务维护一个IPC消息队列,该消息队列通过LiteIPC设备文件向上层用户态程序分别提供代表收取IPC消息的读操作和代表发送IPC消息的写操作。
## 开发指导 ## 开发指导
...@@ -21,7 +29,7 @@ LiteIPC中有两个主要概念,一个是ServiceManager,另一个是Service ...@@ -21,7 +29,7 @@ LiteIPC中有两个主要概念,一个是ServiceManager,另一个是Service
**表1** LiteIPC模块接口(仅LiteOS-A内部使用) **表1** LiteIPC模块接口(仅LiteOS-A内部使用)
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | ------------- | ------------------------------------------------------------ |
| 模块初始化 | OsLiteIpcInit:初始化LiteIPC模块 | | 模块初始化 | OsLiteIpcInit:初始化LiteIPC模块 |
| IPC消息内存池 | -&nbsp;LiteIpcPoolInit:初始化进程的IPC消息内存池<br/>-&nbsp;LiteIpcPoolReInit:重新初始化进程的IPC消息内存池<br/>-&nbsp;LiteIpcPoolDelete:释放进程的IPC消息内存池 | | IPC消息内存池 | -&nbsp;LiteIpcPoolInit:初始化进程的IPC消息内存池<br/>-&nbsp;LiteIpcPoolReInit:重新初始化进程的IPC消息内存池<br/>-&nbsp;LiteIpcPoolDelete:释放进程的IPC消息内存池 |
| Service管理 | LiteIpcRemoveServiceHandle:删除指定的Service | | Service管理 | LiteIpcRemoveServiceHandle:删除指定的Service |
......
...@@ -16,7 +16,7 @@ OpenHarmony系统的动态加载与链接机制主要是由内核加载器以及 ...@@ -16,7 +16,7 @@ OpenHarmony系统的动态加载与链接机制主要是由内核加载器以及
## 运行机制 ## 运行机制
**图1** 动态加载流程 **图1** **动态加载流程**
![zh-cn_image_0000001133104502](figures/zh-cn_image_0000001133104502.png) ![zh-cn_image_0000001133104502](figures/zh-cn_image_0000001133104502.png)
1. 内核将应用程序ELF文件的PT_LOAD段信息映射至进程空间。对于ET_EXEC类型的文件,根据PT_LOAD段中p_vaddr进行固定地址映射;对于ET_DYN类型(位置无关的可执行程序,通过编译选项“-fPIE”得到)的文件,内核通过mmap接口选择base基址进行映射(load_addr = base + p_vaddr)。 1. 内核将应用程序ELF文件的PT_LOAD段信息映射至进程空间。对于ET_EXEC类型的文件,根据PT_LOAD段中p_vaddr进行固定地址映射;对于ET_DYN类型(位置无关的可执行程序,通过编译选项“-fPIE”得到)的文件,内核通过mmap接口选择base基址进行映射(load_addr = base + p_vaddr)。
...@@ -25,18 +25,18 @@ OpenHarmony系统的动态加载与链接机制主要是由内核加载器以及 ...@@ -25,18 +25,18 @@ OpenHarmony系统的动态加载与链接机制主要是由内核加载器以及
3. 动态链接器自举并查找应用程序依赖的所有共享库并对导入符号进行重定位,最后跳转至应用程序的e_entry(或base + e_entry),开始运行应用程序。 3. 动态链接器自举并查找应用程序依赖的所有共享库并对导入符号进行重定位,最后跳转至应用程序的e_entry(或base + e_entry),开始运行应用程序。
**图2** 程序执行流程 **图2** **程序执行流程**
![zh-cn_image_0000001133264664](figures/zh-cn_image_0000001133264664.png) ![zh-cn_image_0000001133264664](figures/zh-cn_image_0000001133264664.png)
1. 加载器与链接器调用mmap映射PT_LOAD段 1. 加载器与链接器调用mmap映射PT_LOAD段
2. 内核调用map_pages接口查找并映射pagecache已有的缓存 2. 内核调用map_pages接口查找并映射pagecache已有的缓存
3. 程序执行时,虚拟内存区间若无具体的物理内存做映射,系统将触发缺页中断,将elf文件内容读入物理内存,并将该内存块加入pagecache 3. 程序执行时,虚拟内存区间若无具体的物理内存做映射,系统将触发缺页中断,将elf文件内容读入物理内存,并将该内存块加入pagecache
4. 将已读入文件内容的物理内存与虚拟地址区间做映射 4. 将已读入文件内容的物理内存与虚拟地址区间做映射
5. 程序继续执行 5. 程序继续执行
## 开发指导 ## 开发指导
...@@ -47,7 +47,7 @@ OpenHarmony系统的动态加载与链接机制主要是由内核加载器以及 ...@@ -47,7 +47,7 @@ OpenHarmony系统的动态加载与链接机制主要是由内核加载器以及
**表1** 内核加载器模块接口 **表1** 内核加载器模块接口
| 功能分类 | 接口**名称** | 描述 | | 功能分类 | 接口**名称** | 描述 |
| -------- | -------- | -------- | | ---------- | ---------------- | -------------------------------- |
| 模块初始化 | LOS_DoExecveFile | 根据输入的参数执行指定的用户程序 | | 模块初始化 | LOS_DoExecveFile | 根据输入的参数执行指定的用户程序 |
......
...@@ -12,7 +12,7 @@ OpenHarmony系统通过VDSO机制实现上层用户态程序可以快速读取 ...@@ -12,7 +12,7 @@ OpenHarmony系统通过VDSO机制实现上层用户态程序可以快速读取
VDSO其核心思想就是内核看护一段内存,并将这段内存映射(只读)进用户态应用程序的地址空间,应用程序通过链接vdso.so后,将某些系统调用替换为直接读取这段已映射的内存从而避免系统调用达到加速的效果。 VDSO其核心思想就是内核看护一段内存,并将这段内存映射(只读)进用户态应用程序的地址空间,应用程序通过链接vdso.so后,将某些系统调用替换为直接读取这段已映射的内存从而避免系统调用达到加速的效果。
VDSO总体可分为数据页与代码页两部分: **VDSO总体可分为数据页与代码页两部分:**
- 数据页提供内核映射给用户进程的内核时数据; - 数据页提供内核映射给用户进程的内核时数据;
...@@ -21,7 +21,7 @@ VDSO总体可分为数据页与代码页两部分: ...@@ -21,7 +21,7 @@ VDSO总体可分为数据页与代码页两部分:
**图1** VDSO系统设计 **图1** VDSO系统设计
![zh-cn_image_0000001173586763](figures/zh-cn_image_0000001173586763.jpg) ![zh-cn_image_0000001173586763](figures/zh-cn_image_0000001173586763.jpg)
如图1所示,当前VDSO机制有以下几个主要步骤: **如图1所示,当前VDSO机制有以下几个主要步骤:**
① 内核初始化时进行VDSO数据页的创建; ① 内核初始化时进行VDSO数据页的创建;
...@@ -42,6 +42,9 @@ VDSO总体可分为数据页与代码页两部分: ...@@ -42,6 +42,9 @@ VDSO总体可分为数据页与代码页两部分:
⑨ 将从VDSO数据页获取到的数据作为结果返回给用户程序; ⑨ 将从VDSO数据页获取到的数据作为结果返回给用户程序;
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 当前VDSO机制支持LibC库clock_gettime接口的CLOCK_REALTIME_COARSE与CLOCK_MONOTONIC_COARSE功能,clock_gettime接口的使用方法详见POSIX标准。用户调用C库接口clock_gettime(CLOCK_REALTIME_COARSE, &amp;ts)或者clock_gettime(CLOCK_MONOTONIC_COARSE, &amp;ts)即可使用VDSO机制。 >
> - 当前VDSO机制支持LibC库clock_gettime接口的CLOCK_REALTIME_COARSE与CLOCK_MONOTONIC_COARSE功能,clock_gettime接口的使用方法详见POSIX标准。
>
> - 用户调用C库接口clock_gettime(CLOCK_REALTIME_COARSE, &amp;ts)或者clock_gettime(CLOCK_MONOTONIC_COARSE, &amp;ts)即可使用VDSO机制。
> >
> - 使用VDSO机制得到的时间精度会与系统tick中断的精度保持一致,适用于对时间没有高精度要求且短时间内会高频触发clock_gettime或gettimeofday系统调用的场景,若有高精度要求,不建议采用VDSO机制。 > - 使用VDSO机制得到的时间精度会与系统tick中断的精度保持一致,适用于对时间没有高精度要求且短时间内会高频触发clock_gettime或gettimeofday系统调用的场景,若有高精度要求,不建议采用VDSO机制。
\ No newline at end of file
...@@ -42,11 +42,12 @@ LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK:开关宏,默认关闭;若打开这 ...@@ -42,11 +42,12 @@ LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK:开关宏,默认关闭;若打开这
**示例代码** **示例代码**
该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试.
代码实现如下: 代码实现如下:
``` ```c
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "los_memory.h" #include "los_memory.h"
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
- 内存水线:即内存池的最大使用量,每次申请和释放时,都会更新水线值,实际业务可根据该值,优化内存池大小; - 内存水线:即内存池的最大使用量,每次申请和释放时,都会更新水线值,实际业务可根据该值,优化内存池大小;
- 碎片率:衡量内存池的碎片化程度,碎片率高表现为内存池剩余内存很多,但是最大空闲内存块很小,可以用公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)来度量 - 碎片率:衡量内存池的碎片化程度,碎片率高表现为内存池剩余内存很多,但是最大空闲内存块很小,可以用公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)来度量
- 其他统计信息:调用接口LOS_MemInfoGet时,会扫描内存池的节点信息,统计出相关信息。 - 其他统计信息:调用接口LOS_MemInfoGet时,会扫描内存池的节点信息,统计出相关信息。
...@@ -25,7 +25,7 @@ LOSCFG_MEM_WATERLINE:开关宏,默认关闭;若需要打开这个功能, ...@@ -25,7 +25,7 @@ LOSCFG_MEM_WATERLINE:开关宏,默认关闭;若需要打开这个功能,
关键结构体介绍: 关键结构体介绍:
``` ```c
typedef struct { typedef struct {
UINT32 totalUsedSize; // 内存池的内存使用量 UINT32 totalUsedSize; // 内存池的内存使用量
UINT32 totalFreeSize; // 内存池的剩余内存大小 UINT32 totalFreeSize; // 内存池的剩余内存大小
...@@ -38,7 +38,7 @@ typedef struct { ...@@ -38,7 +38,7 @@ typedef struct {
} LOS_MEM_POOL_STATUS; } LOS_MEM_POOL_STATUS;
``` ```
- 内存水线获取:调用LOS_MemInfoGet接口,第1个参数是内存池首地址,第2个参数是LOS_MEM_POOL_STATUS类型的句柄,其中字段usageWaterLine即水线值。 - 内存水线获取:调用 LOS_MemInfoGet(VOID *pool, LOS_MEM_POOL_STATUS *poolStatus)接口,第1个参数是内存池首地址,第2个参数是LOS_MEM_POOL_STATUS类型的句柄,其中字段usageWaterLine即水线值。
- 内存碎片率计算:同样调用LOS_MemInfoGet接口,可以获取内存池的剩余内存大小和最大空闲内存块大小,然后根据公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)得出此时的动态内存池碎片率。 - 内存碎片率计算:同样调用LOS_MemInfoGet接口,可以获取内存池的剩余内存大小和最大空闲内存块大小,然后根据公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)得出此时的动态内存池碎片率。
...@@ -53,13 +53,12 @@ typedef struct { ...@@ -53,13 +53,12 @@ typedef struct {
3. 利用公式算出使用率及碎片率。 3. 利用公式算出使用率及碎片率。
**示例代码** **示例代码**
该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。
代码实现如下: 代码实现如下:
``` ```c
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "los_task.h" #include "los_task.h"
...@@ -77,8 +76,7 @@ void MemInfoTaskFunc(void) ...@@ -77,8 +76,7 @@ void MemInfoTaskFunc(void)
unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize; unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize;
/* 算出内存池当前的使用率百分比 */ /* 算出内存池当前的使用率百分比 */
unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool); unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool);
printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, poolStatus.totalFreeSize, poolStatus.usageWaterLine);
poolStatus.totalFreeSize, poolStatus.usageWaterLine);
} }
int MemTest(void) int MemTest(void)
...@@ -93,9 +91,9 @@ int MemTest(void) ...@@ -93,9 +91,9 @@ int MemTest(void)
ret = LOS_TaskCreate(&taskID, &taskStatus); ret = LOS_TaskCreate(&taskID, &taskStatus);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("task create failed\n"); printf("task create failed\n");
return -1; return LOS_NOK;
} }
return 0; return LOS_OK;
} }
``` ```
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
2. LOS_RECORD_LR_CNT:记录的LR层数,默认3层;每层LR消耗sizeof(void \*)字节数的内存。 2. LOS_RECORD_LR_CNT:记录的LR层数,默认3层;每层LR消耗sizeof(void \*)字节数的内存。
3. LOS_OMIT_LR_CNT:忽略的LR层数,默认2层,即从调用LOS_MemAlloc的函数开始记录,可根据实际情况调整。为啥需要这个配置?有3点原因如下: 3. LOS_OMIT_LR_CNT:忽略的LR层数,默认2层,即从调用LOS_MemAlloc的函数开始记录,可根据实际情况调整。需要此配置原因如下:
- LOS_MemAlloc接口内部也有函数调用; - LOS_MemAlloc接口内部也有函数调用;
- 外部可能对LOS_MemAlloc接口有封装; - 外部可能对LOS_MemAlloc接口有封装;
- LOS_RECORD_LR_CNT 配置的LR层数有限; - LOS_RECORD_LR_CNT 配置的LR层数有限;
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
该调测功能可以分析关键的代码逻辑中是否存在内存泄漏。开启这个功能,每次申请内存时,会记录LR信息。在需要检测的代码段前后,调用LOS_MemUsedNodeShow接口,每次都会打印指定内存池已使用的全部节点信息,对比前后两次的节点信息,新增的节点信息就是疑似泄漏的内存节点。通过LR,可以找到具体申请的代码位置,进一步确认是否泄漏。 该调测功能可以分析关键的代码逻辑中是否存在内存泄漏。开启这个功能,每次申请内存时,会记录LR信息。在需要检测的代码段前后,调用LOS_MemUsedNodeShow接口,每次都会打印指定内存池已使用的全部节点信息,对比前后两次的节点信息,新增的节点信息就是疑似泄漏的内存节点。通过LR,可以找到具体申请的代码位置,进一步确认是否泄漏。
调用LOS_MemUsedNodeShow接口输出的节点信息格式如下:每1行为一个节点信息;第1列为节点地址,可以根据这个地址,使用GDB等手段查看节点完整信息;第2列为节点的大小,等于节点头大小+数据域大小;第3~5列为函数调用关系LR地址,可以根据这个值,结合汇编文件,查看该节点具体申请的位置。 调用LOS_MemUsedNodeShow接口输出的节点信息格式如下:每1行为一个节点信息;第1列为节点地址,可以根据这个地址,使用GDB等工具查看节点完整信息;第2列为节点的大小,等于节点头大小+数据域大小;第3~5列为函数调用关系LR地址,可以根据这个值,结合汇编文件,查看该节点具体申请的位置。
``` ```
...@@ -62,9 +62,10 @@ node size LR[0] LR[1] LR[2] ...@@ -62,9 +62,10 @@ node size LR[0] LR[1] LR[2]
**示例代码** **示例代码**
该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试.
代码实现如下: 代码实现如下:
``` ```c
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "los_memory.h" #include "los_memory.h"
......
...@@ -6,16 +6,16 @@ ...@@ -6,16 +6,16 @@
CPU(中央处理器,Central Processing Unit)占用率分为系统CPU占用率、进程CPU占用率、任务CPU占用率和中断CPU占用率。用户通过系统级的CPU占用率,判断当前系统负载是否超出设计规格。通过系统中各个进程/任务/中断的CPU占用情况,判断各个进程/任务/中断的CPU占用率是否符合设计的预期。 CPU(中央处理器,Central Processing Unit)占用率分为系统CPU占用率、进程CPU占用率、任务CPU占用率和中断CPU占用率。用户通过系统级的CPU占用率,判断当前系统负载是否超出设计规格。通过系统中各个进程/任务/中断的CPU占用情况,判断各个进程/任务/中断的CPU占用率是否符合设计的预期。
- 系统CPU占用率(CPU Percent) - 系统CPU占用率(CPU Percent)
指周期时间内系统的CPU占用率,用于表示系统一段时间内的闲忙程度,也表示CPU的负载情况。系统CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分。100表示系统满负荷运转。 指周期时间内系统的CPU占用率,用于表示系统一段时间内的闲忙程度,也表示CPU的负载情况。系统CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分之一。100表示系统满负荷运转。
- 进程CPU占用率 - 进程CPU占用率
指单个进程的CPU占用率,用于表示单个进程在一段时间内的闲忙程度。进程CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分。100表示在一段时间内系统一直在运行该进程。 指单个进程的CPU占用率,用于表示单个进程在一段时间内的闲忙程度。进程CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分之一。100表示在一段时间内系统一直在运行该进程。
- 任务CPU占用率 - 任务CPU占用率
指单个任务的CPU占用率,用于表示单个任务在一段时间内的闲忙程度。任务CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分。100表示在一段时间内系统一直在运行该任务。 指单个任务的CPU占用率,用于表示单个任务在一段时间内的闲忙程度。任务CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分之一。100表示在一段时间内系统一直在运行该任务。
- 中断CPU占用率 - 中断CPU占用率
指单个中断的CPU占用率,用于表示单个中断在一段时间内的闲忙程度。中断CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分。100表示在一段时间内系统一直在运行该中断。 指单个中断的CPU占用率,用于表示单个中断在一段时间内的闲忙程度。中断CPU占用率的有效表示范围为0~100,其精度(可通过配置调整)为百分之一。100表示在一段时间内系统一直在运行该中断。
## 运行机制 ## 运行机制
...@@ -57,6 +57,7 @@ OpenHarmony 提供以下四种CPU占用率的信息查询: ...@@ -57,6 +57,7 @@ OpenHarmony 提供以下四种CPU占用率的信息查询:
| 进程CPU占用率 | LOS_GetAllProcessCpuUsage | 获取系统所有进程的历史CPU占用率 | | 进程CPU占用率 | LOS_GetAllProcessCpuUsage | 获取系统所有进程的历史CPU占用率 |
| 任务CPU占用率 | LOS_HistoryTaskCpuUsage | 获取指定任务历史CPU占用率 | | 任务CPU占用率 | LOS_HistoryTaskCpuUsage | 获取指定任务历史CPU占用率 |
| 中断CPU占用率 | LOS_GetAllIrqCpuUsage | 获取系统所有中断的历史CPU占用率 | | 中断CPU占用率 | LOS_GetAllIrqCpuUsage | 获取系统所有中断的历史CPU占用率 |
| 重置 | LOS_CpupReset | 重置CPU 占用率相关数据 |
### 开发流程 ### 开发流程
...@@ -102,10 +103,11 @@ CPU占用率的典型开发流程: ...@@ -102,10 +103,11 @@ CPU占用率的典型开发流程:
**示例代码** **示例代码**
该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。
代码实现如下: 代码实现如下:
``` ```c
#include "los_task.h" #include "los_task.h"
#include "los_cpup.h" #include "los_cpup.h"
#define MODE 4 #define MODE 4
...@@ -113,27 +115,27 @@ UINT32 g_cpuTestTaskID; ...@@ -113,27 +115,27 @@ UINT32 g_cpuTestTaskID;
VOID ExampleCpup(VOID) VOID ExampleCpup(VOID)
{ {
printf("entry cpup test example\n"); printf("entry cpup test example\n");
while(1) { while (1) {
usleep(100); usleep(100); // 100: delay for 100ms
} }
} }
UINT32 ItCpupTest(VOID) UINT32 ItCpupTest(VOID)
{ {
UINT32 ret; UINT32 ret;
UINT32 cpupUse; UINT32 cpupUse;
TSK_INIT_PARAM_S cpupTestTask = { 0 }; TSK_INIT_PARAM_S cpupTestTask = {0};
memset(&cpupTestTask, 0, sizeof(TSK_INIT_PARAM_S)); memset(&cpupTestTask, 0, sizeof(TSK_INIT_PARAM_S));
cpupTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleCpup; cpupTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleCpup;
cpupTestTask.pcName = "TestCpupTsk"; cpupTestTask.pcName = "TestCpupTsk";
cpupTestTask.uwStackSize = 0x800; cpupTestTask.uwStackSize = 0x800; // 0x800: cpup test task stack size
cpupTestTask.usTaskPrio = 5; cpupTestTask.usTaskPrio = 5; // 5: cpup test task priority
ret = LOS_TaskCreate(&g_cpuTestTaskID, &cpupTestTask); ret = LOS_TaskCreate(&g_cpuTestTaskID, &cpupTestTask);
if(ret != LOS_OK) { if (ret != LOS_OK) {
printf("cpupTestTask create failed .\n"); printf("cpupTestTask create failed .\n");
return LOS_NOK; return LOS_NOK;
} }
usleep(100); usleep(100); // 100: delay for 100ms
/* 获取当前系统历史CPU占用率 */ /* 获取当前系统历史CPU占用率 */
cpupUse = LOS_HistorySysCpuUsage(CPU_LESS_THAN_1S); cpupUse = LOS_HistorySysCpuUsage(CPU_LESS_THAN_1S);
......
...@@ -13,12 +13,12 @@ cpup [_mode_] [_taskID_] ...@@ -13,12 +13,12 @@ cpup [_mode_] [_taskID_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| mode | -&nbsp;缺省:显示系统最近10s内的CPU占用率。<br/>-&nbsp;0:显示系统最近10s内的CPU占用率。<br/>-&nbsp;1:显示系统最近1s内的CPU占用率。<br/>-&nbsp;其他数字:显示系统启动至今总的CPU&nbsp;占用率。 | [0,0xFFFFFFFF] | | mode | -&nbsp;缺省:显示系统最近10s内的CPU占用率。<br/>-&nbsp;0:显示系统最近10s内的CPU占用率。<br/>-&nbsp;1:显示系统最近1s内的CPU占用率。<br/>-&nbsp;其他数字:显示系统启动至今总的CPU&nbsp;占用率。 | [0, 0xFFFFFFFF] |
| taskID | 任务ID号 | [0,0xFFFFFFFF] | | taskID | 任务ID号 | [0, 0xFFFFFFFF] |
## 使用指南 ## 使用指南
...@@ -37,7 +37,7 @@ cpup [_mode_] [_taskID_] ...@@ -37,7 +37,7 @@ cpup [_mode_] [_taskID_]
## 输出说明 ## 输出说明
**示例**:指令输出结果 **示例** 指令输出结果
``` ```
OHOS # cpup 1 5pid 5 OHOS # cpup 1 5pid 5
......
...@@ -19,10 +19,10 @@ date命令用于查询系统日期和时间。 ...@@ -19,10 +19,10 @@ date命令用于查询系统日期和时间。
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ------- | ------------------------------ | ---------------------- |
| --help | 使用帮助。 | N/A | | --help | 使用帮助。 | N/A |
| +Format | 根据Format格式打印日期和时间。 | --help中列出的占位符。 | | +Format | 根据Format格式打印日期和时间。 | --help中列出的占位符。 |
| -u | 显示UTC,而不是当前时区 | N/A | | -u | 显示UTC,而不是当前时区 | N/A |
...@@ -36,6 +36,9 @@ date命令用于查询系统日期和时间。 ...@@ -36,6 +36,9 @@ date命令用于查询系统日期和时间。
- 目前命令不支持设置时间和日期。 - 目前命令不支持设置时间和日期。
## 特殊说明
date -u参数 shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 命令功能 ## 命令功能
dmesg命令用于显示系统启动过程和运行过程中的信息。 dmesg命令用于显示开机信息,以及系统启动过程和运行过程中的信息。
## 命令格式 ## 命令格式
...@@ -21,22 +21,22 @@ dmesg &gt; [_fileA_] ...@@ -21,22 +21,22 @@ dmesg &gt; [_fileA_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | --------------- | ---------------------------------------- | --------------- |
| -c | 打印缓存区内容并清空缓存区。 | N/A | | -c | 打印缓存区内容并清空缓存区。 | N/A |
| -C | 清空缓存区。 | N/A | | -C | 清空缓存区。 | N/A |
| -D/-E | 关闭/开启控制台打印。 | N/A | | -D/-E | 关闭/开启控制台打印。 | N/A |
| -L/-U | 关闭/开启串口打印。 | N/A | | -L/-U | 关闭/开启串口打印。 | N/A |
| -s&nbsp;size | 设置缓存区大小&nbsp;size是要设置的大小。 | N/A | | -s&nbsp;size | 设置缓存区大小&nbsp;size是要设置的大小。 | N/A |
| -l&nbsp;level | 设置缓存等级。 | 0&nbsp;-&nbsp;5 | | -l&nbsp;level | 设置缓存等级。 | [0, 5] |
| &gt;&nbsp;fileA | 将缓存区内容重定向写入文件。 | N/A | | &gt;&nbsp;fileA | 将缓存区内容重定向写入文件。 | N/A |
## 使用指南 ## 使用指南
- 该命令依赖于LOSCFG_SHELL_DMESG,使用时通过menuconfig在配置项中开启"Enable Shell dmesg": - 该命令依赖于LOSCFG_SHELL_DMESG,在kernel/liteos_a中输入make menuconfig命令。此时会弹出配置项,找到Debug选项并进入,然后在配置项中开启"Enable Shell dmesg":
Debug ---&gt; Enable a Debug Version ---&gt; Enable Shell ---&gt; Enable Shell dmesg Debug ---&gt; Enable a Debug Version ---&gt; Enable Shell ---&gt; Enable Shell dmesg
- dmesg参数缺省时,默认打印缓存区内容。 - dmesg参数缺省时,默认打印缓存区内容。
...@@ -53,7 +53,7 @@ dmesg &gt; [_fileA_] ...@@ -53,7 +53,7 @@ dmesg &gt; [_fileA_]
## 输出说明 ## 输出说明
**示例**dmesg重定向到文件 **示例** dmesg重定向到文件
``` ```
OHOS # dmesg > dmesg.log OHOS # dmesg > dmesg.log
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 命令功能 ## 命令功能
exec命令属于shell内置命令,目前实现最基础的执行用户态程序的功能。 exec命令属于shell内置命令,在exec执行命令时,不启用新的shell进程。目前实现最基础的执行用户态程序的功能
## 命令格式 ## 命令格式
...@@ -13,11 +13,11 @@ exec &lt;_executable-file_&gt; ...@@ -13,11 +13,11 @@ exec &lt;_executable-file_&gt;
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | | --------------- | ------------------ |
| executable-file | 有效的可执行文件。 | N/A | | executable-file | 有效的可执行文件。 |
## 使用指南 ## 使用指南
......
...@@ -13,17 +13,17 @@ free [_-b | -k | -m | -g | -t_] ...@@ -13,17 +13,17 @@ free [_-b | -k | -m | -g | -t_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | | -------- | -------- |
| 无参数 | 以Byte为单位显示。 | N/A | | 无参数 | 以Byte为单位显示。 |
| --help/-h | 查看free命令支持的参数列表。 | N/A | | --help/-h | 查看free命令支持的参数列表。 |
| -b | 以Byte为单位显示。 | N/A | | -b | 以Byte为单位显示。 |
| -k | 以KiB为单位显示。 | N/A | | -k | 以KiB为单位显示。 |
| -m | 以MiB为单位显示。 | N/A | | -m | 以MiB为单位显示。 |
| -g | 以GiB为单位显示。 | N/A | | -g | 以GiB为单位显示。 |
| -t | 以TiB为单位显示。 | N/A | | -t | 以TiB为单位显示。 |
## 使用指南 ## 使用指南
...@@ -57,7 +57,7 @@ Mem: 2 2 0 0 0 ...@@ -57,7 +57,7 @@ Mem: 2 2 0 0 0
Swap: 0 0 0 Swap: 0 0 0
``` ```
**表2** 输出说明 **表2** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -13,7 +13,7 @@ help ...@@ -13,7 +13,7 @@ help
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
......
...@@ -13,7 +13,7 @@ hwi ...@@ -13,7 +13,7 @@ hwi
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
...@@ -106,7 +106,7 @@ hwi ...@@ -106,7 +106,7 @@ hwi
102: 0 0 0.0 0.0 0.0 normal SPI_HI35XX 102: 0 0 0.0 0.0 0.0 normal SPI_HI35XX
``` ```
**表1** 输出说明 **表1** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 命令功能 ## 命令功能
命令用于发送特定信号给指定进程 kill命令用于发送特定信号给指定进程,让它去终结不正常的应用
## 命令格式 ## 命令格式
...@@ -13,26 +13,29 @@ kill [-l [_signo_] | _-s signo_ | _-signo_] _pid..._ ...@@ -13,26 +13,29 @@ kill [-l [_signo_] | _-s signo_ | _-signo_] _pid..._
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ------ | -------------------------- | ----------- |
| --help | 查看kill命令支持的参数列表 | N/A | | --help | 查看kill命令支持的参数列表 | N/A |
| -l | 列出信号名称和编号。 | N/A | | -l | 列出信号名称和编号。 | N/A |
| -s | 发送信号 | N/A | | -s | 发送信号 | N/A |
| signo | 信号ID。 | [1,30] | | signo | 信号ID。 | [1, 30] |
| pid | 进程ID。 | [1,MAX_INT] | | pid | 进程ID。 | [1, MAX_INT] |
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:** > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:**
> signo有效范围为[0,64],建议取值范围为[1,30],其余为保留内容。 > signo有效范围为[0, 64],建议取值范围为[1, 30],其余为保留内容。
## 使用指南 ## 使用指南
- 必须指定发送的信号编号及进程号。 - 必须指定发送的信号编号及进程号。
- 进程编号取值范围根据系统配置变化,例如系统最大支持pid为256,则取值范围缩小为[1-256]。 - 进程编号取值范围根据系统配置变化,例如系统最大支持pid为256,则取值范围缩小为[1, 256]。
## 特殊说明
kill命令以及参数 shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -91,7 +94,7 @@ kill [-l [_signo_] | _-s signo_ | _-signo_] _pid..._ ...@@ -91,7 +94,7 @@ kill [-l [_signo_] | _-s signo_ | _-signo_] _pid..._
发送成功或失败输出结果如下。 发送成功或失败输出结果如下。
**示例 1** 发送信号给指定进程 **示例1** 发送信号给指定进程
``` ```
...@@ -102,7 +105,7 @@ OHOS:/$ ...@@ -102,7 +105,7 @@ OHOS:/$
信号发送成功会显示的提示进程已被杀死。 信号发送成功会显示的提示进程已被杀死。
**示例 2** 信号发送失败 **示例2** 信号发送失败
``` ```
......
...@@ -13,11 +13,11 @@ log level [_levelNum_] ...@@ -13,11 +13,11 @@ log level [_levelNum_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| levelNum | 配置日志打印等级。 | [0,5] | | levelNum | 配置日志打印等级。 | [0, 5] |
## 使用指南 ## 使用指南
...@@ -52,7 +52,7 @@ log level [_levelNum_] ...@@ -52,7 +52,7 @@ log level [_levelNum_]
## 输出说明 ## 输出说明
**示例**设置当前日志打印级别为3 **示例** 设置当前日志打印级别为3
``` ```
......
...@@ -13,7 +13,7 @@ memcheck ...@@ -13,7 +13,7 @@ memcheck
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
...@@ -34,14 +34,14 @@ memcheck ...@@ -34,14 +34,14 @@ memcheck
## 输出说明 ## 输出说明
**示例1**当前没有内存越界 **示例1** 当前没有内存越界
``` ```
OHOS # memcheck OHOS # memcheck
system memcheck over, all passed! system memcheck over, all passed!
``` ```
**示例2**出现内存越界 **示例2** 出现内存越界
``` ```
[L0S DLnkCheckMenl 349, memory check [L0S DLnkCheckMenl 349, memory check
......
...@@ -21,19 +21,20 @@ oom -h | --help ...@@ -21,19 +21,20 @@ oom -h | --help
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ----------------------- | ------------------------------- | ------------------------------------------------------------ |
| -i&nbsp;[interval] | 设置oom线程任务检查的时间间隔。 | 100ms&nbsp;~&nbsp;10000ms | | -i&nbsp;[interval] | 设置oom线程任务检查的时间间隔。 | [100, 10000] 单位: ms |
| -m&nbsp;[mem&nbsp;byte] | 设置低内存阈值。 | 0MB&nbsp;~&nbsp;1MB,0MB表示不做低内存阈值检查。 | | -m&nbsp;[mem&nbsp;byte] | 设置低内存阈值。 | 0MB&nbsp;~&nbsp;1MB,0MB表示不做低内存阈值检查。 |
| -r&nbsp;[mem&nbsp;byte] | 设置pagecache内存回收阈值。 | 低内存阈值&nbsp;~&nbsp;系统可用最大内存。 | | -r&nbsp;[mem&nbsp;byte] | 设置pagecache内存回收阈值。 | 低内存阈值 ~ 系统可用最大内存,一个pagecache页一般为4KB,也有16 ~ 64KB的情况。 |
| -h&nbsp;\|&nbsp;--help | 使用帮助。 | N/A | | -h&nbsp;\|&nbsp;--help | 使用帮助。 | N/A |
## 使用指南 ## 使用指南
参数缺省时,显示oom功能当前配置信息。 参数缺省时,显示oom功能当前配置信息。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 当系统内存不足时,会打印出内存不足的提示信息。 > 当系统内存不足时,会打印出内存不足的提示信息。
...@@ -49,7 +50,7 @@ oom -h | --help ...@@ -49,7 +50,7 @@ oom -h | --help
## 输出说明 ## 输出说明
**示例1:**oom缺省打印配置信息 **示例1** oom缺省打印配置信息
``` ```
...@@ -109,7 +110,7 @@ traceback 5 -- 1r = 0x20c4df50 fp = 0хb0b0b0b 1r in /1ib/libc.so - -> 0x62f50 ...@@ -109,7 +110,7 @@ traceback 5 -- 1r = 0x20c4df50 fp = 0хb0b0b0b 1r in /1ib/libc.so - -> 0x62f50
``` ```
**示例2**设置 oom 线程任务检查的时间间隔 **示例2** 设置 oom 线程任务检查的时间间隔
...@@ -119,10 +120,10 @@ OHOS:/$ oom -i 100 ...@@ -119,10 +120,10 @@ OHOS:/$ oom -i 100
``` ```
**表2** 输出说明 **表2** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [oom]&nbsp;OS&nbsp;is&nbsp;in&nbsp;low&nbsp;memory&nbsp;state<br/>total&nbsp;physical&nbsp;memory:&nbsp;0x1bcf000(byte),&nbsp;used:&nbsp;0x1b50000(byte),&nbsp;free:&nbsp;0x7f000(byte),&nbsp;low&nbsp;memory&nbsp;threshold:&nbsp;0x80000(byte) | 操作系统处于低内存状态。<br/>整个系统可用物理内存为0x1bcf000&nbsp;byte,已经使用了&nbsp;0x1b50000&nbsp;byte,&nbsp;还剩0x7f000&nbsp;byte,当前设置的低内存阈值为0x80000&nbsp;byte。 | | [oom]&nbsp;OS&nbsp;is&nbsp;in&nbsp;low&nbsp;memory&nbsp;state<br/>total&nbsp;physical&nbsp;memory:&nbsp;0x1bcf000(byte),&nbsp;used:&nbsp;0x1b50000(byte),&nbsp;free:&nbsp;0x7f000(byte),&nbsp;low&nbsp;memory&nbsp;threshold:&nbsp;0x80000(byte) | 操作系统处于低内存状态。<br/>整个系统可用物理内存为0x1bcf000&nbsp;byte,已经使用了&nbsp;0x1b50000&nbsp;byte,&nbsp;还剩0x7f000&nbsp;byte,当前设置的低内存阈值为0x80000&nbsp;byte。 |
| [oom]&nbsp;candidate&nbsp;victim&nbsp;process&nbsp;init&nbsp;pid:&nbsp;1,&nbsp;actual&nbsp;phy&nbsp;mem&nbsp;byte:&nbsp;82602 | 打印当前各个进程的内存使用情况,init进程实际占用物理内存82602byte。 | | [oom]&nbsp;candidate&nbsp;victim&nbsp;process&nbsp;init&nbsp;pid:&nbsp;1,&nbsp;actual&nbsp;phy&nbsp;mem&nbsp;byte:&nbsp;82602 | 打印当前各个进程的内存使用情况,init进程实际占用物理内存82602byte。 |
| [oom]&nbsp;candidate&nbsp;victim&nbsp;process&nbsp;UserProcess12&nbsp;pid:&nbsp;12,&nbsp;actual&nbsp;phy&nbsp;mem&nbsp;byte:&nbsp;25951558 | UserProcess12进程实际使用25951558byte内存。 | | [oom]&nbsp;candidate&nbsp;victim&nbsp;process&nbsp;UserProcess12&nbsp;pid:&nbsp;12,&nbsp;actual&nbsp;phy&nbsp;mem&nbsp;byte:&nbsp;25951558 | UserProcess12进程实际使用25951558byte内存。 |
......
...@@ -28,7 +28,7 @@ Debug版本才具备的命令。 ...@@ -28,7 +28,7 @@ Debug版本才具备的命令。
## 输出说明 ## 输出说明
**示例:**查看物理页使用情况 **示例** 查看物理页使用情况
``` ```
OHOS # pmm OHOS # pmm
...@@ -55,7 +55,7 @@ Vnode number = 67 ...@@ -55,7 +55,7 @@ Vnode number = 67
Vnode memory size = 10720(B) Vnode memory size = 10720(B)
``` ```
**表1** 输出说明 **表1** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -13,7 +13,7 @@ reboot ...@@ -13,7 +13,7 @@ reboot
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
...@@ -28,4 +28,4 @@ reboot ...@@ -28,4 +28,4 @@ reboot
## 输出说明 ## 输出说明
...@@ -13,7 +13,7 @@ reset ...@@ -13,7 +13,7 @@ reset
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
...@@ -28,4 +28,4 @@ reset ...@@ -28,4 +28,4 @@ reset
## 输出说明 ## 输出说明
...@@ -13,7 +13,7 @@ sem [_ID__ / fulldata_] ...@@ -13,7 +13,7 @@ sem [_ID__ / fulldata_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -40,7 +40,7 @@ sem [_ID__ / fulldata_] ...@@ -40,7 +40,7 @@ sem [_ID__ / fulldata_]
## 输出说明 ## 输出说明
**示例1**查询所有在用的信号量信息 **示例1** 查询所有在用的信号量信息
``` ```
OHOS # sem OHOS # sem
...@@ -67,7 +67,7 @@ OHOS # sem ...@@ -67,7 +67,7 @@ OHOS # sem
0x00000006 0 0x00000006 0
``` ```
**表2** 输出说明 **表2** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
...@@ -79,7 +79,7 @@ OHOS # sem ...@@ -79,7 +79,7 @@ OHOS # sem
> >
> ● sem命令的ID参数在[0, 1023]范围内时,返回对应ID的信号量的状态(如果对应ID的信号量未被使用则进行提示);其他取值时返回参数错误的提示。 > ● sem命令的ID参数在[0, 1023]范围内时,返回对应ID的信号量的状态(如果对应ID的信号量未被使用则进行提示);其他取值时返回参数错误的提示。
**示例2:**查询所有在用的信号量信息 **示例2** 查询所有在用的信号量信息
``` ```
OHOS # sem fulldata OHOS # sem fulldata
...@@ -113,7 +113,7 @@ Used Semaphore List: ...@@ -113,7 +113,7 @@ Used Semaphore List:
0x38 0x1 0x1 0x404978fc 0x395 0x38 0x1 0x1 0x404978fc 0x395
``` ```
**表3** 输出说明 **表3** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -13,12 +13,12 @@ stack ...@@ -13,12 +13,12 @@ stack
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
## 使用实例 ## 使用实例
...@@ -28,7 +28,7 @@ stack ...@@ -28,7 +28,7 @@ stack
## 输出说明 ## 输出说明
**示例:**系统堆栈使用情况 **示例** 系统堆栈使用情况
``` ```
OHOS # stack OHOS # stack
...@@ -40,7 +40,7 @@ OHOS # stack ...@@ -40,7 +40,7 @@ OHOS # stack
exc_stack 0 0x405c9000 0x1000 0x0 exc_stack 0 0x405c9000 0x1000 0x0
``` ```
**表1** 输出说明 **表1** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -13,12 +13,12 @@ su [_uid_] [_gid_] ...@@ -13,12 +13,12 @@ su [_uid_] [_gid_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| uid | 目标用户的用户id值。 | -&nbsp;为空。<br/>-&nbsp;[0,60000] | | uid | 目标用户的用户id值。 | -&nbsp;为空。<br/>-&nbsp;[0, 60000] |
| gid | 目标用户的群组id值。 | -&nbsp;为空。<br/>-&nbsp;[0,60000] | | gid | 目标用户的群组id值。 | -&nbsp;为空。<br/>-&nbsp;[0, 60000] |
## 使用指南 ## 使用指南
...@@ -37,7 +37,7 @@ su [_uid_] [_gid_] ...@@ -37,7 +37,7 @@ su [_uid_] [_gid_]
## 输出说明 ## 输出说明
**示例:**切换到为uid为1000,gid为1000的用户 **示例** 切换到为uid为1000,gid为1000的用户
``` ```
OHOS # ls OHOS # ls
......
...@@ -13,11 +13,11 @@ swtmr [_ID_] ...@@ -13,11 +13,11 @@ swtmr [_ID_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ID | 软件定时器ID号。 | [0,0xFFFFFFFF] | | ID | 软件定时器ID号。 | [0, 0xFFFFFFFF] |
## 使用指南 ## 使用指南
...@@ -38,7 +38,7 @@ swtmr [_ID_] ...@@ -38,7 +38,7 @@ swtmr [_ID_]
## 输出说明 ## 输出说明
**示例1:**查询所有软件定时器相关信息 **示例1** 查询所有软件定时器相关信息
``` ```
OHOS # swtmr OHOS # swtmr
...@@ -59,7 +59,7 @@ SwTmrID State Mode Interval Count Arg handlerAddr ...@@ -59,7 +59,7 @@ SwTmrID State Mode Interval Count Arg handlerAddr
0x00000079 Ticking NSD 30000 1749 0x406189d8 0x40160e1c 0x00000079 Ticking NSD 30000 1749 0x406189d8 0x40160e1c
``` ```
**示例2:**查询对应 ID 的软件定时器信息 **示例2** 查询对应 ID 的软件定时器信息
``` ```
OHOS # swtmr 1 OHOS # swtmr 1
......
...@@ -13,12 +13,12 @@ systeminfo ...@@ -13,12 +13,12 @@ systeminfo
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
## 使用实例 ## 使用实例
...@@ -28,7 +28,7 @@ systeminfo ...@@ -28,7 +28,7 @@ systeminfo
## 输出说明 ## 输出说明
**示例:**查看系统资源使用情况 **示例** 查看系统资源使用情况
``` ```
OHOS:/$ systeminfo OHOS:/$ systeminfo
...@@ -40,16 +40,15 @@ OHOS:/$ systeminfo ...@@ -40,16 +40,15 @@ OHOS:/$ systeminfo
SwTmr 20 1024 YES SwTmr 20 1024 YES
``` ```
**表1** 输出说明 **表1** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | ------- | -------------- |
| Module | 模块名称。 | | Module | 模块名称。 |
| Used | 当前使用量。 | | Used | 当前使用量。 |
| Total | 最大可用量。 | | Total | 最大可用量。 |
| Enabled | 模块是否开启。 | | Enabled | 模块是否开启。 |
| Task | 任务。 | | Task | 任务。 |
| Sem | 信号量。 | | Sem | 信号量。 |
| Mutex | 互斥量。 |
| Queue | 队列。 | | Queue | 队列。 |
| SwTmr | 定时器。 | | SwTmr | 定时器。 |
\ No newline at end of file
...@@ -13,7 +13,7 @@ task/task -a ...@@ -13,7 +13,7 @@ task/task -a
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -32,8 +32,7 @@ task/task -a ...@@ -32,8 +32,7 @@ task/task -a
## 输出说明 ## 输出说明
**示例:**查询任务部分信息 **示例** 查询任务部分信息
``` ```
OHOS # task OHOS # task
...@@ -61,7 +60,7 @@ OHOS # task ...@@ -61,7 +60,7 @@ OHOS # task
7 2 0x3 -1 Pending 0x4e20 0xa5c 0.0 0 PlatformWorkerThread 7 2 0x3 -1 Pending 0x4e20 0xa5c 0.0 0 PlatformWorkerThread
``` ```
**表2** 输出说明 **表2** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -13,18 +13,21 @@ top [_-a_] ...@@ -13,18 +13,21 @@ top [_-a_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 缺省值 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | -------- | | ------ | --------------------------- |
| --help | 查看top命令支持的参数列表。 | N/A | | | --help | 查看top命令支持的参数列表。 |
| -a | 显示更详细的信息。 | N/A | | | -a | 显示更详细的信息。 |
## 使用指南 ## 使用指南
参数缺省时默认打印部分任务信息。 参数缺省时默认打印部分任务信息。
## 特殊说明
shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -33,7 +36,7 @@ top [_-a_] ...@@ -33,7 +36,7 @@ top [_-a_]
## 输出说明 ## 输出说明
**示例1** top 命令显示详情 **示例1** top 命令显示详情
``` ```
OHOS:/$ top OHOS:/$ top
...@@ -78,10 +81,10 @@ OHOS:/$ top ...@@ -78,10 +81,10 @@ OHOS:/$ top
64 2 0x3 -1 Pending 0x4000 0x244 0.0 0 USB_NGIAN_BULK_TasK 64 2 0x3 -1 Pending 0x4000 0x244 0.0 0 USB_NGIAN_BULK_TasK
``` ```
**表2** 输出元素说明 **表2** 输出元素说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | --------- | ----------------- |
| PID | 进程ID。 | | PID | 进程ID。 |
| PPID | 父进程ID。 | | PPID | 父进程ID。 |
| PGID | 进程组ID。 | | PGID | 进程组ID。 |
......
...@@ -11,10 +11,10 @@ uname命令用于显示当前操作系统的名称,版本创建时间,系统 ...@@ -11,10 +11,10 @@ uname命令用于显示当前操作系统的名称,版本创建时间,系统
uname [_-a | -s | -r | -m | -n | -v | --help_] uname [_-a | -s | -r | -m | -n | -v | --help_]
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | | 参数 | 参数说明 |
| -------- | -------- | | ------ | ----------------------- |
| --help | 显示uname指令格式提示。 | | --help | 显示uname指令格式提示。 |
| 无参数 | 默认显示操作系统名称。 | | 无参数 | 默认显示操作系统名称。 |
| -a | 显示全部信息。 | | -a | 显示全部信息。 |
...@@ -31,6 +31,9 @@ uname [_-a | -s | -r | -m | -n | -v | --help_] ...@@ -31,6 +31,9 @@ uname [_-a | -s | -r | -m | -n | -v | --help_]
- 除参数--help和-a以外,其他参数可以相互搭配使用;uname -a 等价于 uname -srmnv。 - 除参数--help和-a以外,其他参数可以相互搭配使用;uname -a 等价于 uname -srmnv。
## 特殊说明
-r -m -n参数暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -43,8 +46,7 @@ uname [_-a | -s | -r | -m | -n | -v | --help_] ...@@ -43,8 +46,7 @@ uname [_-a | -s | -r | -m | -n | -v | --help_]
## 输出说明 ## 输出说明
**示例1:** 查看系统信息 **示例1** 查看系统信息
``` ```
OHOS:/$ uname -a OHOS:/$ uname -a
...@@ -52,8 +54,7 @@ LiteOS hisilicon 2.0.0.37 LiteOS 2.0.0.37 Oct 21 2021 17:39:32 Cortex-A7 ...@@ -52,8 +54,7 @@ LiteOS hisilicon 2.0.0.37 LiteOS 2.0.0.37 Oct 21 2021 17:39:32 Cortex-A7
OHOS:/$ OHOS:/$
``` ```
**示例2:** 只查看操作系统名称和系统架构名称 **示例2** 只查看操作系统名称和系统架构名称
``` ```
OHOS:/$ uname -ms OHOS:/$ uname -ms
......
...@@ -15,13 +15,13 @@ ...@@ -15,13 +15,13 @@
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| -a | 输出所有进程的虚拟内存使用情况。 | N/A | | -a | 输出所有进程的虚拟内存使用情况。 | N/A |
| -h&nbsp;\|&nbsp;--help | 命令格式说明。 | N/A | | -h&nbsp;\|&nbsp;--help | 命令格式说明。 | N/A |
| pid | 进程ID,说明指定进程的虚拟内存使用情况。 | [0,63] | | pid | 进程ID,说明指定进程的虚拟内存使用情况。 | [0, 63] |
## 使用指南 ## 使用指南
...@@ -36,7 +36,7 @@ ...@@ -36,7 +36,7 @@
## 输出说明 ## 输出说明
**示例:**PID为3的进程虚拟内存使用信息 **示例** PID为3的进程虚拟内存使用信息
``` ```
OHOS # vmm 3 OHOS # vmm 3
...@@ -62,7 +62,7 @@ OHOS # vmm 3 ...@@ -62,7 +62,7 @@ OHOS # vmm 3
0x408c3ce0 /lib/libc++.so 0x23cb0000 0x00001000 CH US RD WR 1 1 0x408c3ce0 /lib/libc++.so 0x23cb0000 0x00001000 CH US RD WR 1 1
``` ```
**表2** 进程基本信息 **表2** 进程基本信息
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
...@@ -73,7 +73,7 @@ OHOS # vmm 3 ...@@ -73,7 +73,7 @@ OHOS # vmm 3
| size | 虚拟内存大小 | | size | 虚拟内存大小 |
| pages | 已使用的物理页数量 | | pages | 已使用的物理页数量 |
**表3** 虚拟内存区间信息 **表3** 虚拟内存区间信息
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -38,7 +38,7 @@ watch -n 2 -c 6 task ...@@ -38,7 +38,7 @@ watch -n 2 -c 6 task
## 输出说明 ## 输出说明
**示例**每隔2秒运行一次task命令,一共运行6次 **示例** 每隔2秒运行一次task命令,一共运行6次
``` ```
OHOS # watch -n 2 -c 6 task OHOS # watch -n 2 -c 6 task
......
...@@ -13,7 +13,7 @@ cat [_pathname_] ...@@ -13,7 +13,7 @@ cat [_pathname_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -32,7 +32,7 @@ cat用于显示文本文件的内容。 ...@@ -32,7 +32,7 @@ cat用于显示文本文件的内容。
## 输出说明 ## 输出说明
**示例**查看 hello-openharmony.txt 文件的信息 **示例** 查看 hello-openharmony.txt 文件的信息
``` ```
OHOS # cat hello-openharmony.txt OHOS # cat hello-openharmony.txt
......
...@@ -13,7 +13,7 @@ cd [_path_] ...@@ -13,7 +13,7 @@ cd [_path_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -42,8 +42,7 @@ cd [_path_] ...@@ -42,8 +42,7 @@ cd [_path_]
## 输出说明 ## 输出说明
**示例**:显示结果如下 **示例**显示结果如下
``` ```
OHOS:/nfs$ cd ../ OHOS:/nfs$ cd ../
......
...@@ -13,20 +13,22 @@ chgrp [_group_] [_pathname_] ...@@ -13,20 +13,22 @@ chgrp [_group_] [_pathname_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | ---------- | -------------- |
| group | 文件群组。 | [0,0xFFFFFFFF] | | group | 文件群组。 | [0, 0xFFFFFFFF] |
| pathname | 文件路径。 | 已存在的文件。 | | pathname | 文件路径。 | 已存在的文件。 |
## 使用指南 ## 使用指南
- 在需要修改的文件名前加上文件群组值就可以修改该文件的所属组。 - 在需要修改的文件名前加上文件群组值就可以修改该文件的所属组。
- fatfs文件系统不支持修改用户组id。 - fatfs文件系统不支持修改用户组id。
## 特殊说明
shell端暂不支持。
## 使用实例 ## 使用实例
...@@ -35,7 +37,7 @@ chgrp [_group_] [_pathname_] ...@@ -35,7 +37,7 @@ chgrp [_group_] [_pathname_]
## 输出说明 ## 输出说明
**示例:**修改 dev/目录下testfile 文件的群组为100 **示例** 修改 dev/目录下testfile 文件的群组为100
``` ```
OHOS:/dev$ ll testfile OHOS:/dev$ ll testfile
......
...@@ -13,11 +13,11 @@ chmod [_mode_] [_filename_] ...@@ -13,11 +13,11 @@ chmod [_mode_] [_filename_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | ------------------------------------------------------------ | -------------- |
| mode | 文件或文件夹权限,用8进制表示对应User、Group、及Others(拥有者、群组、其他组)的权限。 | [0,777] | | mode | 文件或文件夹权限,用8进制表示对应User、Group、及Others(拥有者、群组、其他组)的权限。 | [0, 777] |
| filename | 文件路径。 | 已存在的文件。 | | filename | 文件路径。 | 已存在的文件。 |
...@@ -27,6 +27,9 @@ chmod [_mode_] [_filename_] ...@@ -27,6 +27,9 @@ chmod [_mode_] [_filename_]
- fatfs文件系统所有创建的文件和挂载节点的权限属性保持一致,目前节点的权限只有用户读写权限,group和others权限不生效;且只允许修改用户读写权限,读写权限只有rw和ro两种。其他文件系统无限制。 - fatfs文件系统所有创建的文件和挂载节点的权限属性保持一致,目前节点的权限只有用户读写权限,group和others权限不生效;且只允许修改用户读写权限,读写权限只有rw和ro两种。其他文件系统无限制。
## 特殊说明
shell端暂不支持。
## 使用实例 ## 使用实例
...@@ -35,8 +38,7 @@ chmod [_mode_] [_filename_] ...@@ -35,8 +38,7 @@ chmod [_mode_] [_filename_]
## 输出说明 ## 输出说明
**示例:**修改/dev目录下 hello-openharmony.txt 文件的权限 **示例** 修改/dev目录下 hello-openharmony.txt 文件的权限
``` ```
OHOS:/dev$ chmod 644 hello-openharmony.txt OHOS:/dev$ chmod 644 hello-openharmony.txt
......
...@@ -13,11 +13,11 @@ chown [_owner_] [_pathname_] ...@@ -13,11 +13,11 @@ chown [_owner_] [_pathname_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | ------------ | -------------- |
| owner | 文件拥有者。 | [0,0xFFFFFFFF] | | owner | 文件拥有者。 | [0, 0xFFFFFFFF] |
| pathname | 文件路径。 | 已存在的文件。 | | pathname | 文件路径。 | 已存在的文件。 |
...@@ -25,6 +25,9 @@ chown [_owner_] [_pathname_] ...@@ -25,6 +25,9 @@ chown [_owner_] [_pathname_]
修改文件的所有者,目前fatfs不支持修改。 修改文件的所有者,目前fatfs不支持修改。
## 特殊说明
shell端暂不支持。
## 使用实例 ## 使用实例
...@@ -33,8 +36,7 @@ chown [_owner_] [_pathname_] ...@@ -33,8 +36,7 @@ chown [_owner_] [_pathname_]
## 输出说明 ## 输出说明
示例 1 修改 /dev下的testfile 文件的uid为100 **示例1** 修改 /dev下的testfile 文件的uid为100
``` ```
OHOS:/dev$ touch testfile OHOS:/dev$ touch testfile
......
...@@ -47,8 +47,7 @@ cp [_SOURCEFILE_] [_DESTFILE_] ...@@ -47,8 +47,7 @@ cp [_SOURCEFILE_] [_DESTFILE_]
## 输出说明 ## 输出说明
**示例:**同时拷贝两个文件至指定目录 **示例** 同时拷贝两个文件至指定目录
``` ```
OHOS:/$ ls OHOS:/$ ls
......
...@@ -13,16 +13,16 @@ du [_-kKmh_] [_file..._] ...@@ -13,16 +13,16 @@ du [_-kKmh_] [_file..._]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | | ------ | ------------------------------------------------------------ |
| --help | 查看du命令支持的参数列表。 | N/A | | --help | 查看du命令支持的参数列表。 |
| -k | 显示占用的块,每块1024bytes(默认)。 | N/A | | -k | 显示占用的块,每块1024bytes(默认)。 |
| -K | 显示占用的块,每块512bytes(posix标准)。 | N/A | | -K | 显示占用的块,每块512bytes(posix标准)。 |
| -m | 兆字节为单位。 | N/A | | -m | 兆字节为单位。 |
| -h | 以K,M,G为单位,提高信息的可读性(例如,1K&nbsp;243M&nbsp;2G)。 | N/A | | -h | 以K,M,G为单位,提高信息的可读性(例如,1K&nbsp;243M&nbsp;2G)。 |
| file | 指定的需要统计的文件。 | N/A | | file | 指定的需要统计的文件。 |
## 使用指南 ## 使用指南
...@@ -31,6 +31,9 @@ du [_-kKmh_] [_file..._] ...@@ -31,6 +31,9 @@ du [_-kKmh_] [_file..._]
- file的内容既为文件名,不能包含其所在的目录。 - file的内容既为文件名,不能包含其所在的目录。
## 特殊说明
shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -39,8 +42,7 @@ du [_-kKmh_] [_file..._] ...@@ -39,8 +42,7 @@ du [_-kKmh_] [_file..._]
## 输出说明 ## 输出说明
**示例:**显示结果如下 **示例** 显示结果如下
``` ```
OHOS:/$ du -h testfile OHOS:/$ du -h testfile
......
...@@ -13,7 +13,7 @@ format &lt;_dev_inodename_&gt; &lt;_sectors_&gt; &lt;_option_&gt; [_label_] ...@@ -13,7 +13,7 @@ format &lt;_dev_inodename_&gt; &lt;_sectors_&gt; &lt;_option_&gt; [_label_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | | 参数 | 参数说明 |
| -------- | -------- | | -------- | -------- |
...@@ -39,8 +39,7 @@ format &lt;_dev_inodename_&gt; &lt;_sectors_&gt; &lt;_option_&gt; [_label_] ...@@ -39,8 +39,7 @@ format &lt;_dev_inodename_&gt; &lt;_sectors_&gt; &lt;_option_&gt; [_label_]
## 输出说明 ## 输出说明
**示例**:格式化mmc卡 **示例** 格式化mmc卡
``` ```
OHOS # format /dev/mmcblk1 128 2 OHOS # format /dev/mmcblk1 128 2
......
...@@ -16,10 +16,10 @@ ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._] ...@@ -16,10 +16,10 @@ ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._]
## 参数说明 ## 参数说明
**表1** 展示功能参数说明 **表1** 展示功能参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ------ | ------------------------------------------------------------ | ----------------------------- |
| --help | 查看ls命令支持的参数列表,使用方式。 | N/A | | --help | 查看ls命令支持的参数列表,使用方式。 | N/A |
| -a | 显示所有文件包括.hidden隐藏类型的文件。 | N/A | | -a | 显示所有文件包括.hidden隐藏类型的文件。 | N/A |
| -b | 转义非图形字符。 | N/A | | -b | 转义非图形字符。 | N/A |
...@@ -36,38 +36,46 @@ ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._] ...@@ -36,38 +36,46 @@ ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._]
| -Z | 安全上下文。 | N/A | | -Z | 安全上下文。 | N/A |
| path | path为空时,显示当前目录的内容。<br/>path为无效文件名时,显示失败,提示:<br/>ls&nbsp;error:&nbsp;No&nbsp;such&nbsp;directory。<br/>path为有效目录路径时,会显示对应目录下的内容。 | 1.为空。<br/>2.有效的目录路径 | | path | path为空时,显示当前目录的内容。<br/>path为无效文件名时,显示失败,提示:<br/>ls&nbsp;error:&nbsp;No&nbsp;such&nbsp;directory。<br/>path为有效目录路径时,会显示对应目录下的内容。 | 1.为空。<br/>2.有效的目录路径 |
**表2** 输出格式参数说明 **表2** 输出格式参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | | ------- | --------------------------------------- |
| -1 | 每行列出一个文件。 | N/A | | -1 | 每行列出一个文件。 |
| -c | 列,垂直排序。 | N/A | | -c | 列,垂直排序。 |
| -g | 类似于&nbsp;-l&nbsp;但没有所有者。 | N/A | | -g | 类似于&nbsp;-l&nbsp;但没有所有者。 |
| -h | 统计path目录下文件的总大小,单位为KiB。 | N/A | | -h | 统计path目录下文件的总大小,单位为KiB。 |
| -l | 详细的显示path目录下文件的信息。 | N/A | | -l | 详细的显示path目录下文件的信息。 |
| -m | 文件之间添加逗号。 | N/A | | -m | 文件之间添加逗号。 |
| -n | 类似&nbsp;-l&nbsp;数字格式显示uid/gid。 | N/A | | -n | 类似&nbsp;-l&nbsp;数字格式显示uid/gid。 |
| -o | 类似&nbsp;-l&nbsp;但显示列表不包括组。 | N/A | | -o | 类似&nbsp;-l&nbsp;但显示列表不包括组。 |
| -x | 列,水平排序。 | N/A | | -x | 列,水平排序。 |
| -ll | 文件的时间属性显示纳秒。 | N/A | | -ll | 文件的时间属性显示纳秒。 |
| --color | 彩色打印。 | 默认配置为:device=yellow&nbsp;symlink=turquoise/red&nbsp;dir=blue&nbsp;socket=purple&nbsp;files:&nbsp;exe=green&nbsp;suid=red&nbsp;suidfile=redback&nbsp;stickydir=greenback=auto&nbsp;means&nbsp;detect&nbsp;if&nbsp;output&nbsp;is&nbsp;a&nbsp;tty. |
**表3** 排序参数说明(默认为按首字母排序)
| 参数 | 参数说明 | 取值范围 | **表3** 排序参数说明(默认为按首字母排序)
| -------- | -------- | -------- |
| -f | 不排序。 | N/A | | 参数 | 参数说明 |
| -r | 按首字母反向排序。 | N/A | | ---- | ------------------------------------------ |
| -t | 按文件的最后修改时间排序,最近时间为排头。 | N/A | | -f | 不排序。 |
| -S | 按文件大小来排序,大文件为排头。 | N/A | | -r | 按首字母反向排序。 |
| -t | 按文件的最后修改时间排序,最近时间为排头。 |
| -S | 按文件大小来排序,大文件为排头。 |
**表4** 彩色打印
| 参数 | 默认配置 |
| ---- | ------------------------------------------ |
| --color | device=yellow symlink=turquoise/red dir=blue socket=purple files: exe=green suid=red suidfile=redback stickydir=greenback=auto means detect if output is a tty. |
## 使用指南 ## 使用指南
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:**
> **须知:**
> fatfs的文件节点信息继承其父节点,父节点号为0。故在hi3516dv300开发板上ls -i显示的文件节点号全为0。 > fatfs的文件节点信息继承其父节点,父节点号为0。故在hi3516dv300开发板上ls -i显示的文件节点号全为0。
## 特殊说明
ls中参数shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -80,8 +88,7 @@ ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._] ...@@ -80,8 +88,7 @@ ls [_-ACHLSZacdfhiklmnopqrstux1_] [_--color_[_=auto_]] [_directory..._]
## 输出说明 ## 输出说明
**示例1:**ls命令查看当前路径下的内容 **示例1** ls命令查看当前路径下的内容
``` ```
OHOS:/$ ls OHOS:/$ ls
...@@ -89,8 +96,7 @@ bin etc nfs sdcard system usr ...@@ -89,8 +96,7 @@ bin etc nfs sdcard system usr
dev lib proc storage userdata vendor dev lib proc storage userdata vendor
``` ```
**示例2:**ll命令查看当前路径下的内容 **示例2** ll命令查看当前路径下的内容
``` ```
OHOS:/$ ll OHOS:/$ ll
......
...@@ -23,8 +23,7 @@ lsfd命令显示当前已经打开文件的fd号以及文件的名字。 ...@@ -23,8 +23,7 @@ lsfd命令显示当前已经打开文件的fd号以及文件的名字。
## 输出说明 ## 输出说明
**示例:**lsfd输出说明 **示例** lsfd输出说明
``` ```
OHOS # lsfd OHOS # lsfd
......
...@@ -13,24 +13,27 @@ mkdir [_-vp_] [_-m mode_] [_dirname..._] ...@@ -13,24 +13,27 @@ mkdir [_-vp_] [_-m mode_] [_dirname..._]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | | --------- | ------------------------------ |
| --help | 查看mkdir命令支持的参数列表 | N/A | | --help | 查看mkdir命令支持的参数列表 |
| -m | 设置即将创建目录的权限。 | N/A | | -m | 设置即将创建目录的权限。 |
| -p | 递归逐级创建父子目录。 | N/A | | -p | 递归逐级创建父子目录。 |
| -v | 打印创建目录过程中的详细信息。 | N/A | | -v | 打印创建目录过程中的详细信息。 |
| directory | 需要创建的目录。 | N/A | | directory | 需要创建的目录。 |
## 使用指南 ## 使用指南
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:** > **须知:**
> fatfs文件系统所有创建的文件和其挂载节点的权限属性保持一致,目前节点的权限只有用户读写权限,group和others权限不生效, > fatfs文件系统所有创建的文件和其挂载节点的权限属性保持一致,目前节点的权限只有用户读写权限,group和others权限不生效,
> >
> 且只有读写位可设置,有rw和ro两种,因此mkdir在附加-m参数时,创建的目录权限仅有777和555两种,可执行权限也不生效。 > 且只有读写位可设置,有rw和ro两种,因此mkdir在附加-m参数时,创建的目录权限仅有777和555两种,可执行权限也不生效。
## 特殊说明
shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -53,7 +56,7 @@ total 2 ...@@ -53,7 +56,7 @@ total 2
drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath/ drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath/
``` ```
示例 2 创建指定mode的目录 **示例2** 创建指定mode的目录
``` ```
...@@ -63,7 +66,7 @@ total 2 ...@@ -63,7 +66,7 @@ total 2
drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath/ drwxrwxrwx 1 0 0 2048 1979-12-31 00:00 testpath/
``` ```
示例 3 逐级创建目录 **示例3** 逐级创建目录
``` ```
......
...@@ -13,10 +13,10 @@ mount [_-f_] [_-t TYPE_] [_-o OPTION,_] [[_DEVICE_] _DIR_] ...@@ -13,10 +13,10 @@ mount [_-f_] [_-t TYPE_] [_-o OPTION,_] [[_DEVICE_] _DIR_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ------ | ----------------------------------------------------------- | ------------------------------------------------------------ |
| --help | 查看mount命令支持的参数列表。 | N/A | | --help | 查看mount命令支持的参数列表。 | N/A |
| -f | 佯装挂载动作(实际不做挂载)。 | N/A | | -f | 佯装挂载动作(实际不做挂载)。 | N/A |
| -t | 文件系统的种类。 | TYPE:vfat,&nbsp;yaffs,&nbsp;jffs,&nbsp;ramfs,&nbsp;nfs,procfs,&nbsp;romfs. | | -t | 文件系统的种类。 | TYPE:vfat,&nbsp;yaffs,&nbsp;jffs,&nbsp;ramfs,&nbsp;nfs,procfs,&nbsp;romfs. |
...@@ -29,6 +29,9 @@ mount [_-f_] [_-t TYPE_] [_-o OPTION,_] [[_DEVICE_] _DIR_] ...@@ -29,6 +29,9 @@ mount [_-f_] [_-t TYPE_] [_-o OPTION,_] [[_DEVICE_] _DIR_]
mount后加需要挂载的设备信息、指定目录以及设备文件格式,就能成功挂载文件系统到指定目录。 mount后加需要挂载的设备信息、指定目录以及设备文件格式,就能成功挂载文件系统到指定目录。
## 特殊说明
shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -37,7 +40,7 @@ mount后加需要挂载的设备信息、指定目录以及设备文件格式, ...@@ -37,7 +40,7 @@ mount后加需要挂载的设备信息、指定目录以及设备文件格式,
## 输出说明 ## 输出说明
**示例:**将服务器端nfs目录192.168.1.3:/nfs挂载到当前系统下新建的/nfs目录: **示例** 将服务器端nfs目录192.168.1.3:/nfs挂载到当前系统下新建的/nfs目录:
``` ```
......
...@@ -13,10 +13,10 @@ mv [_-fivn_] _SOURCE... DEST_ ...@@ -13,10 +13,10 @@ mv [_-fivn_] _SOURCE... DEST_
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ------ | ------------------------------------------------------------ | ----------------------------------------------- |
| -help | 使用帮助。 | N/A | | -help | 使用帮助。 | N/A |
| -f | 通过删除目标文件强制复制。 | N/A | | -f | 通过删除目标文件强制复制。 | N/A |
| -i | 若指定移动的源目录或文件与目标中目录或文件同名,则会先询问是否覆盖旧文件,输入&nbsp;y&nbsp;直接覆盖,输入&nbsp;n&nbsp;取消该操作。 | N/A | | -i | 若指定移动的源目录或文件与目标中目录或文件同名,则会先询问是否覆盖旧文件,输入&nbsp;y&nbsp;直接覆盖,输入&nbsp;n&nbsp;取消该操作。 | N/A |
...@@ -28,7 +28,7 @@ mv [_-fivn_] _SOURCE... DEST_ ...@@ -28,7 +28,7 @@ mv [_-fivn_] _SOURCE... DEST_
## 使用指南 ## 使用指南
- 源文件路径支持“\*”和“?”通配符,“\*”代表任意多个字符,“?”代表任意单个字符。目的路径不支持通配符。当源路径可匹配多个文件时,目的路径必须为目录。 - 源文件路径支持“\*”和“?”通配符,“\*”代表任意多个字符,“?”代表任意单个字符。目的路径不支持通配符。当源路径可匹配多个文件时,目的路径必须为目录。
- 目的路径为目录时,该目录必须存在。此时目的文件以源文件命名。 - 目的路径为目录时,该目录必须存在。此时目的文件以源文件命名。
...@@ -36,6 +36,9 @@ mv [_-fivn_] _SOURCE... DEST_ ...@@ -36,6 +36,9 @@ mv [_-fivn_] _SOURCE... DEST_
- 目的文件已存在则会覆盖。 - 目的文件已存在则会覆盖。
## 特殊说明
shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -48,7 +51,7 @@ mv [_-fivn_] _SOURCE... DEST_ ...@@ -48,7 +51,7 @@ mv [_-fivn_] _SOURCE... DEST_
## 输出说明 ## 输出说明
**示例 1** 显示结果如下 **示例1** 显示结果如下
``` ```
...@@ -71,7 +74,7 @@ bin etc proc storage test.txt userdata vendor ...@@ -71,7 +74,7 @@ bin etc proc storage test.txt userdata vendor
dev lib sdcard system testpath usr dev lib sdcard system testpath usr
``` ```
**示例 2** 通配符使用 **示例2** 通配符使用
``` ```
......
...@@ -32,7 +32,7 @@ partinfo &lt;_dev_inodename_&gt; ...@@ -32,7 +32,7 @@ partinfo &lt;_dev_inodename_&gt;
## 输出说明 ## 输出说明
**示例**:查看系统分区信息 **示例** 查看系统分区信息
``` ```
......
...@@ -13,7 +13,7 @@ pwd ...@@ -13,7 +13,7 @@ pwd
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
...@@ -28,7 +28,7 @@ pwd 命令将当前目录的全路径名称(从根目录)写入标准输出 ...@@ -28,7 +28,7 @@ pwd 命令将当前目录的全路径名称(从根目录)写入标准输出
## 输出说明 ## 输出说明
**示例**查看当前路径 **示例** 查看当前路径
``` ```
......
...@@ -13,14 +13,14 @@ rm [_-fv_] _FILE or rm_ [_-rv_] [_PATH_ | _filename_]... ...@@ -13,14 +13,14 @@ rm [_-fv_] _FILE or rm_ [_-rv_] [_PATH_ | _filename_]...
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | | ------------- | ------------------------------------------------ |
| -r | 删除空目录或非空目录。 | N/A | | -r | 删除空目录或非空目录。 |
| -f | 强制删除:不需要确认,删除不存的文件在也不报错。 | N/A | | -f | 强制删除:不需要确认,删除不存的文件在也不报错。 |
| -v | 显示删除的过程。 | N/A | | -v | 显示删除的过程。 |
| PATH/filename | 要删除文件或文件夹的名称,支持输入路径。 | N/A | | PATH/filename | 要删除文件或文件夹的名称,支持输入路径。 |
## 使用指南 ## 使用指南
...@@ -31,6 +31,9 @@ rm [_-fv_] _FILE or rm_ [_-rv_] [_PATH_ | _filename_]... ...@@ -31,6 +31,9 @@ rm [_-fv_] _FILE or rm_ [_-rv_] [_PATH_ | _filename_]...
- 删除不存在的文件会报错。 - 删除不存在的文件会报错。
## 特殊说明
-f -v 参数shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -43,7 +46,7 @@ rm [_-fv_] _FILE or rm_ [_-rv_] [_PATH_ | _filename_]... ...@@ -43,7 +46,7 @@ rm [_-fv_] _FILE or rm_ [_-rv_] [_PATH_ | _filename_]...
## 输出说明 ## 输出说明
**示例 1** 用 rm 命令删除文件 testfile **示例1** 用 rm 命令删除文件 testfile
``` ```
...@@ -56,7 +59,7 @@ bin etc proc storage userdata vendor ...@@ -56,7 +59,7 @@ bin etc proc storage userdata vendor
dev lib sdcard system usr dev lib sdcard system usr
``` ```
**示例 2** 用 rm -r 删除非空目录 testpath **示例2** 用 rm -r 删除非空目录 testpath
``` ```
......
...@@ -13,7 +13,7 @@ rmdir [_-p_] [_dirname..._] ...@@ -13,7 +13,7 @@ rmdir [_-p_] [_dirname..._]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -39,7 +39,7 @@ rmdir [_-p_] [_dirname..._] ...@@ -39,7 +39,7 @@ rmdir [_-p_] [_dirname..._]
## 输出说明 ## 输出说明
**示例:**删除一个名为 dir 的目录 **示例** 删除一个名为 dir 的目录
``` ```
......
...@@ -13,7 +13,7 @@ statfs [_directory_] ...@@ -13,7 +13,7 @@ statfs [_directory_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -31,7 +31,7 @@ statfs [_directory_] ...@@ -31,7 +31,7 @@ statfs [_directory_]
statfs /nfs statfs /nfs
**示例**statfs输出说明 **示例** statfs输出说明
``` ```
OHOS # statfs ./nfs OHOS # statfs ./nfs
......
...@@ -13,7 +13,7 @@ sync ...@@ -13,7 +13,7 @@ sync
## 参数说明 ## 参数说明
## 使用指南 ## 使用指南
...@@ -30,4 +30,4 @@ sync ...@@ -30,4 +30,4 @@ sync
## 输出说明 ## 输出说明
...@@ -18,7 +18,7 @@ touch [_filename_] ...@@ -18,7 +18,7 @@ touch [_filename_]
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | --------------------------- | -------- |
| --help | 查看touch命令支持的参数列表 | N/A | | --help | 查看touch命令支持的参数列表 | N/A |
| filename | 需要创建文件的名称。 | N/A | | filename | 需要创建文件的名称。 | N/A |
...@@ -28,9 +28,13 @@ touch [_filename_] ...@@ -28,9 +28,13 @@ touch [_filename_]
- touch命令用来创建一个空文件,该文件可读写。 - touch命令用来创建一个空文件,该文件可读写。
- 使用touch命令允许一次创建多个文件。 - 使用touch命令允许一次创建多个文件。
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:** > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:**
> 在系统重要资源路径下使用touch命令创建文件,会对系统造成死机等未知影响,如在/dev路径下执行touch uartdev-0,会产生系统卡死现象。 > 在系统重要资源路径下使用touch命令创建文件,会对系统造成死机等未知影响,如在/dev路径下执行touch uartdev-0,会产生系统卡死现象。
## 特殊说明
--help参数以及同时创建多个文件,shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
......
...@@ -13,10 +13,10 @@ umount [_-a [-t TYPE]_] [_dir_] ...@@ -13,10 +13,10 @@ umount [_-a [-t TYPE]_] [_dir_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ------ | ------------------------------------------------------------ | -------------------------- |
| --help | 查看umount命令支持的参数列表。 | N/A | | --help | 查看umount命令支持的参数列表。 | N/A |
| -a | 卸载所有已挂载的目录。 | N/A | | -a | 卸载所有已挂载的目录。 | N/A |
| -t | 同-a选项一起使用,限制-a的卸载范围,只卸载-t所指定的文件系统类型的挂载目录。 | N/A | | -t | 同-a选项一起使用,限制-a的卸载范围,只卸载-t所指定的文件系统类型的挂载目录。 | N/A |
...@@ -27,6 +27,9 @@ umount [_-a [-t TYPE]_] [_dir_] ...@@ -27,6 +27,9 @@ umount [_-a [-t TYPE]_] [_dir_]
umount后加上需要卸载的指定文件系统的目录,即将指定文件系统卸载。 umount后加上需要卸载的指定文件系统的目录,即将指定文件系统卸载。
## 特殊说明
参数shell端暂不支持。切换mksh版本可全支持,方法:cd bin; ./mksh。
## 使用实例 ## 使用实例
...@@ -41,7 +44,7 @@ umount后加上需要卸载的指定文件系统的目录,即将指定文件 ...@@ -41,7 +44,7 @@ umount后加上需要卸载的指定文件系统的目录,即将指定文件
将已在./nfs挂载的文件系统卸载掉 将已在./nfs挂载的文件系统卸载掉
**示例 1** umount输出示例 **示例1** umount输出示例
``` ```
...@@ -49,7 +52,7 @@ OHOS:/$ umount ./nfs/ ...@@ -49,7 +52,7 @@ OHOS:/$ umount ./nfs/
umount ok umount ok
``` ```
**示例 2** 卸载所有已挂载的nfs类型的目录 **示例2** 卸载所有已挂载的nfs类型的目录
``` ```
......
...@@ -13,12 +13,12 @@ writeproc &lt;_data_&gt; &gt;&gt; /proc/&lt;_filename_&gt; ...@@ -13,12 +13,12 @@ writeproc &lt;_data_&gt; &gt;&gt; /proc/&lt;_filename_&gt;
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 |
| -------- | -------- | -------- | | -------- | ---------------------------------------------------------- |
| data | 要输入的字符串,以空格为结束符,如需输入空格,请用""包裹。 | N/A | | data | 要输入的字符串,以空格为结束符,如需输入空格,请用""包裹。 |
| filename | data要传入的proc文件。 | N/A | | filename | data要传入的proc文件。 |
## 使用指南 ## 使用指南
...@@ -28,6 +28,9 @@ proc文件实现自身的write函数,调用writeproc命令后会将入参传 ...@@ -28,6 +28,9 @@ proc文件实现自身的write函数,调用writeproc命令后会将入参传
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> procfs不支持多线程访问。 > procfs不支持多线程访问。
## 特殊说明
shell端暂不支持。
## 使用实例 ## 使用实例
...@@ -36,11 +39,13 @@ proc文件实现自身的write函数,调用writeproc命令后会将入参传 ...@@ -36,11 +39,13 @@ proc文件实现自身的write函数,调用writeproc命令后会将入参传
## 输出说明 ## 输出说明
```
OHOS \# writeproc test &gt;&gt; /proc/uptime OHOS \# writeproc test &gt;&gt; /proc/uptime
[INFO]write buf is: test [INFO]write buf is: test
test &gt;&gt; /proc/uptime test &gt;&gt; /proc/uptime
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> uptime proc文件临时实现write函数,INFO日志为实现的测试函数打印的日志。 > uptime proc文件临时实现write函数,INFO日志为实现的测试函数打印的日志。
\ No newline at end of file
...@@ -8,17 +8,18 @@ ...@@ -8,17 +8,18 @@
在中断有响应的情况下,可以通过魔法键查看task信息中 cpup(CPU占用率)看是哪个任务长时间占用CPU导致系统其他任务无响应(一般为比较高优先级任务一直抢占CPU,导致低优先级任务无响应)。 在中断有响应的情况下,可以通过魔法键查看task信息中 cpup(CPU占用率)看是哪个任务长时间占用CPU导致系统其他任务无响应(一般为比较高优先级任务一直抢占CPU,导致低优先级任务无响应)。
## 使用方法 ## 使用配置
魔法键依赖于宏LOSCFG_ENABLE_MAGICKEY,在kernel/liteos_a中输入make menuconfig命令。此时会弹出配置项,找到Debug选项并进入,在配置项中开启“Enable MAGIC KEY”:
1. 配置宏LOSCFG_ENABLE_MAGICKEY Debug ---&gt; Enable MAGIC KEY;若关闭该选项,则魔法键失效(默认为选中的)
魔法键依赖于宏LOSCFG_ENABLE_MAGICKEY,使用时通过menuconfig在配置项中开启“Enable MAGIC KEY”: > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 可以在menuconfig中,将光标移动到LOSCFG_ENABLE_MAGICKEY上,输入“?”,可以查看帮助信息。
Debug ---&gt; Enable MAGIC KEY;若关闭该选项,则魔法键失效。 ## 使用方法
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 可以在menuconfig中,将光标移动到LOSCFG_ENABLE_MAGICKEY上,输入“?”,查看帮助信息。
2. 输入“ctrl + r”键,打开魔法键检测功能。 1. 输入“ctrl + r”键,打开魔法键检测功能。
在连接UART或者USB转虚拟串口的情况下,输入“ctrl + r” 键,打开魔法键检测功能,输出 “Magic key on”;再输入一次后,则关闭魔法键检测功能,输出“Magic key off”。魔法键功能如下: 在连接UART或者USB转虚拟串口的情况下,输入“ctrl + r” 键,打开魔法键检测功能,输出 “Magic key on”;再输入一次后,则关闭魔法键检测功能,输出“Magic key off”。魔法键功能如下:
...@@ -30,5 +31,5 @@ ...@@ -30,5 +31,5 @@
- ctrl + e:系统进行简单完整性内存池检查,检查出错会输出相关错误信息,检查正常会输出“system memcheck over, all passed!”。 - ctrl + e:系统进行简单完整性内存池检查,检查出错会输出相关错误信息,检查正常会输出“system memcheck over, all passed!”。
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:** > **须知:**
> 魔法键检测功能打开情况下,如果需要通过UART或者USB转虚拟串口输入特殊字符需避免与魔法键值重复,否则魔法键会被误触发,而原有设计功能可能出现错误。 > 魔法键检测功能打开情况下,如果需要通过UART或者USB转虚拟串口输入特殊字符需避免与魔法键值重复,否则魔法键会被误触发,而原有设计功能可能出现错误。
\ No newline at end of file
...@@ -17,7 +17,7 @@ arp [_-i IF_] -d _IPADDR_ ...@@ -17,7 +17,7 @@ arp [_-i IF_] -d _IPADDR_
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -40,7 +40,7 @@ arp [_-i IF_] -d _IPADDR_ ...@@ -40,7 +40,7 @@ arp [_-i IF_] -d _IPADDR_
输入arp 输入arp
**示例:**打印整个 ARP 缓存表 **示例** 打印整个 ARP 缓存表
``` ```
OHOS # arp OHOS # arp
...@@ -48,7 +48,7 @@ Address HWaddress Iface Type ...@@ -48,7 +48,7 @@ Address HWaddress Iface Type
192.168.1.10 E6:2B:99:2C:4B:20 eth0 static 192.168.1.10 E6:2B:99:2C:4B:20 eth0 static
``` ```
**表2** 参数说明 **表2** 参数说明
| 参数 | 说明 | | 参数 | 说明 |
| -------- | -------- | | -------- | -------- |
......
...@@ -15,10 +15,10 @@ ...@@ -15,10 +15,10 @@
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | ------------------------------- | -------------------------------------------- | ---------------- |
| -h&nbsp;\|&nbsp;--help | 查看dhclient命令支持的参数列表,及使用方式。 | N/A | | -h&nbsp;\|&nbsp;--help | 查看dhclient命令支持的参数列表,及使用方式。 | N/A |
| &lt;netif&nbsp;name&gt; | 启动对应网卡的dhcp请求。 | 网卡名字,eth0。 | | &lt;netif&nbsp;name&gt; | 启动对应网卡的dhcp请求。 | 网卡名字,eth0。 |
| -x&nbsp;&lt;netif&nbsp;name&gt; | 关闭对应网卡的dhcp功能。 | 网卡名字,eth0。 | | -x&nbsp;&lt;netif&nbsp;name&gt; | 关闭对应网卡的dhcp功能。 | 网卡名字,eth0。 |
...@@ -32,10 +32,13 @@ ...@@ -32,10 +32,13 @@
- dhclient -x eth0 - dhclient -x eth0
## 特殊说明
shell端暂不支持。
## 使用实例 ## 使用实例
**示例1:**启动网卡eth0的dhcp请求 **示例1** 启动网卡eth0的dhcp请求
``` ```
...@@ -50,8 +53,7 @@ OHOS:/$ ...@@ -50,8 +53,7 @@ OHOS:/$
``` ```
**示例2:**关闭网卡eth0的dhcp请求 **示例2** 关闭网卡eth0的dhcp请求
``` ```
......
...@@ -27,7 +27,7 @@ option: ...@@ -27,7 +27,7 @@ option:
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -65,7 +65,7 @@ option: ...@@ -65,7 +65,7 @@ option:
## 输出说明 ## 输出说明
- **示例1:**设置网络参数 - **示例1** 设置网络参数
``` ```
OHOS:/$ ifconfig eth0 192.168.100.31 netmask 255.255.255.0 gateway 192.168.100.1 hw ether 00:49:cb:6c:a1:31 OHOS:/$ ifconfig eth0 192.168.100.31 netmask 255.255.255.0 gateway 192.168.100.1 hw ether 00:49:cb:6c:a1:31
...@@ -92,7 +92,7 @@ option: ...@@ -92,7 +92,7 @@ option:
| Default | 有这项说明此网卡连接到默认网关。 | | Default | 有这项说明此网卡连接到默认网关。 |
| Link&nbsp;UP/Down | 网卡连接状态。 | | Link&nbsp;UP/Down | 网卡连接状态。 |
- **示例2:**获取协议栈统计信息 - **示例2** 获取协议栈统计信息
``` ```
OHOS # ifconfig -a OHOS # ifconfig -a
...@@ -104,7 +104,7 @@ option: ...@@ -104,7 +104,7 @@ option:
输出的各参数说明如下表所示: 输出的各参数说明如下表所示:
**表3** ifconfig -a 参数说明 **表3** ifconfig -a 参数说明
| 参数 | 说明 | | 参数 | 说明 |
| -------- | -------- | | -------- | -------- |
...@@ -119,7 +119,7 @@ option: ...@@ -119,7 +119,7 @@ option:
| TX&nbsp;overrun | 暂未使用。 | | TX&nbsp;overrun | 暂未使用。 |
| TX&nbsp;bytes | IP层已正常发送或者转发的数据包的总长度。 | | TX&nbsp;bytes | IP层已正常发送或者转发的数据包的总长度。 |
- **示例3**设置IPv6的地址信息 - **示例3** 设置IPv6的地址信息
``` ```
OHOS:/$ ifconfig eth0 inet6 add 2001:a:b:c:d:e:f:d OHOS:/$ ifconfig eth0 inet6 add 2001:a:b:c:d:e:f:d
...@@ -139,7 +139,7 @@ option: ...@@ -139,7 +139,7 @@ option:
HWaddr 66:2f:e5:bd:24:e6 MTU:1500 Running Default Link UP HWaddr 66:2f:e5:bd:24:e6 MTU:1500 Running Default Link UP
``` ```
- **示例4**删除IPv6的地址信息 - **示例4** 删除IPv6的地址信息
``` ```
OHOS:/$ ifconfig eth0 inet6 del 2001:a:b:c:d:e:f:d OHOS:/$ ifconfig eth0 inet6 del 2001:a:b:c:d:e:f:d
......
...@@ -18,7 +18,7 @@ ipdebug ...@@ -18,7 +18,7 @@ ipdebug
## 输出说明 ## 输出说明
**示例:**ipdebug打印信息如下: **示例** ipdebug打印信息如下:
``` ```
OHOS # ipdebug OHOS # ipdebug
......
...@@ -20,6 +20,9 @@ netstat ...@@ -20,6 +20,9 @@ netstat
netstat netstat
## 特殊说明
shell端暂不支持。
## 使用实例 ## 使用实例
...@@ -28,7 +31,7 @@ netstat ...@@ -28,7 +31,7 @@ netstat
## 输出说明 ## 输出说明
**示例:**netstat 打印信息 **示例** netstat 打印信息
``` ```
OHOS # netstat OHOS # netstat
...@@ -46,10 +49,10 @@ udp 0 0 127.0.0.1:62180 127.0.0.1:62179 ...@@ -46,10 +49,10 @@ udp 0 0 127.0.0.1:62180 127.0.0.1:62179
udp 0 0 127.0.0.1:62178 127.0.0.1:62177 udp 0 0 127.0.0.1:62178 127.0.0.1:62177
``` ```
**表1** 输出说明 **表1** 输出说明
| 输出 | 说明 | | 输出 | 说明 |
| -------- | -------- | | -------------------- | ------------------------------------------------------------ |
| Proto | 协议类型。 | | Proto | 协议类型。 |
| Recv-Q | 未被用户读取的数据量。<br/>对于Listen&nbsp;TCP,此值为已完成三次握手,但是未被用户accept的TCP连接的数量。 | | Recv-Q | 未被用户读取的数据量。<br/>对于Listen&nbsp;TCP,此值为已完成三次握手,但是未被用户accept的TCP连接的数量。 |
| Send-Q | 对TCP连接,已发送但未确认的数据量。<br/>对UDP连接,由于IP地址解析未完成而缓存的数据量。 | | Send-Q | 对TCP连接,已发送但未确认的数据量。<br/>对UDP连接,由于IP地址解析未完成而缓存的数据量。 |
......
...@@ -13,7 +13,7 @@ ntpdate [_SERVER_IP1_] [_SERVER_IP2_]... ...@@ -13,7 +13,7 @@ ntpdate [_SERVER_IP1_] [_SERVER_IP2_]...
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
......
...@@ -13,7 +13,7 @@ ping _[-4] [-c cnt] [-f] [-i interval] [-q] [-s size] &lt;IP&gt;_ ...@@ -13,7 +13,7 @@ ping _[-4] [-c cnt] [-f] [-i interval] [-q] [-s size] &lt;IP&gt;_
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -45,7 +45,7 @@ ping _[-4] [-c cnt] [-f] [-i interval] [-q] [-s size] &lt;IP&gt;_ ...@@ -45,7 +45,7 @@ ping _[-4] [-c cnt] [-f] [-i interval] [-q] [-s size] &lt;IP&gt;_
## 输出说明 ## 输出说明
**示例:**ping tftp 服务器地址 **示例** ping tftp 服务器地址
``` ```
OHOS:/$ ping 192.168.1.3 OHOS:/$ ping 192.168.1.3
......
...@@ -13,11 +13,11 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_ ...@@ -13,11 +13,11 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | --------------------- | ----------------------------------- | -------- |
| -c&nbsp;count | 执行的次数,不带本参数则默认为4次。 | 1~65535 | | -c&nbsp;count | 执行的次数,不带本参数则默认为4次。 | [1, 65535] |
| -I&nbsp;interface | 指定网卡执行IPv6&nbsp;ping操作。 | N/A | | -I&nbsp;interface | 指定网卡执行IPv6&nbsp;ping操作。 | N/A |
| -I&nbsp;sourceAddress | 指定源IPv6地址执行ping操作。 | N/A | | -I&nbsp;sourceAddress | 指定源IPv6地址执行ping操作。 | N/A |
| destination | 目标主机地址。 | N/A | | destination | 目标主机地址。 | N/A |
...@@ -31,6 +31,9 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_ ...@@ -31,6 +31,9 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_
- 命令需要启动TCP/IP协议栈后才能使用。 - 命令需要启动TCP/IP协议栈后才能使用。
## 特殊说明
shell端暂不支持。
## 使用实例 ## 使用实例
...@@ -45,7 +48,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_ ...@@ -45,7 +48,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_
## 输出说明 ## 输出说明
1. 输入ping6 2001:a:b:c:d:e:f:b 1. 输入`ping6 2001:a:b:c:d:e:f:b`
``` ```
OHOS # ping6 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. OHOS # ping6 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data.
...@@ -58,7 +61,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_ ...@@ -58,7 +61,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_
rtt min/avg/max = 0/0.00/0 ms rtt min/avg/max = 0/0.00/0 ms
``` ```
2. 输入 ping6 -c 3 2001:a:b:c:d:e:f:b 指定3次进行网络测试 2. 输入 `ping6 -c 3 2001:a:b:c:d:e:f:b` 指定3次进行网络测试
``` ```
OHOS # ping6 -c 3 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. OHOS # ping6 -c 3 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data.
...@@ -70,7 +73,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_ ...@@ -70,7 +73,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_
rtt min/avg/max = 0/0.00/0 ms rtt min/avg/max = 0/0.00/0 ms
``` ```
3. 输入 ping6 -I eth0 2001:a:b:c:d:e:f:b 使用指定网卡接口eth0测试IPv6。 3. 输入 `ping6 -I eth0 2001:a:b:c:d:e:f:b` 使用指定网卡接口eth0测试IPv6。
``` ```
OHOS # ping6 -I eth0 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. OHOS # ping6 -I eth0 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data.
...@@ -82,7 +85,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_ ...@@ -82,7 +85,7 @@ ping6 _[-c count] [-I interface / sourceAddress] destination_
4 packets transmitted, 4 received, 0.00% packet loss, time 30msrtt min/avg/max = 0/2.50/10 ms 4 packets transmitted, 4 received, 0.00% packet loss, time 30msrtt min/avg/max = 0/2.50/10 ms
``` ```
4. 输入 ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b 使用指定的源IPv6地址2001:a:b:c:d:e:f:d进行测试。 4. 输入 `ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b` 使用指定的源IPv6地址2001:a:b:c:d:e:f:d进行测试。
``` ```
OHOS # ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data. OHOS # ping6 -I 2001:a:b:c:d:e:f:d 2001:a:b:c:d:e:f:b PING 2001:A:B:C:D:E:F:B with 56 bytes of data.
......
...@@ -13,7 +13,7 @@ telnet [_on | off_] ...@@ -13,7 +13,7 @@ telnet [_on | off_]
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -37,7 +37,7 @@ telnet [_on | off_] ...@@ -37,7 +37,7 @@ telnet [_on | off_]
## 输出说明 ## 输出说明
**示例:**输入 telnet on **示例** 输入 telnet on
``` ```
......
...@@ -15,7 +15,7 @@ tftp命令可以从TFTP服务器上下载文件。 ...@@ -15,7 +15,7 @@ tftp命令可以从TFTP服务器上下载文件。
## 参数说明 ## 参数说明
**表1** 参数说明 **表1** 参数说明
| 参数 | 参数说明 | 取值范围 | | 参数 | 参数说明 | 取值范围 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
......
...@@ -88,7 +88,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -88,7 +88,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
``` ```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 预置的Trace事件及参数均可以通过上述方式进行裁剪,参数详见kernel\include\los_trace.h > 预置的Trace事件及参数均可以通过上述方式进行裁剪,参数详见 [kernel\include\los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h)
- Trace Mask事件过滤接口LOS_TraceEventMaskSet(UINT32 mask),其入参mask仅高28位生效(对应LOS_TRACE_MASK中某模块的使能位),仅用于模块的过滤,暂不支持针对某个特定事件的细粒度过滤。例如:LOS_TraceEventMaskSet(0x202),则实际设置生效的mask为0x200(TRACE_QUE_FLAG),QUE模块的所有事件均会被采集。一般建议使用的方法为: LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG); - Trace Mask事件过滤接口LOS_TraceEventMaskSet(UINT32 mask),其入参mask仅高28位生效(对应LOS_TRACE_MASK中某模块的使能位),仅用于模块的过滤,暂不支持针对某个特定事件的细粒度过滤。例如:LOS_TraceEventMaskSet(0x202),则实际设置生效的mask为0x200(TRACE_QUE_FLAG),QUE模块的所有事件均会被采集。一般建议使用的方法为: LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);
...@@ -101,7 +101,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -101,7 +101,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
- 针对中断事件的Trace, 提供中断号过滤,用于解决某些场景下特定中断号频繁触发导致其他事件被覆盖的情况,用户可自定义中断过滤的规则, - 针对中断事件的Trace, 提供中断号过滤,用于解决某些场景下特定中断号频繁触发导致其他事件被覆盖的情况,用户可自定义中断过滤的规则,
示例如下: 示例如下:
``` ```c
BOOL Example_HwiNumFilter(UINT32 hwiNum) BOOL Example_HwiNumFilter(UINT32 hwiNum)
{ {
if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) {
...@@ -117,7 +117,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -117,7 +117,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
### 用户态 ### 用户态
新增trace字符设备,位于"/dev/trace",通过对设备节点的read、write、ioctl,实现用户态trace的读写和控制: 新增trace字符设备,位于"/dev/trace"通过对设备节点的read、write、ioctl,实现用户态trace的读写和控制:
- read: 用户态读取Trace记录数据 - read: 用户态读取Trace记录数据
...@@ -126,7 +126,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -126,7 +126,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
- ioctl: 用户态Trace控制操作,包括 - ioctl: 用户态Trace控制操作,包括
``` ```c
#define TRACE_IOC_MAGIC 'T' #define TRACE_IOC_MAGIC 'T'
#define TRACE_START _IO(TRACE_IOC_MAGIC, 1) #define TRACE_START _IO(TRACE_IOC_MAGIC, 1)
#define TRACE_STOP _IO(TRACE_IOC_MAGIC, 2) #define TRACE_STOP _IO(TRACE_IOC_MAGIC, 2)
...@@ -148,7 +148,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -148,7 +148,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
开启Trace调测的典型流程如下: 开启Trace调测的典型流程如下:
1. 配置Trace模块相关宏。 1. 配置Trace模块相关宏。
配置Trace控制宏LOSCFG_KERNEL_TRACE,默认关,在kernel/liteos_a目录下执行 make update_config命令配置"Kernel-&gt;Enable Hook Feature-&gt;Enable Trace Feature"中打开: 配置Trace控制宏LOSCFG_KERNEL_TRACE,默认关,在 kernel/liteos_a 目录下执行 make update_config 命令配置 "Kernel-&gt;Enable Hook Feature-&gt;Enable Trace Feature" 中打开:
| 配置项 | menuconfig选项 | 含义 | 设置值 | | 配置项 | menuconfig选项 | 含义 | 设置值 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -156,7 +156,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -156,7 +156,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
| LOSCFG_RECORDER_MODE_OFFLINE | Trace&nbsp;work&nbsp;mode&nbsp;-&gt;Offline&nbsp;mode | Trace工作模式为离线模式 | YES/NO | | LOSCFG_RECORDER_MODE_OFFLINE | Trace&nbsp;work&nbsp;mode&nbsp;-&gt;Offline&nbsp;mode | Trace工作模式为离线模式 | YES/NO |
| LOSCFG_RECORDER_MODE_ONLINE | Trace&nbsp;work&nbsp;mode&nbsp;-&gt;Online&nbsp;mode | Trace工作模式为在线模式 | YES/NO | | LOSCFG_RECORDER_MODE_ONLINE | Trace&nbsp;work&nbsp;mode&nbsp;-&gt;Online&nbsp;mode | Trace工作模式为在线模式 | YES/NO |
| LOSCFG_TRACE_CLIENT_INTERACT | Enable&nbsp;Trace&nbsp;Client&nbsp;Visualization&nbsp;and&nbsp;Control | 使能与Trace&nbsp;IDE&nbsp;(dev&nbsp;tools)的交互,包括数据可视化和流程控制 | YES/NO | | LOSCFG_TRACE_CLIENT_INTERACT | Enable&nbsp;Trace&nbsp;Client&nbsp;Visualization&nbsp;and&nbsp;Control | 使能与Trace&nbsp;IDE&nbsp;(dev&nbsp;tools)的交互,包括数据可视化和流程控制 | YES/NO |
| LOSCFG_TRACE_FRAME_CORE_MSG | Enable&nbsp;Record&nbsp;more&nbsp;extended&nbsp;content&nbsp;-<br>&gt;Record&nbsp;cpuid,&nbsp;hardware&nbsp;interrupt<br>&nbsp;status,&nbsp;task&nbsp;lock&nbsp;status | 记录CPUID、中断状态、锁任务状态 | YES/NO | | LOSCFG_TRACE_FRAME_CORE_MSG | Enable&nbsp;Record&nbsp;more&nbsp;extended content<br>->Record&nbsp;cpuid,&nbsp;hardware&nbsp;interrupt status,&nbsp;task&nbsp;lock&nbsp;status | 记录CPUID、中断状态、锁任务状态 | YES/NO |
| LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable&nbsp;Record&nbsp;more&nbsp;extended&nbsp;content<br>&nbsp;-&gt;Record&nbsp;event&nbsp;count,<br>&nbsp;which&nbsp;indicate&nbsp;the&nbsp;sequence&nbsp;of&nbsp;happend&nbsp;events | 记录事件的次序编号 | YES/NO | | LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable&nbsp;Record&nbsp;more&nbsp;extended&nbsp;content<br>&nbsp;-&gt;Record&nbsp;event&nbsp;count,<br>&nbsp;which&nbsp;indicate&nbsp;the&nbsp;sequence&nbsp;of&nbsp;happend&nbsp;events | 记录事件的次序编号 | YES/NO |
| LOSCFG_TRACE_FRAME_MAX_PARAMS | Record&nbsp;max&nbsp;params | 配置记录事件的最大参数个数 | INT | | LOSCFG_TRACE_FRAME_MAX_PARAMS | Record&nbsp;max&nbsp;params | 配置记录事件的最大参数个数 | INT |
| LOSCFG_TRACE_BUFFER_SIZE | Trace&nbsp;record&nbsp;buffer&nbsp;size | 配置Trace的缓冲区大小 | INT | | LOSCFG_TRACE_BUFFER_SIZE | Trace&nbsp;record&nbsp;buffer&nbsp;size | 配置Trace的缓冲区大小 | INT |
...@@ -165,7 +165,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -165,7 +165,7 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
3. (可选)调用LOS_TraceStop停止Trace后,清除缓冲区LOS_TraceReset(系统默认已启动trace)。 3. (可选)调用LOS_TraceStop停止Trace后,清除缓冲区LOS_TraceReset(系统默认已启动trace)。
4. (可选)调用LOS_TraceEventMaskSet设置需要追踪的事件掩码(系统默认的事件掩码仅使能中断与任务事件),事件掩码参见los_trace.h 中的LOS_TRACE_MASK定义。 4. (可选)调用LOS_TraceEventMaskSet设置需要追踪的事件掩码(系统默认的事件掩码仅使能中断与任务事件),事件掩码参见 [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h) 中的LOS_TRACE_MASK定义。
5. 在需要记录事件的代码起始点调用LOS_TraceStart。 5. 在需要记录事件的代码起始点调用LOS_TraceStart。
...@@ -203,10 +203,11 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以 ...@@ -203,10 +203,11 @@ LiteOS-A内核的Trace模块提供下面几种功能,接口详细信息可以
### 内核态示例代码 ### 内核态示例代码
该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。
实例代码如下: 实例代码如下:
``` ```c
#include "los_trace.h" #include "los_trace.h"
UINT32 g_traceTestTaskId; UINT32 g_traceTestTaskId;
VOID Example_Trace(VOID) VOID Example_Trace(VOID)
...@@ -227,18 +228,19 @@ VOID Example_Trace(VOID) ...@@ -227,18 +228,19 @@ VOID Example_Trace(VOID)
LOS_TraceStop(); LOS_TraceStop();
LOS_TraceRecordDump(FALSE); LOS_TraceRecordDump(FALSE);
} }
UINT32 Example_Trace_test(VOID){ UINT32 Example_Trace_test(VOID)
{
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S traceTestTask; TSK_INIT_PARAM_S traceTestTask;
/* 创建用于trace测试的任务 */ /* 创建用于trace测试的任务 */
memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S)); memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S));
traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace; traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace;
traceTestTask.pcName = "TestTraceTsk"; /* 测试任务名称 */ traceTestTask.pcName = "TestTraceTsk"; /* 测试任务名称 */
traceTestTask.uwStackSize = 0x800; traceTestTask.uwStackSize = 0x800; // 0x800: trace test task stacksize
traceTestTask.usTaskPrio = 5; traceTestTask.usTaskPrio = 5; // 5: trace test task priority
traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED; traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
ret = LOS_TaskCreate(&g_traceTestTaskId, &traceTestTask); ret = LOS_TaskCreate(&g_traceTestTaskId, &traceTestTask);
if(ret != LOS_OK){ if (ret != LOS_OK) {
dprintf("TraceTestTask create failed .\n"); dprintf("TraceTestTask create failed .\n");
return LOS_NOK; return LOS_NOK;
} }
...@@ -276,13 +278,13 @@ Index Time(cycles) EventType CurTask Identity params ...@@ -276,13 +278,13 @@ Index Time(cycles) EventType CurTask Identity params
输出的事件信息包括:发生时间、事件类型、事件发生在哪个任务中、事件操作的主体对象、事件的其他参数。 输出的事件信息包括:发生时间、事件类型、事件发生在哪个任务中、事件操作的主体对象、事件的其他参数。
- EventType:表示的具体事件可查阅头文件los_trace.h中的enum LOS_TRACE_TYPE。 - EventType:表示的具体事件可查阅头文件 [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h) 中的enum LOS_TRACE_TYPE。
- CurrentTask:表示当前运行在哪个任务中,值为taskid。 - CurrentTask:表示当前运行在哪个任务中,值为taskid。
- Identity:表示事件操作的主体对象,可查阅头文件los_trace.h中的\#TYPE\#_PARAMS。 - Identity:表示事件操作的主体对象,可查阅头文件 [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h) 中的\#TYPE\#_PARAMS。
- params:表示的事件参数可查阅头文件los_trace.h中的\#TYPE\#_PARAMS。 - params:表示的事件参数可查阅头文件 [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h) 中的\#TYPE\#_PARAMS。
下面以序号为0的输出项为例,进行说明。 下面以序号为0的输出项为例,进行说明。
...@@ -298,7 +300,7 @@ Index Time(cycles) EventType CurTask Identity params ...@@ -298,7 +300,7 @@ Index Time(cycles) EventType CurTask Identity params
- Identity和params的含义需要查看TASK_SWITCH_PARAMS宏定义: - Identity和params的含义需要查看TASK_SWITCH_PARAMS宏定义:
``` ```c
#define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \ #define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \
taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus
``` ```
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、踩内存分析以及backtrace功能等维测手段,可以提高用户态内存相关问题的定位效率。 Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、踩内存分析以及backtrace功能等维测手段,可以提高用户态内存相关问题的定位效率。
采用了对malloc/free接口进行插桩,保存关键节点信息,然后程序在申请和释放内存时进行内存节点完整性校验,最后在程序结束时通过统计节点信息得到内存统计信息并根据统计信息判断内存是否泄漏的设计思想 采用了对malloc/free接口进行插桩,保存关键节点信息,然后程序在申请和释放内存时进行内存节点完整性校验,最后在程序结束时通过统计节点信息得到内存统计信息并根据统计信息判断内存是否泄漏的设计思想
## 运行机制 ## 运行机制
...@@ -28,7 +28,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、 ...@@ -28,7 +28,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、
![zh-cn_image_0000001165890518](figures/zh-cn_image_0000001165890518.png) ![zh-cn_image_0000001165890518](figures/zh-cn_image_0000001165890518.png)
其中,TID表示线程ID;PID表示进程ID;ptr表示申请的内存地址;size表示申请的内存大小;lr[n]表示函数调用栈地址,变量n可以根据具体场景的需要进行配置。 其中,TID表示线程ID;PID表示进程ID;ptr表示申请的内存地址;size表示申请的内存大小;lr[n]表示函数调用栈地址,变量n的大小可以根据具体场景的需要进行配置。
释放内存时,将free等接口的入参指针与node的ptr字段进行匹配,如果相同则删除该内存节点控制块信息。 释放内存时,将free等接口的入参指针与node的ptr字段进行匹配,如果相同则删除该内存节点控制块信息。
...@@ -46,7 +46,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、 ...@@ -46,7 +46,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、
### 内存完整性检查 ### 内存完整性检查
- 使用malloc申请内存(小于等于0x1c000bytes时通过堆分配算法分配) - 使用malloc申请内存(小于等于0x1c000 bytes时通过堆分配算法分配)
用户程序申请堆内存时,在堆内存节点处添加校验值等信息,如果校验值异常,则很有可能是前一块堆内存使用越界导致的(目前无法识别校验值被野指针破坏的场景)。在内存申请、释放时校验内存节点校验值的正确性,若内存节点被破坏,校验失败时则输出tid、pid及当前被踩节点前一块堆内存申请时保存的调用栈信息,通过addr2line工具可获得具体的代码行信息,辅助用户解决问题。 用户程序申请堆内存时,在堆内存节点处添加校验值等信息,如果校验值异常,则很有可能是前一块堆内存使用越界导致的(目前无法识别校验值被野指针破坏的场景)。在内存申请、释放时校验内存节点校验值的正确性,若内存节点被破坏,校验失败时则输出tid、pid及当前被踩节点前一块堆内存申请时保存的调用栈信息,通过addr2line工具可获得具体的代码行信息,辅助用户解决问题。
**图4** node节点头信息添加校验值 **图4** node节点头信息添加校验值
...@@ -59,7 +59,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、 ...@@ -59,7 +59,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、
![zh-cn_image_0000001165890904](figures/zh-cn_image_0000001165890904.png) ![zh-cn_image_0000001165890904](figures/zh-cn_image_0000001165890904.png)
- 使用malloc申请内存(大于0x1c000bytes时通过mmap申请) - 使用malloc申请内存(大于0x1c000 bytes时通过mmap申请)
当malloc通过mmap申请大块内存时,在返回给用户使用的内存区间头和尾分别多申请一个页,一个页PAGE_SIZE当前为0x1000,这两个页分别通过mprotect接口设置权限为PROT_NONE(无可读可写权限),可以有效防止内存越界读写问题:越界读写数据时由于无读写权限而导致用户程序异常,根据异常调用栈信息可找到相应的代码逻辑。 当malloc通过mmap申请大块内存时,在返回给用户使用的内存区间头和尾分别多申请一个页,一个页PAGE_SIZE当前为0x1000,这两个页分别通过mprotect接口设置权限为PROT_NONE(无可读可写权限),可以有效防止内存越界读写问题:越界读写数据时由于无读写权限而导致用户程序异常,根据异常调用栈信息可找到相应的代码逻辑。
**图6** malloc通过mmap机制申请内存的内存布局 **图6** malloc通过mmap机制申请内存的内存布局
...@@ -119,7 +119,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、 ...@@ -119,7 +119,7 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、
代码功能:显式调用调测模块的相关接口对用户代码进行内存校验。 代码功能:显式调用调测模块的相关接口对用户代码进行内存校验。
``` ```c
#include <pthread.h> #include <pthread.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
...@@ -127,7 +127,8 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、 ...@@ -127,7 +127,8 @@ Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、
#define MALLOC_LEAK_SIZE 0x300 #define MALLOC_LEAK_SIZE 0x300
void func(void) { void func(void)
{
char *ptr = malloc(MALLOC_LEAK_SIZE); char *ptr = malloc(MALLOC_LEAK_SIZE);
memset(ptr, '3', MALLOC_LEAK_SIZE); memset(ptr, '3', MALLOC_LEAK_SIZE);
} }
...@@ -293,14 +294,15 @@ kill -37 <pid> # 检查堆内存头节点是否完整 ...@@ -293,14 +294,15 @@ kill -37 <pid> # 检查堆内存头节点是否完整
代码功能:构造内存问题利用命令行方式进行内存调测。 代码功能:构造内存问题利用命令行方式进行内存调测。
``` ```c
#include <pthread.h> #include <pthread.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#define MALLOC_LEAK_SIZE 0x300 #define MALLOC_LEAK_SIZE 0x300
void func(void) { void func(void)
{
char *ptr = malloc(MALLOC_LEAK_SIZE); char *ptr = malloc(MALLOC_LEAK_SIZE);
memset(ptr, '3', MALLOC_LEAK_SIZE); memset(ptr, '3', MALLOC_LEAK_SIZE);
} }
...@@ -504,7 +506,7 @@ Now using addr2line ... ...@@ -504,7 +506,7 @@ Now using addr2line ...
### UAF(Use after free) ### UAF(Use after free)
- 申请小块内存(不大于0x1c000字节 - 申请小块内存(不大于0x1c000 bytes
free之后: free之后:
读操作:读取free之后的内存大概率是魔术数字(0xFEFEFEFE) 读操作:读取free之后的内存大概率是魔术数字(0xFEFEFEFE)
...@@ -515,7 +517,7 @@ Now using addr2line ... ...@@ -515,7 +517,7 @@ Now using addr2line ...
写操作:无法校验。 写操作:无法校验。
- 申请大块内存(大于0x1c000) - 申请大块内存(大于0x1c000 bytes
堆内存由malloc通过调用mmap接口申请,free之后若仍访问该内存,则用户程序异常(该内存区间已被unmap)。 堆内存由malloc通过调用mmap接口申请,free之后若仍访问该内存,则用户程序异常(该内存区间已被unmap)。
...@@ -526,7 +528,8 @@ Double free时,用户程序将会异常退出。 ...@@ -526,7 +528,8 @@ Double free时,用户程序将会异常退出。
### 堆内存节点被踩 ### 堆内存节点被踩
- 申请小块内存(不大于0x1c000) - 申请小块内存(不大于0x1c000 bytes)
堆内存节点被踩时,用户程序将会异常退出,并输出破坏被踩节点的可能的堆内存申请调用栈,对于野指针踩内存情况无法校验出来。例如用户程序mem_check中存在堆内存越界踩的情况,利用命令行方式可以获得踩内存的可能的具体位置。 堆内存节点被踩时,用户程序将会异常退出,并输出破坏被踩节点的可能的堆内存申请调用栈,对于野指针踩内存情况无法校验出来。例如用户程序mem_check中存在堆内存越界踩的情况,利用命令行方式可以获得踩内存的可能的具体位置。
...@@ -541,7 +544,7 @@ Double free时,用户程序将会异常退出。 ...@@ -541,7 +544,7 @@ Double free时,用户程序将会异常退出。
可以通过调用栈解析脚本对调用栈信息进行解析。 可以通过调用栈解析脚本对调用栈信息进行解析。
- 申请大块内存(大于0x1c000) - 申请大块内存(大于0x1c000 bytes
堆内存由malloc通过mmap接口申请,申请得到的堆内存块前后各置一个size为PAGE_SIZE大小的区间,设置无读写权限,读写操作会触发用户程序异常。 堆内存由malloc通过mmap接口申请,申请得到的堆内存块前后各置一个size为PAGE_SIZE大小的区间,设置无读写权限,读写操作会触发用户程序异常。
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 基本概念 ## 基本概念
LMS全称为Lite Memory Sanitizer,是一种实时检测内存操作合法性的调测工具。LMS能够实时检测缓冲区溢出(buffer overflow),释放后使用(use after free) 和重复释放(double Free), 在异常发生的第一时间通知操作系统,结合backtrace等定位手段,能准确定位到产生内存问题的代码行,极大提升内存问题定位效率。 LMS全称为Lite Memory Sanitizer,是一种实时检测内存操作合法性的调测工具。LMS能够实时检测缓冲区溢出(buffer overflow),释放后使用(use after free) 和重复释放(double free), 在异常发生的第一时间通知操作系统,结合backtrace等定位手段,能准确定位到产生内存问题的代码行,极大提升内存问题定位效率。
OpenHarmony LiteOS-A内核的LMS模块提供下面几种功能: OpenHarmony LiteOS-A内核的LMS模块提供下面几种功能:
...@@ -20,7 +20,7 @@ OpenHarmony LiteOS-A内核的LMS模块提供下面几种功能: ...@@ -20,7 +20,7 @@ OpenHarmony LiteOS-A内核的LMS模块提供下面几种功能:
LMS使用影子内存映射标记系统内存的状态,一共可标记为三个状态:可读写,不可读写,已释放。影子内存存放在内存池的尾部。 LMS使用影子内存映射标记系统内存的状态,一共可标记为三个状态:可读写,不可读写,已释放。影子内存存放在内存池的尾部。
- 内存从堆上申请后,会将数据区的影子内存设置为“可读写”状态,并将头点区的影子内存设置为“不可读写”状态。 - 内存从堆上申请后,会将数据区的影子内存设置为“可读写”状态,并将头点区的影子内存设置为“不可读写”状态。
- 内存在堆上被释放时,会将被释放内存的影子内存设置为“已释放”状态。 - 内存在堆上被释放时,会将被释放内存的影子内存设置为“已释放”状态。
...@@ -105,14 +105,15 @@ OpenHarmony LiteOS-A内核的LMS模块提供下面几种功能,接口详细信 ...@@ -105,14 +105,15 @@ OpenHarmony LiteOS-A内核的LMS模块提供下面几种功能,接口详细信
2. 构造内存溢出错误和释放后使用错误。 2. 构造内存溢出错误和释放后使用错误。
3. 添加-fsanitize=kernel-address后编译执行,观察输出结果 3. 添加-fsanitize=kernel-address后编译执行,观察输出结果
#### 内核态示例代码 #### 内核态示例代码
该示例代码的测试函数可以加在 kernel /liteos_a/testsuites /kernel /src /osTest.c 中的 TestTaskEntry 中进行测试。
实例代码如下: 实例代码如下:
``` ```c
#define PAGE_SIZE (0x1000U) #define PAGE_SIZE (0x1000U)
#define INDEX_MAX 20 #define INDEX_MAX 20
UINT32 g_lmsTestTaskId; UINT32 g_lmsTestTaskId;
...@@ -138,7 +139,7 @@ static VOID LmsTestUseAfterFree(VOID) ...@@ -138,7 +139,7 @@ static VOID LmsTestUseAfterFree(VOID)
PRINTK("\n######%s start ######\n", __FUNCTION__); PRINTK("\n######%s start ######\n", __FUNCTION__);
UINT32 i; UINT32 i;
CHAR *str = (CHAR *)LOS_MemAlloc(g_testLmsPool, INDEX_MAX); CHAR *str = (CHAR *)LOS_MemAlloc(g_testLmsPool, INDEX_MAX);
LOS_MemFree(g_testLmsPool, str); (VOID)LOS_MemFree(g_testLmsPool, str);
PRINTK("str[%2d]=0x%2x ", 0, str[0]); /* trigger use after free at str[0] */ PRINTK("str[%2d]=0x%2x ", 0, str[0]); /* trigger use after free at str[0] */
PRINTK("\n######%s stop ######\n", __FUNCTION__); PRINTK("\n######%s stop ######\n", __FUNCTION__);
} }
...@@ -148,18 +149,19 @@ VOID LmsTestCaseTask(VOID) ...@@ -148,18 +149,19 @@ VOID LmsTestCaseTask(VOID)
LmsTestOsmallocOverflow(); LmsTestOsmallocOverflow();
LmsTestUseAfterFree(); LmsTestUseAfterFree();
} }
UINT32 Example_Lms_test(VOID){ UINT32 Example_Lms_test(VOID)
{
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S lmsTestTask; TSK_INIT_PARAM_S lmsTestTask;
/* 创建用于lms测试的任务 */ /* 创建用于lms测试的任务 */
memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S)); memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S));
lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask; lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask;
lmsTestTask.pcName = "TestLmsTsk"; /* 测试任务名称 */ lmsTestTask.pcName = "TestLmsTsk"; /* 测试任务名称 */
lmsTestTask.uwStackSize = 0x800; lmsTestTask.uwStackSize = 0x800; // 0x800: lms test task stack size
lmsTestTask.usTaskPrio = 5; lmsTestTask.usTaskPrio = 5; // 5: lms test task priority
lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED; lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
ret = LOS_TaskCreate(&g_lmsTestTaskId, &lmsTestTask); ret = LOS_TaskCreate(&g_lmsTestTaskId, &lmsTestTask);
if(ret != LOS_OK){ if (ret != LOS_OK) {
PRINT_ERR("LmsTestTask create failed .\n"); PRINT_ERR("LmsTestTask create failed .\n");
return LOS_NOK; return LOS_NOK;
} }
...@@ -257,7 +259,7 @@ str[ 0]=0x 0 ...@@ -257,7 +259,7 @@ str[ 0]=0x 0
### 用户态开发流程 ### 用户态开发流程
在待检测的app编译脚本中,添加如下参数即可, 完整示例可参见/kernel/liteos_a/apps/lms/BUILD.gn 在待检测的app编译脚本中,添加如下参数即可, 完整示例可参见 [/kernel/liteos_a/apps/lms/BUILD.gn](https://gitee.com/openharmony/kernel_liteos_a/blob/master/apps/lms/BUILD.gn)
``` ```
...@@ -308,14 +310,14 @@ if ("$ohos_build_compiler_specified" == "gcc") { ...@@ -308,14 +310,14 @@ if ("$ohos_build_compiler_specified" == "gcc") {
1. 构造内存溢出错误和释放后使用错误。 1. 构造内存溢出错误和释放后使用错误。
2. 添加对应编译选项后,重新编译执行 2. 添加对应编译选项后,重新编译执行
#### 用户态示例代码 #### 用户态示例代码
实例代码如下: 实例代码如下:
``` ```c
static void BufWriteTest(void *buf, int start, int end) static void BufWriteTest(void *buf, int start, int end)
{ {
for (int i = start; i <= end; i++) { for (int i = start; i <= end; i++) {
...@@ -332,7 +334,7 @@ static void BufReadTest(void *buf, int start, int end) ...@@ -332,7 +334,7 @@ static void BufReadTest(void *buf, int start, int end)
static void LmsMallocTest(void) static void LmsMallocTest(void)
{ {
printf("\n-------- LmsMallocTest Start --------\n"); printf("\n-------- LmsMallocTest Start --------\n");
char *buf = (char *)malloc(16); char *buf = (char *)malloc(16); // 16: buffer size for test
BufReadTest(buf, -1, 16); BufReadTest(buf, -1, 16);
free(buf); free(buf);
printf("\n-------- LmsMallocTest End --------\n"); printf("\n-------- LmsMallocTest End --------\n");
...@@ -340,7 +342,7 @@ static void LmsMallocTest(void) ...@@ -340,7 +342,7 @@ static void LmsMallocTest(void)
static void LmsFreeTest(void) static void LmsFreeTest(void)
{ {
printf("\n-------- LmsFreeTest Start --------\n"); printf("\n-------- LmsFreeTest Start --------\n");
char *buf = (char *)malloc(16); char *buf = (char *)malloc(16); // 16: buffer size for test
free(buf); free(buf);
BufReadTest(buf, 1, 1); BufReadTest(buf, 1, 1);
free(buf); free(buf);
...@@ -349,7 +351,7 @@ static void LmsFreeTest(void) ...@@ -349,7 +351,7 @@ static void LmsFreeTest(void)
int main(int argc, char * const * argv) int main(int argc, char * const * argv)
{ {
printf("\n############### Lms Test start ###############\n"); printf("\n############### Lms Test start ###############\n");
char *tmp = (char *)malloc(5000); char *tmp = (char *)malloc(5000); // 5000: temp buffer size
LmsMallocTest(); LmsMallocTest();
LmsFreeTest(); LmsFreeTest();
printf("\n############### Lms Test End ###############\n"); printf("\n############### Lms Test End ###############\n");
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 内核启动流程 ## 内核启动流程
内核启动流程包含汇编启动阶段和C语言启动阶段2部分,如图1所示。汇编启动阶段完成CPU初始设置,关闭dcache/icache,使能FPU及neon,设置MMU建立虚实地址映射,设置系统栈,清理bss段,调用C语言main函数等。C语言启动阶段包含OsMain函数及开始调度等,其中如上图所示,OsMain函数用于内核基础初始化和架构、板级初始化等,其整体由内核启动框架主导初始化流程,图中右边区域为启动框架中可接受外部模块注册启动的阶段,各个阶段的说明如下表1所示。 内核启动流程包含汇编启动阶段和C语言启动阶段2部分,如图1所示。汇编启动阶段完成CPU初始设置,关闭dcache/icache,使能FPU及neon,设置MMU建立虚实地址映射,设置系统栈,清理bss段,调用C语言main函数等。C语言启动阶段包含OsMain函数及开始调度等,其中如图1所示,OsMain函数用于内核基础初始化和架构、板级初始化等,其整体由内核启动框架主导初始化流程,图中右边区域为启动框架中可接受外部模块注册启动的阶段,各个阶段的说明如下表1所示。
**图1** 内核启动流程图 **图1** 内核启动流程图
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
| LOS_INIT_LEVEL_KMOD_BASIC | 内核基础模块初始化<br/>说明:内核可拆卸的基础模块初始化<br/>例如:VFS初始化 | | LOS_INIT_LEVEL_KMOD_BASIC | 内核基础模块初始化<br/>说明:内核可拆卸的基础模块初始化<br/>例如:VFS初始化 |
| LOS_INIT_LEVEL_KMOD_EXTENDED | 内核扩展模块初始化<br/>说明:内核可拆卸的扩展模块初始化<br/>例如:系统调用初始化、ProcFS初始化、Futex初始化、HiLog初始化、HiEvent初始化、LiteIPC初始化 | | LOS_INIT_LEVEL_KMOD_EXTENDED | 内核扩展模块初始化<br/>说明:内核可拆卸的扩展模块初始化<br/>例如:系统调用初始化、ProcFS初始化、Futex初始化、HiLog初始化、HiEvent初始化、LiteIPC初始化 |
| LOS_INIT_LEVEL_KMOD_TASK | 内核任务创建<br/>说明:进行内核任务的创建(内核任务,软件定时器任务)<br/>例如:资源回收系统常驻任务的创建、SystemInit任务创建、CPU占用率统计任务创建 | | LOS_INIT_LEVEL_KMOD_TASK | 内核任务创建<br/>说明:进行内核任务的创建(内核任务,软件定时器任务)<br/>例如:资源回收系统常驻任务的创建、SystemInit任务创建、CPU占用率统计任务创建 |
| LOS_INIT_LEVEL_FINISH | 内核初始化完成 |
## 编程样例 ## 编程样例
...@@ -38,7 +39,7 @@ ...@@ -38,7 +39,7 @@
``` ```c
/* 内核启动框架头文件 */ /* 内核启动框架头文件 */
#include "los_init.h" #include "los_init.h"
...... ......
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
使用链接脚本将如下init启动代码放置到系统镜像指定位置。 使用链接脚本将如下init启动代码放置到系统镜像指定位置。
``` ```c
#define LITE_USER_SEC_ENTRY __attribute__((section(".user.entry"))) #define LITE_USER_SEC_ENTRY __attribute__((section(".user.entry")))
LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args) LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args)
{ {
...@@ -27,6 +27,8 @@ LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args) ...@@ -27,6 +27,8 @@ LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args)
} }
``` ```
> 上述启动代码在 kernel/liteos_a/kernel/user/src/los_user_init.c 中,g_initPath 根据启动设置的不同,其值为 /dev/shm/init 或 /bin/init。
系统启动阶段,OsUserInitProcess启动init进程。具体过程如下: 系统启动阶段,OsUserInitProcess启动init进程。具体过程如下:
1. 由内核OsLoadUserInit加载上述代码。 1. 由内核OsLoadUserInit加载上述代码。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册